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

     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 (; ; ) { 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 = new Scanner(System.in) E.g., Scanner userInput = new Scanner(System.in) Declaring the Scanner Variable = .next 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 [   int [ ] arrayVariable; Declaring an array = new [size of array] arrayVariable = new int [25 ]; Allocate space for elements
William Anderson (Schoolworkhelper Editorial Team)
William completed his Bachelor of Science and Master of Arts in 2013. He current serves as a lecturer, tutor and freelance writer. In his spare time, he enjoys reading, walking his dog and parasailing. Article last reviewed: 2022 | St. Rosemary Institution © 2010-2024 | Creative Commons 4.0