Printing

System.out.print("Hello World")
System.out.println("Hello World") // Adds new line character

Variable

Declaring variable

It has two parts that needs to be defined: setting the data type and the variable name.

String my_variable;
  • Java does not allow different variables to have the same name - regardless of data type.
  • Additionally, Java does not allow spaces in variable names - either user camelCase or snake_case to separate words.
  • Since Java variables are case sensitive, var and Var are different variables.

Assigning variables

We can either assign variables combined with the declaration, or assign or re-assign values after the declation step.

int value;
value = 5;
int new_value = 10;

Rules for variable names

Here are the basic rules for variable names:

  1. Start with a letter, dollar sign or underscore
  2. Remainder of variable name is letters, numbers, or underscores
  3. Cannot use a Java keyword
  4. Variables are case sensitive

Data Types

Integers

int number = 5000;

Floats and Double

float uses 4 bytes and double uses 8 bytes.

double fraction = 0.5;

Boolean

boolean thisIsTrue = true;
boolean thisIsFalse = false;

Strings

String variable value must be surrounded by quotation marks. Single quotation mark does not work.

String words = "This is a string";

Concatenate strings with + sign.

String variable = "This is " + "a concatenated string.";

Type casting

// convert int to a double
int a = 5;
int b = 2:
System.out.println((double) a / b) // cast variable a from type int to type double
// The result will be "53" because Java will convert 5 into a String
int a = 5;
String b = "3";
System.out.println(a + b);
// The result will be 8 because Integer.parseInt(b) will convert b from String to int
int a = 5;
String b = "3";
System.out.println(a + Integer.parseInt(b));
  • Parse a String to a different type:
    • Integer.parseInt()
    • Double.parseDouble()
    • Boolean.parseBoolean()
  • Convert a different type to a String
    • String.valueOf()

Operators

Assignment operator

  • =: Assign value to a variable.

Arithmetic operators

  • +: Addition operator
  • -: Subtraction operator
  • a++: Increment the variable a by 1. Decrement variable a--.
  • a+=x: Increment the variable a by x. Decrement variable a by x a-=x.
  • /: Division operator.
  • a/=b: a = a / b
  • Interger division: Division between two int returns and int by removing the decimal part.
  • %: Performs the division but returns the remainder
  • *: Performs multiplication
  • a *= b: a = a * b
  • Java uses the PEMDAS method for determining order of operations.
    • P: Parentheses
    • E: Exponents: powers and square roots
    • MD: Multiplication and division - left to right
    • AS: Addition and Subtraction - left to right

Boolean operators

  • ==: Check if two values are equal
  • !=: Check if two values are not equal
  • < and <=: Less and less than or equal operator
  • > and >=: Greater and greater than or equal operator
  • &&: and operator
  • ||: or operator
  • !: not operator
  • Short-circuting: If Java can determine the result of a boolean expression before evaluating the entire thing, it will stop and return the value.
  • When evaluating complex boolean expresssions involving arithmetic operators
    • Evaluate all arithmetic operators according to PEMDAS
    • Evaluate all boolean operators (order: parenthesis, not, and, or)

Conditionals

If statement

  • If statements in Java must contain the following items:
    • the keyword if
    • a boolean expression in parentheses
    • curly braces surrounding all lines of code that will run if the boolean expression is true
    • It is best practice to also indent the lines of code inside the curly braces to visually differentiate them from the commands that will always run.
// Example of if statement
if(5 > 4) {
  System.out.println("1st command if true");
  System.out.println("2nd command if true");
}   
System.out.println("I will always print!");
// Example of if statement using a compound conditional statement
int num = 16;

if (num % 2 == 0 && num > 10) {
    System.out.println("Even and greater than 10");
}

If Else statement

// Example of if else statement
if (5 > 4) {
    System.out.println("The boolean expression is true");
}
else {
    System.out.println("The boolean expression is false");
}

Nesting multiple if else statements

Nesting if else statements is more efficient than writing many if statements because nesting will interrupt the search as soon as one of the conditions is satisfied, while all the if statements are executed independent of conditions being satisfied.

int grade = 62;
if(grade < 60) {
    System.out.println("F"); }
else if(grade < 70) {
    System.out.println("D"); }
else if(grade < 80) {
    System.out.println("C"); }
else if(grade < 90) {
    System.out.println("B"); }
else if(grade <= 100) {
    System.out.println("A"); }

Switch case statement

  • Here are the rules for writing a switch case statement:
    • Start with switch followed by the variable that is going to be tested in parentheses ()
    • All of the cases are surrounded by curly braces {}
    • Each case is followed by a value (numeric or String) and a colon :
    • After each : write the code that should run if the variable is equal to that value
    • After each section of code, include break;
    • As the very last case, use default: and specify what should happen if none of the above cases are true
// Switch case example
int dayOfWeek = 3;

switch(dayOfWeek) {

    case 1: System.out.print("Sunday"); //only prints if dayOfWeek == 1
                 break;
    case 2: System.out.print("Monday"); //only prints if dayOfWeek == 2
                 break;
    case 3: System.out.print("Tuesday"); //only prints if dayOfWeek == 3
                 break;
    case 4: System.out.print("Wednesday"); //only prints if dayOfWeek == 4
                 break;
    case 5: System.out.print("Thursday"); //only prints if dayOfWeek == 5
                 break;
    case 6: System.out.print("Friday"); //only prints if dayOfWeek == 6
                 break;
    case 7: System.out.print("Saturday"); //only prints if dayOfWeek == 7
                 break;
    default : System.out.print("Invalid"); //only prints if none of the above are true

}
// Switch case example with same command accross multiple cases
int grade = 62;
int letterGrade = grade / 10;
switch(letterGrade) {
    case 10: case 9: System.out.print("A"); 
                 break;
    case 8: System.out.print("B"); 
                 break;
    case 7: System.out.print("C"); 
                 break;
    case 6: System.out.print("D"); 
                 break;
    default : System.out.print("F");
}

Switch case vs If else

  • If Else is used for ranges - Switch Case is for values
  • If Else is used for handling multiple variables
    • Switch case can only compare against values - not variables.
  • If Else is used for compound conditionals

Loops

For loops

for(int i = 0; i < 5; i++) {
    System.out.println("Loop #" + i);
}

While loops

  • Same result implemented with for loop and while loop
// Example with for loop
for (int i = 0; i < 5; i++) {
  System.out.println("Loop#: "+i);
}

// Same example with while loop
int i = 0;
while (i < 5) {
  System.out.println("Loop# "+i);
  i++;
}
  • When to use a while loop
    • while loops are actually more useful when you are waiting for a certain event to occur but you don't know how many iterations it will take.
  • Infinite loop with break statement
while(true){
  System.out.println("This is an infinite loop");
  int randNum = random.nextInt(100) + 1; // random integer between 1 and 100

  if(randNum > 75){
    System.out.println("The loop has ended");
    break; // stop and exit the loop
  } // close if condition
} // close while loop

Nested loops

// Nested loop example
for(int row = 0; row < 10; row++){
    for(int col = 0; col < 10; col++) {
        System.out.print("#");
    }
    System.out.println(""); //adds new line
}

Exception handling

// Example using exception handling via try and catch
double result = 0;
double input;
Scanner sc = new Scanner(System.in);

while (true) {
  System.out.print("Enter a number to add to sum. ");
  System.out.println("Or enter a non-number to quit and calculate sum.");
  try {
    input = Double.parseDouble(sc.next());
    result = result + input;
  }
  catch (NumberFormatException ignore) {
    System.out.println("Sum = " + result);
    break;
  }  
}

sc.close();

Scanner: User input

// Example using user input with Scanner
double result = 0;
double input;
Scanner sc = new Scanner(System.in);

while (true) {
  System.out.print("Enter a number to add to sum. ");
  System.out.println("Or enter a non-number to quit and calculate sum.");
  try {
    input = Double.parseDouble(sc.next());
    result = result + input;
  }
  catch (NumberFormatException ignore) {
    System.out.println("Sum = " + result);
    break;
  }  
}

sc.close();

Reference