Java Cheatsheet

Java Syntax#

Files#

All Java files & programs have the .java ending. ex: HelloWorld.java

Comments#

Comments are used to help understand a piece of code. Comments are ignored by the compiler and are human-readable words intended to make the code more readable.

// this is an example comment
/* this is 
a multiline
example comment */

Brackets and Semicolons#

Java uses braces { } to define blocks of code. A block is typically a group of statements. Java also requires semicolons ; at the end of each statement (the basic building block of many programming languages).

Class Declaration & main() Method#

Example Class & Main Method:

public class HelloWorld{
    public static void main(String[] args){
               
    }
}

Java code must be run inside a class and the filename must match the class name. In our example, the filename would be HelloWorld.java to match the class name of HelloWorld.
Note: Java is case-sensitive: HelloWorld is not the same as helloWorld

The second line is our main() method and will also be found in every Java program. When you run a Java application, the main() method is where the programThere is no need to understand it for now, just memorize it and remember that each Java program will have a class name matching the filename as well as a main() method.

Check out this article for more on files, comments, class declarations, main() methods, keywords & literals, and more in Java.

Java’s System.out.print() prints out something in the console. ex: Hello!

Difference between print() and println()#

  • System.out.print(): Prints the text on the console and the cursor remains at the end of the text, the next print statement will start from here.
  • System.out.println(): Prints the text on the console and the cursor moves to the start of the next line at the console, the next print statement will start from here. (more commonly used)
System.out.print("Hello ");
System.out.println("World");
System.out.println("Java is cool!");
System.out.println("Remember your semicolons!!!");

Output:

Hello World
Java is cool!
Remember your semicolons!!!

World is printed on the same line as Hello  because the first print statement is a print() not println().

Check out this article for more on print statements in Java.

Variables#

Variables are containers for storing data values. In Java, 3 commonly used terms when refering to variables are declaration, assignment, and initialization.

  • declaration: states the type of a variable, along with its name. A variable cannot be declared multiple times and must be declared before reading or assigning values to a variable.
  • assignment: replacing the old value of a variable with a new one
  • initialization: the first time a value is assigned to a variable. Can be done with declaration.

Data Types#

Integer

An Integer or an int is a whole number with no decimal points. Examples of integers are: 22, -14, 39

int x = 5;
System.out.println(x);

In this example, the integer variable x has been assigned the value of 5 and the program will print out 5 when run.

String

A String is a sequence of characters that typically represents text. Examples of Strings are: Hello, Python, the brown fox jumps over the lazy dog

String y = "John";
System.out.println(y);

In this example. the String variable y has been assigned the value of John and the program will print John when run.

Boolean

A boolean represents either true or false and is used in logic computing.

boolean z = true;
System.out.println(z);

Check out this article for more on variables in Java.

Converting/Parsing Arguments#

String to Integer

String a = "123";
int b = Integer.parseInt(a);
System.out.println(b + 2);

To convert from one data type to another, the most common way is to use parse. There are also many other ways to convert; to convert to a String, we’d most commonly use toString().

Check out this article and this article for more on converting/parsing in Java.

Operators#

Regular Arithmetic Expressions#

  • addition: +
  • subtraction: -
  • multiplication: *
  • division: /
  • modulus (a.k.a remainder): %

Example:

System.out.println(1 + 3 / 2 * 10 % 5 - 2);
// output: -1

Because of Order of Operations and P.E.M.D.A.S., first we do 3/2 which is equal to 1 because Java Integers do not support decimals. To read more about Integers and decimals check out this article . 1 * 10 is equal to 10 and 10 % 5 is equal to 0 (there’s no remainder). Lastly, 1 + 0 - 2 is equal to -1.

Compound Arithmetic Assignment Operators#

  • compound addition: +=
  • compound subtraction: -=
  • compound multiplication: *=
  • compound division: /=
  • compound modulo: %=

Example:

int a = 3;
a += 5;
System.out.println(a);
// output: 8

In line 2, the expression a += 5 is shorthand for a = a + 5, which is why the output is 8 (3 + 5 = 8)

Increment/Decrement#

  • increment: ++
  • decrement: --

Example:

int b = 2;
b++;
System.out.println(b);
b--;
b--;
System.out.println(b);

Output:

3
1 

Increment ++ and Decrement -- are both shorthand for += 1 and -= 1.
In line 2, b++ increments b by 1, assigning the value of 3 to b.
In lines 4 and 5, b-- decrements b by 1, assigning the value of 2 then 1 to b.

Comparison Operators#

  • equal: ==
  • not equal: !=
  • less than: <
  • less than or equal: <=
  • greater than: >
  • greater than or equal: >=
  • or: ||
  • and: &&

Example:

System.out.println(2 <= 3);
System.out.println((2 != 3) || (6 > 6));
System.out.println((10 == 6) && (3 < 7));

Output:

true
true
false

The first line is true because 2 is less than or equal to 3.
The second line is true because 2 is not equal to 3 even though 6 is NOT greater than 6. Note that only one of the conditions have to be true in an or || comparison.
The third line is false because 10 is not equal to 6 even though 3 IS less than 7. Note that because only one of the conditions is true, the output is still false because it is an and && comparison.

Check out this article for more on Operators in Java.

Scanner (User Input)#

Scanner is a Java class in the java.util package to obtain input. It’s the easiest way to read input, but not the most efficient.

Reading Input from the Console

// make the Scanner class available for use
import java.util.Scanner;
public class ScannerDemo{
    public static void main(String[] args){
        // create the Scanner object (called "in" for demo purposes)
        // "System.in" is the opposite of "System.out" and grabs input from the terminal/console
        Scanner in = new Scanner(System.in);
        
        // user inputs an integer and is stored in variable n 
        // n is a regular integer variable and can be modified like normal
        int n = in.nextInt();

        // prints the value
        // should be the same as the user input 
        System.out.println(n);
    }
}

Example GIF:
.

Note that Scanner can be used for many data types, although you may need to convert/parse values.

Check out this article for more on the Scanner class in Java.

If Statements#

Syntax:

if(expression){
    // statements to be executed if the boolean expression is true
}
else if(expression){
    // statements to be executed if the boolean expression is true
}
else{
    // statements to be executed if the above boolean expressions are false
}

Example:

int hour = 5;
if(hour != 10){
    System.out.println("The hour is not 10!");
}
else if(hour < 5){
    System.out.println("The hour is less than 5!");
}
else{
    System.out.println("The hour is 10 OR greater than or equal to 5!");
}
// Output: The hour is 10 OR greater than or equal to 5!

The first two boolean expressions are false, therefore the else statement is executed and The hour is 10 OR greater than or equal to 5! is printed. If the first or second boolean expressions were true, the first or second code blocks would have been executed properly.

Check out this article for more on if statements in Java.

Loops#

For Loops#

Syntax:

for(init; condition; update){
    // statements to be executed
}

init: executed once before everything else
condition: the condition of the loop
update: executed every time the loop is iterated

Example:

for(int i = 0; i < 4; i++){
    System.out.println(i);
}

Output:

0
1
2
3

init: declares/initializes a variable before the loop starts int i = 0.
condition: defines the condition for the loop to run (i < 4). If the condition is true, the loop will iterate, if it is false, the loop will end.
update: increases a value i++ each time the code block in the loop has been executed.

During each iteration, the loop will print out the value of i which increments from 0 to 3.

Check out this article for more on for loops in Java.

While Loops#

Syntax:

while(condition){
    // statements to be executed
}

A while loop will iterate as long as the boolean condition is true.

Example:

int i = 0;
while(i < 4){
    System.out.println(i);
    i++;
}

Output:

0
1
2
3

During each iteration, the loop will print out the value of i which starts at 0 and increments by 1 via i++ and ends at 3.

Check out this article for more on while loops in Java.

Break & Continue Statements#

Break and Continue statements are “jump” statements that are used to skip statements in a loop or terminate a loop. These are most commonly used inside loops .

Break Statement

A break statement is used to terminate a loop immediately. Once terminated, the program returns immediately to the first statement outside the loop.

Below are two examples of break statements in a for loop and a while loop.

for(int i = 0; i < 5; i++){
    if(i == 3){
        break;
    }
    System.out.println(i);
}
System.out.println("outside of the loop");

Output:

0
1 
2
outside of the loop
int j = 0;
while(true){    // will loop forever unless there's a break statement
    if(j == 3){
        break;
    }
    System.out.print(j);
    j++;
}
System.out.println("outside of the loop");

Output:

0 
1 
2
outside of the loop

Continue Statement#

A continue statement is used to skip the current iteration of a loop. Unlike a break statement, a continue statement does not terminate the loop.

Below are two examples of continue statements in a for loop and a while loop.

for(int i = 0; i < 3; i++){
    if(i == 1){
        continue;
    }
    System.out.println(i);
}

Output:

0
2
int j = 0;
while(j < 3){
    if(j = 1){
        continue;
    }
    System.out.println(j);
}

Output:

0
2

Check out this article for more on break and continue statements in Java.

Arrays#

An array is a fixed-size sequential collection of elements of the same data type. Arrays are used to store collections of data.

Declaring/Initializing#

There are many various ways to declare an Array, below are some more commonly used methods.

int arr[] = new int[5];                                
String[] fruits = {"apple", "orange", "pear", "banana"};

The first line creates an empty Integer (int) Array of size 5 with the name arr.

The second line creates a String Array called fruits with the elements apple, orange, pear, and banana.

Accessing Elements of an Array#

String[] fruits = {"apple", "orange", "pear", "banana"};
System.out.println(fruits[0]);
fruits[1] = "lemon";
System.out.println(fruits[1]);

Output:

apple
lemon

Java Arrays are zero-indexed (starts counting from 0). The first element of an array can be accessed using the name of the Array then [0] as shown by line 2.

In line 3, fruits[1] has the value orange, but was reassign it to lemon. In line 4, when we print the value of fruits[1], the program prints lemon.

You can treat each element of an Array as a variable and all specific properties of the corresponding data type still applies to Array elements.

Looping through an Array#

We can loop through an Array using a for() loop.

Syntax:

String[] fruits = {"apple", "lemon", "pear", "banana"};
for(int i = 0; i < fruits.length; i++){
    // statements to be executed
    System.out.println(fruits[i]);
} 

Output:

apple
lemon
pear
banana

fruits.length returns the length of the Array fruit, which is 4. Note that fruits[fruits.length] will return an error because Java Arrays are 0-based and there is no element in fruits[4].

Check out this article and this article for more on Arrays in Java.

ArrayList#

A Java ArrayList is a resizable array, found in the java.util package. ArrayLists are useful because unlike regular Arrays, there is no length limit. (If you want to add or remove elements from an array you have to create a new one).

Syntax:

import java.util.ArrayList;

// creates an empty Integer ArrayList called 'list'
ArrayList<Integer> list = new ArrayList<Integer>(); 
// creates an empty String ArrayList called 'fruits'
ArrayList<String> fruits = new ArrayList<String>();
// add elements 
fruits.add("apple");
fruits.add("orange");
fruits.add("pear");
fruits.add("banana");

// size (length) of an ArrayList
System.out.println(fruits.size());

// iterate through an ArrayList
for(int i = 0; i < fruits.size(); i++){
    // prints each element
    // fruits.get(i) grabs the element at index i 
    System.out.println(fruits.get(i));
}

// remove elements
// removes "orange"
fruits.remove(1);
// prints "pear" which is the new index 1
System.out.println(fruits.get(1));

// modify elements
// sets element at index 0 to "apples"
fruits.set(0, "apples");

// grab the index of an element
// returns 2 which is the index of "banana"
System.out.println(fruits.indexOf("banana"));

Output:

4
apple
orange
pear
banana
pear
apples
2

Check out this article and this article for more on ArrayLists in Java.

2d-Arrays#

A two dimensional Array in Java is simple an Array of Arrays. Elements are stored in rows and columns, similar to a spreadsheet or table.

Syntax:

// creates an empty 2 by 4 String 2d-array called 'arr'
String[][] arr = new String[2][4];

// modify elements (very similar to regular Arrays)
arr[0][0] = "test";
System.out.println(arr[0][0]);

// creates a 2 by 3 Integer 2d-array called 'nums'
int[][] nums = { {1, 2, 3}, {4, 5, 6} };

// iterating through a 2d array
for(int i = 0; i < nums.length; i++){           // nums.length = # of rows
    for(int j = 0; j < nums[i].length; j++){    // nums[i].length = # of columns
        System.out.print(nums[i][j] + " ");     // prints the element and a space
    }
    System.out.println();                       // creates a new line
}

Output:

test
1 2 3
4 5 6

Overall, 2d-Arrays are extremely similar to 1d-Arrays in Java. The main difference is that 2d-Arrays operate in a table or spreadsheet format, with rows first then columns.

Check out this article and this article for more on 2d-Arrays in Java.

This is still a work in progress.
Created By: WHS Comp Sci Club Officers

CC-BY-NC-SA 4.0 | WHS CSC 2021