Program used to illustrate the syntax of variable definition:
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
// (1) Assign a radius
radius = 20;
// (2) Compute area
area = 3.14159 * radius * radius;
// (3) Print result
System.out.println(area);
}
}
|
DEMO: demo/02-elem-prog/04-vars/ComputeArea.java
|
Programming rules on variable definition:
|
DEMO: use BleuJ --- demo/02-elem-prog/04-vars/ComputeArea.java
|
Invalid identifiers: hello!, O'Neil, 3CPO --- Quiz: R2D2 ??
|
|
|
public class PrimeTypes
{
public static void main(String[] args)
{
double highPrec = 123.4567890123456789; // Put breakpoint here
float lowPrec = 123.4567890123456789f;
// float lowPrec = (float) 123.4567890123456789f;
int normalInt = 1234567890;
short shortInt = 12345;
// short shortInt = 1234567890; // Show error
byte veryShortInt = 123;
// byte veryShortInt = 12345; // Show error
long veryLongInt = 1234567890123456789L;
char letter = 'a';
boolean isPrime = true
}
}
|
DEMO:
demo/02-elem-prog/05-prim-types/PrimeTypes.java
Use BleuJ debug window to
show the
value stored in
variables
double: -1.7976931348623157E+308 --- +1.7976931348623157E+308 float: -3.4028235E+38 --- +3.4028235E+38 long: -9223372036854775808 --- 9223372036854775807 int: -2147483648 --- 2147483647 short: -32768 --- 32767 byte: -128 --- 127 |
import java.util.Scanner; // Scanner can be used to reading any type of numbers
public class ReadNumbers
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a double value:");
double highPrec = input.nextDouble(); // Convert to double representation
System.out.print("Enter a float value:");
float lowPrec = input.nextFloat(); // Convert to float representation
System.out.print("Enter an int value:");
int normalInt = input.nextInt(); // And so on...
System.out.print("Enter a short value:");
short shortInt = input.nextShort();
System.out.print("Enter a byte value:");
byte veryShortInt = input.nextByte();
System.out.print("Enter a long value:");
long veryLongInt = input.nextLong();
System.out.print("Enter a boolean value:");
boolean isPrime = input.nextBoolean();
System.out.println("Done"); // ** Put a breakpoint here
}
}
|
DEMO:
demo/02-elem-prog/05-prim-types/ReadNumbers.java
Use BleuJ debug window to
show the
value stored in
variables
|
DEMO: demo/02-elem-prog/05-prim-types/ComputeArea.java
|