Java Quick Reference Guide
Java Quick Reference Guide
The switch/case Construct ( break and default are optional ) Java Numeric Conversions:
Form: Example: Widening conversions are done implicitly.
switch (int-expression) switch (choice) double x; int y = 100;
{ { x = y; // value of y implicitly converted to a double.
case int-constant : case 0 : Narrowing conversions must be done explicitly using a cast.
statement(s); System.out.println( double x = 100; int y;
“You selected 0.” ); y = (int) x; // value of x explicitly cast to an int
[ break; ] break;
case int-constant : case 1: In mixed expressions, numeric conversion happens implicitly.
statement(s); System.out.println( double is the “highest” data type, byte is the “lowest”.
“You selected 1.” ); Conversion from a String to a number using Wrapper Classes
[ break; ] break;
double d = Double.parseDouble(dString);
[ default : default : float f = Float.parseFloat(fString);
statement; ] System.out.println( int j = Integer.parseInt(jString);
“You did not select 0 or 1.” );
} }
Use the break keyword to exit the structure ( avoid “falling through” Java Escape Sequences ( two symbols but only one character )
other cases). Use the default keyword to provide a default case if none
of the case expressions match ( similar to trailing “else” in an if-else-if … \n newline character '\n'
statement ). \t tab character '\t'
Java Quick Reference Guide
The for Loop ( pre-test loop )
Form: Example:
for (initialization; test; update) for (count = 0; count < 10; count++)
statement; System.out.println ( count );
for (initialization; test; update) for (int count = 1; count <= 10; count++)
{ {
statement; System.out.print( "The value of count is " );
statement; System.out.println( count );
} }
For definite while and do..while loops, remember there should be an initialization statement preceeding the loop body and an update
statement in the loop body (usually the last statement). Examples below don’t show these explicitly due to space…
The do-while Loop ( post-test loop ) The while Loop ( pre-test loop )
Form: Example: Form: Example:
do do while (expression) while (x < 100)
statement; sum += x; statement; y = y + x++;
while (test-exp); while (sum < 100)
while (expression) while (x < 100)
do do { {
{ { statement; y = y + x;
statement; y = x + 5; statement; x++;
statement; x++; } }
} while (expression); } while (x < 100);