Comments
| Documentation Comment | Statement Comments |
| /** * */ E.g., /** This is a sample comment * that would span * multiple lines */ | //
// This is a sample single line comment |
Primitive data Type
| int E.g., int sumOfNumbers; | double E.g, double average; | char E.g., char singleChar; | boolean E.g., boolean isBig; |
Declaring Variables
| <Visibility> <type> <name> E.g., private int sumOfNumbers Note: Generally all field (i.e., class level) variables should be private |
Print statements
| Prints on the Same Line | Prints on a new line |
| System.out.print(“”) E.g., System.out.print(“The sum is: “ + sumOfNumbers); | System.out.println(“”) |
Numeric Expressions
| Expression | Meaning |
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus division |
| += E.g., sum += value | This is the equivalent of sum = sum + value |
Rational Operators – used in conditional statements (if, while, etc.)
| Operator | Meaning |
| = = | equal |
| < | less than |
| <= | Less than or equal |
| > | Greater than |
| >= | Greater than or equal |
| != | Not equal |
Conditional Controls
| If – else if |
| if (condition){ statements } else if (condition){ statements }else{ statement } E.g., if ( sumOfNumbers > = 23) { sumOfNumbers = 15; totalSum += 23; }else if (totalSum <156) { System.out.println(“You don’t have enough money.”); }else { System.out.println(“You have just the right amount.”); |
Loops
| Do while statement | For loop |
| do{ statements }while (condition) E.g., do { sum += value } while (sum <= 456) | for (<initialization>; <condition>; <increment>) { Statements } e.g., for ( int i = 0; i < = 10; i++) { Statements } |
Scanner – to get user input
| Meaning | |
| import java.util.Scanner | Imports scanner class |
| Scanner <name> = new Scanner(System.in) E.g., Scanner userInput = new Scanner(System.in) | Declaring the Scanner |
| Variable = <name>.next<data> E.g., number = userInput.nextInt( ); | Using Scanner |
Math Class
| Meaning | |
| import java.lang.Math | Imports scanner class |
| Math.random( ) randomNumber = (int)(100*Math.random( ) + 1) | Creates a random number from 1 to 100 |
| (high – low + 1 * Math.random( ) + low) | Random number range |
| (int) Math.random Or (int) (high – low + 1 * Math.random( ) + low) | Makes the random numbers integers |
| Math.abs | Absolute value of x: If x is negative, it returns the positive equivalent, otherwise it leaves it the same. |
Arrays
| Meaning | |
| <type>[ <name> int [ ] arrayVariable; | Declaring an array |
| <name> = new <type> [size of array] arrayVariable = new int [25 ]; | Allocate space for elements |