0% found this document useful (0 votes)
127 views

ICSE Java Quick Reference

1) The document provides a quick reference guide for common Java concepts including arithmetic operators, relational operators, if/else statements, loops, arrays, strings, input/output, and formatting. 2) Key details covered include using methods like equals() and compareTo() to compare strings, the different forms of if/else statements and when to use blocks, how to get user input with the Scanner class and display output with System.out, and how to perform conversions between strings and numeric types. 3) The guide also summarizes primitive data types in Java, object creation with the new operator, and constructs like switch statements with examples of proper usage involving breaks and defaults.

Uploaded by

GreatAkbar1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

ICSE Java Quick Reference

1) The document provides a quick reference guide for common Java concepts including arithmetic operators, relational operators, if/else statements, loops, arrays, strings, input/output, and formatting. 2) Key details covered include using methods like equals() and compareTo() to compare strings, the different forms of if/else statements and when to use blocks, how to get user input with the Scanner class and display output with System.out, and how to perform conversions between strings and numeric types. 3) The guide also summarizes primitive data types in Java, object creation with the new operator, and constructs like switch statements with examples of proper usage involving breaks and defaults.

Uploaded by

GreatAkbar1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Java Quick Reference Guide

Arithmetic Operators Remember to use the methods Forms of the if Statement


+ Addition equals( ) or compareTo( ) when comparing
- Subtraction Strings rather than relational comparison Simple if Example
/ Division (int / floating-point) operators. if (expression) if (x < y) The
2/3 = 0, 2.0/3.0 =.666667 statement; x++; "expression" in
String s1 = "abc", s2 = "def";
* Multiplication the parentheses
% Modulus (integer remainder) String Comparison expressions: if/else Example
for an
Compare for equality: if (expression) if (x < y)
Relational/Equality Operators
 s1.equals(s2) or statement; x++; if statement
< Less than else else
<= Less than or equal to  s1.compareTo(s2) == 0
statement; x--; or
> Greater than Remember the compareTo( ) method
>= Greater than or equal to returns one of 3 values: if/else if (nested if) Example loop
== Equal to  neg number, pos number, 0 if (expression) if (x < y)
!= Not equal to is often also
Compare for lexical order: statement; x++;
referred to as a
Logical Operators  s1.compareTo(s2) < 0 (s1 before s2) else else
if (expression) if (x < z) "condition"
! NOT  s1.compareTo(s2) > 0 (s1 after s2)
&& AND statement; x--;
|| OR else else
Remember to distinguish between integers
statement; y++;
Assignment Operators and real numbers (called floating-point in
= simple assignment Java). These are stored differently in To conditionally execute more than one statement, you must
+= addition/assignment memory and have different ranges of create a compound statement (block) by enclosing the statements
-= subtraction/assignment values that may be stored. in braces ( this is true for loops as well ):
*= multiplication/assignment  integer: 2, 3, -5, 0, 8
Form Example
/= division/assignment  floating-point: 2.0, 0.5, -3., 4.653 if (expression) if (x < y)
%= modulus/assignment
{ {
Increment ++ /Decrement -- operators used in prefix and postfix modes statement; x++;
++/-- prefix mode - inc(dec) variable, use variable in the larger expression statement; System.out.println( x );
++/-- postfix mode - use variable in larger expression, inc(dec) variable } }
Object Creation: ( new ) new int[ 10 ], new GradeBook("CIS 182")
The new operator creates an object and returns a reference (address of an object)
Input using Scanner class
Java Types [value/reference ] Scanner input = new Scanner ( System.in ); //keyboard input
A value type stores a value of a primitive type int x = 3; input methods: next(), nextLine(), nextInt(), nextDouble()
A reference type stores the address of an object Circle c = new Circle(2);
A reference variable is created using a class name: GradeBook myGradeBook; Output methods for System.out or PrintWriter objects
print(), println(), printf() [formatted output]
Primitive Data Types ( Java value types ) Remember: String is a reference type
boolean flag / logical true, false [ boolean literals ] Input/Output using JOptionPane class [ package javax.swing ]
char character 'A', 'n', '!' [ char literals ]
byte, short, int, long integral 2, 3, 5000, 0 [ int literals ] String numString; int num;
float, double floating-point 123.456, .93 [ double literals ] numString = JOptionPane.showInputDialog("Enter a number");
Default numeric literal types: num = Integer.parseInt(numString);
integral: int int x = 3; //3 is an int literal JOptionPane.showMessageDialog(null, "Number is " + num);
floating-point: double double y = 2.5; //2.5 is a double literal
Most commonly used reference type in Java is String. String name = "Jack";
Conversion from a String to a number using Wrapper Classes
double d = Double.parseDouble(dString);
The switch case Construct ( break and default are optional ) float f = Float.parseFloat(fString);
int j = Integer.parseInt(jString);
Form: Example:
switch (expression) switch (choice) Java formatted output [ printf( ) and String.format( ) methods ]
{ {
3 components: format string and optionally: format-specifiers ( fs )
case int-constant : case 0 :
and an argument list ( al )
statement(s); System.out.println( “You selected 0.” );
 fs: " ... % [flags] [width] [precision] format-specifier ... "
[ break; ] break;
 al: comma separated list of expressions
case int-constant : case 1: Format-specifiers: s (string), d (integer), f (floating-point)
statement(s); System.out.println( “You selected 1.” ); Example: System.out.printf("Total is %,10.2f%n", total);
[ break; ] break;
[ default : default : Java Numeric Conversions and Casts:
statement; ] System.out.println(
“You did not select 0 or 1.” ); Widening conversions are done implicitly.
} } double x; int y = 100;
x = y; // value from y implicitly converted to a double.
The "expression" and “int-constant” are usually type int or char. Java 7
adds the ability to use a string. switch(behavior) { case “good”: … } Narrowing conversions must be done explicitly using a cast.
double x = 100; int y;
Use the break keyword to exit the structure (avoid “falling through” other y = (int) x; // value from x explicitly cast to an int
cases). Use the default keyword to provide a default case if none of the
case expressions match (similar to a trailing “else” in an if-else-if In mixed expressions, numeric conversion happens implicitly.
statement). double is the “highest” primitive data type, byte is the “lowest”.
Java Quick Reference Guide

The while Loop ( pre-test loop ) The for Loop ( pre-test loop )

Form: Example: Form: Example:


for (init; test; update) for (int count=1; count<=10; count++)
init; x = 0;
{ {
while (test) while (x < 10) statement; System.out.println( count );
{ { } }
statement; sum += x;
update; x++; Enhanced for loop: for (parameter : collection)
} } statement;
int scores[ ] = {85, 92, 76, 66, 94}; //collection is the array scores
for ( int number : scores ) //parameter is the variable number
The do-while Loop ( post-test loop ) System.out.println(number);
Form: Example: Escape Sequences Operator Precedence
init; x = 0; Special characters in Java (1) mathematical (2) relational (3) logical
do do
\n newline character '\n' ( )
{ { ----------
\t tab character '\t'
statement; sum += x; *, /, % [ mathematical ]
\" double quote '\"'
update; x++; ----------
\' single quote '\''
} while (test); } while (x < 10); +, -
\\ backslash '\\'
Logical operators: !, &&, ||

Selection and Loop Structures Use the ArrayList class to


Java Arrays: Create an array ( 2 ways )
create a dynamically
Selection: 1. <type> <array-name>[ ] = new <type>[size]; resizable array.
 Unary or single selection 2. <type> <array-name>[ ] = { <initializer-list> };
 Binary or dual selection The Arrays class has static
 Case structure possible when //create an array of 20 elements. methods that can be used
int myArray[ ] = new int[20]; with arrays and ArrayLists to
branching on a variable
 Simple selection //create an array of 3 elements set to the values in the initializer list. search, sort, copy, compare
 One condition int myArray[ ] = { 1, 2, 3 }; for equality, etc.
String stooges[ ] = { "Moe", "Larry", "Curly" };
 Compound selection int num[ ]; … <stmts> ….
 Multiple conditions joined //assign value of first element in myArray to the integer variable x.
with AND / OR operators int x = myArray[0]; Create a new initialized
//assign value of the last element in myArray to the integer variable y. array and assign to num.
Looping: num = new int[ ]{1,2,3,4,5};
int y = myArray[ myArray.length-1 ];
 Java Pre-test loops
 Test precedes loop body All arrays have a public field named length which holds the number of elements in the array.
 while
Given this declaration: int x[][][];
 for
 Java Post-test loop x.length is the number of elements in the array in the first dimension.
 Test follows loop body x[m].length is the number of elements for a specific array in the second dimension.
 do-while x[m][n].length is the number of elements for a specific array in the third dimension.

Loop Control: Java Methods: <modifier(s)> <type> <method-name> ( [<type> param1] [, <type> param2] [, … ] )
 3 types of expressions that A Java method can return a single value using a return statement: return <expression>; If a method
are used to control loops: will not return a value, the return type void is used in the method header. The return statement return;
may be used if needed or left out (causing an implicit return at the end of the method).
 initialization ( init )
 test void printHeadings( ) //no parameters, return type is void
 update { <method body> }
 Counter-controlled loops, void printDetailLine( String name, int number, double gpa )//33.141592635…
Math.PI parameters, return type is void
aka definite loops, work with { <method body> }
a loop control variable (lcv)
int getCount( ) //no parameters, return type is int
 Sentinel-controlled loops, { <method body> }
aka indefinite loops, work
double max( double x, double y ) //2 parameters, return type is double
with a sentinel value
{ <method body> }
 Java Loop Early Exit: When a method is called, the data is passed to the parameters (if any) using arguments
 break statement
//Arguments: "Jack Wilson", 100, 3.50 passed to Parameters: name, number, gpa for Method:
Note: The break statement can printDetailLine (see method header above) : printDetailLine( "Jack Wilson", 100, 3.50);
be used with a switch
statement or a loop in A method may be declared with one variable length parameter. It must be the last parameter declared.
Java. Loops may also use The syntax of the declaration is <type> ... <parameter-name>. Spacing doesn’t matter.
a continue statement. Examples: int... numbers, double ... values, String ...names //implicit array creation

You might also like