Home Java
Post
Cancel

Java

Java Cheatsheet

Introduction

Java is a widely-used, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.

Basic Syntax

Hello World Program

1
2
3
4
5
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Data Types

Primitive Data Types

1
2
3
4
5
6
7
8
int myNum = 5;              // 32-bit Integer
float myFloatNum = 5.99f;   // 32-bit Floating Point
double myDoubleNum = 9.98;  // 64-bit Floating Point
char myLetter = 'D';        // Single 16-bit Unicode Character
boolean myBool = true;      // Boolean (true or false)
byte myByte = 100;          // 8-bit Signed Integer
short myShort = 5000;       // 16-bit Signed Integer
long myLong = 15000000000L; // 64-bit Signed Integer

Non-Primitive Data Types (Reference Types)

1
2
3
4
5
6
String myText = "Hello";    // String
int[] myNumArray = {10, 20, 30}; // Array
// Class
public class Main {
    int x = 5;
}

Type Casting

Widening Casting (automatically)

1
2
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

Narrowing Casting (manually)

1
2
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

Operators

Arithmetic Operators

1
2
3
4
5
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int quot = a / b; // Division
int mod = a % b; // Modulus

Assignment Operators

1
2
3
4
5
a += 5; // a = a + 5
a -= 5; // a = a - 5
a *= 5; // a = a * 5
a /= 5; // a = a / 5
a %= 5; // a = a % 5

Comparison Operators

1
2
3
4
5
6
7
boolean result;
result = a == b; // Equal to
result = a != b; // Not equal
result = a > b;  // Greater than
result = a < b;  // Less than
result = a >= b; // Greater than or equal to
result = a <= b; // Less than or equal to

Logical Operators

1
2
3
4
boolean result;
result = a && b; // Logical and
result = a || b; // Logical or
result = !a;     // Logical not

Bitwise Operators

1
2
3
4
5
6
7
int result;
result = a & b;  // AND
result = a | b;  // OR
result = a ^ b;  // XOR
result = ~a;     // NOT
result = a << 2; // Left Shift
result = a >> 2; // Right Shift

Strings

Basic String Operations

1
2
3
4
5
String txt = "Hello World";
int length = txt.length(); // String Length
String txtUpper = txt.toUpperCase(); // Convert to Upper Case
String txtLower = txt.toLowerCase(); // Convert to Lower Case
int pos = txt.indexOf("Hello"); // Find position of substring

Concatenation

1
2
3
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // Concatenation

Escape Characters

1
2
String txt = "We are the so-called \"Vikings\" from the north.";
String path = "C:\\Users\\User";

Arrays

1
import java.util.Arrays

Declaring and Using Arrays

1
2
3
4
5
int[] myNum = {10, 20, 30, 40}; // Declare and Initialize
int myNumLength = myNum.length; // Get Array Length
for (int i : myNum) { // Enhanced for loop
    System.out.println(i);
}

Multidimensional Arrays

1
2
3
4
5
6
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
    for(int j = 0; j < myNumbers[i].length; ++j) {
        System.out.println(myNumbers[i][j]);
    }
}

Control Flow Statements

If-Else

1
2
3
4
5
6
7
if (condition) {
    // Code if condition is true
} else if (anotherCondition) {
    // Code if anotherCondition is true
} else {
    // Code if all conditions are false
}

Switch

1
2
3
4
5
6
7
8
9
10
11
switch(expression) {
    case x:
        // Code block
        break;
    case y:
        // Code block
        break;
    default:
        // Code block
        break;
}

While Loop

1
2
3
while (condition) {
    // Code block to be executed
}

For Loop

1
2
3
for (int i = 0; i < 5; i++) {
    // Code block to be executed
}

For-Each Loop (Enhanced For Loop)

1
2
3
for (String i : cars) {
    System.out.println(i);
}

Methods (Functions)

Defining and Calling a Method

1
2
3
4
5
6
7
public static void myMethod() {
    // Code to be executed
}

public static void main(String[] args) {
    myMethod(); // Call the method
}

Method with Parameters

1
2
3
4
5
6
7
public static void myMethod(String fname) {
    System.out.println(fname + " Doe");
}

public static void main(String[] args) {
    myMethod("John");
}

Method Overloading

1
2
3
4
5
6
7
public static int plusMethod(int x, int y) {
    return x + y;
}

public static double plusMethod(double x, double y) {
    return x + y;
}

Object-Oriented Programming

Class and Objects

1
2
3
4
5
6
7
8
public class Main {
    int x = 5;

    public static void main(String[] args) {
        Main myObj = new Main(); // Create an object
        System.out.println(myObj.x); // Access attribute
    }
}

Constructors

1
2
3
4
5
public class Car {
    public Car() { // Constructor
        // Initialize object
    }
}

Inheritance

1
2
3
4
5
6
7
class Vehicle {
    // Base class
}

class Car extends Vehicle {
    // Derived class
}

Polymorphism

1
2
3
4
5
6
7
8
9
10
11
class Animal {
    public void animalSound() {
        System.out.println("The animal makes a sound");
    }
}

class Pig extends Animal {
    public void animalSound() {
        System.out.println("The pig says: wee wee");
    }
}

Encapsulation

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Person {
    private String name; // Private attribute

    // Getter
    public String getName() {
        return name;
    }

    // Setter
    public void setName(String newName) {
        this.name = newName;
    }
}

Abstraction

A abstract class is a class that is only used as super class. It can’t generate it’s own Objects.

1
2
3
4
5
6
7
8
9
10
11
12
abstract class Animal {
    public abstract void animalSound();
    public void sleep() {
        System.out.println("Zzz");
    }
}

class Pig extends Animal {
    public void animalSound() {
        System.out.println("The pig says: wee wee");
    }
}

Records

A record is a data type that contains a set of fields, just like a class with usefull default methods. However, a record is immutable, which means that once a record is created, its fields cannot be changed.
Declaring a Record

1
public record Point(int x, int y) { }

In this example, Point is a record with two fields, x and y. The record automatically gets several methods:

  • An all-arguments constructor:
1
2
3
4
public Point(int x, int y) {
    this.x = x;
    this.y = y;
}
  • equals and hashCode methods:
1
2
3
4
5
6
7
8
9
10
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Point)) return false;
    Point point = (Point) o;
    return x == point.x && y == point.y;
}

public int hashCode() {
    return Objects.hash(x, y);
}
  • A toString method:
1
2
3
public String toString() {
    return "Point{x=" + x + ", y=" + y + "}";
}
  • Accessor methods for the fields:
1
2
3
4
5
6
7
public int x() {
    return x;
}

public int y() {
    return y;
}

Using a Record

1
2
3
Point point = new Point(5, 10);
System.out.println(point.x()); // prints 5
System.out.println(point.y()); // prints 10

In this example, we create a new Point record and access its fields using the automatically generated accessor methods.
You can also add methods to a record:

1
2
3
4
5
6
7
8
public record Point(int x, int y) {
    public int sum() {
        return x + y;
    }
}

Point point = new Point(5, 10);
System.out.println(point.sum()); // prints 15

In this example, we add a sum method to the Point record that returns the sum of x and y.

Interfaces

A Interface is a blueprint for a class. It defines the methods that a class must implement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Exception Handling

Try-Catch

1
2
3
4
5
6
7
try {
    // Code that may produce an exception
} catch (ExceptionType name) {
    // Code to handle the exception
} finally {
    // Code to be executed after try and catch
}

Throwing Exceptions

1
2
3
4
5
6
7
8
public static void checkAge(int age) throws ArithmeticException {
    if (age < 18) {
        throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
        System.out.println("Access granted - You are old enough!");
    }
}

Custom Exceptions

1
2
3
4
5
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

Enums

Enums are a special data type that enable for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

1
2
3
public enum Color {
    RED, GREEN, BLUE
}

In this example, Color is the enum and RED, GREEN, and BLUE are its predefined constants. This means that a variable of type Color can only be either RED, GREEN, or BLUE.

You can use an enum in a switch statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
Color myColor = Color.RED;

switch(myColor) {
    case RED:
        System.out.println("Color is Red");
        break;
    case GREEN:
        System.out.println("Color is Green");
        break;
    case BLUE:
        System.out.println("Color is Blue");
        break;
}

You can also use enums in loops and collections:

1
2
3
for (Color color : Color.values()) {
    System.out.println(color);
}

This will print:

1
2
3
RED
GREEN
BLUE

Collections

ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.get(0); // returns "Volvo"
    cars.set(0, "BMW"); // sets the element at index 0 to "BMW"
    cars.remove(0); // removes the element at index 0
    cars.size(); // returns the number of elements in the ArrayList
    cars.clear(); // removes all elements from the ArrayList
    System.out.println(cars);
    // lambda expression
    cars.forEach((n) -> { System.out.println(n); });
  }
}

LinkedList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.addFirst("BMW");
    cars.addLast("Ford");
    cars.removeFirst();
    cars.removeLast();
    cars.getFirst();
    cars.getLast();
    System.out.println(cars);
  }
}

You can also use all ArrayList methods.

Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.HashMap;
import java.util.Set;

public class Main {
public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.get("England");
capitalCities.remove("England");
capitalCities.clear();
capitalCities.size();
System.out.println(capitalCities);
// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
Set<String> keys = capitalCities.keySet();
Set<String> values = (Set<String>) capitalCities.values();
		}
	}
}

IO

Scanner

1
2
3
4
5
6
7
8
9
10
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        int age = sc.nextInt()
        sc.close();
    }
}

Reading from a File

1
2
3
4
5
6
7
8
9
10
11
12
try {
    File myObj = new File("filename.txt");
    Scanner myReader = new Scanner(myObj);
    while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
    }
    myReader.close();
} catch (FileNotFoundException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

Writing to a File

1
2
3
4
5
6
7
8
9
try {
    FileWriter myWriter = new FileWriter("filename.txt");
    myWriter.write("Files in Java might be tricky, but it is fun enough!");
    myWriter.close();
    System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

Stack

A Stack is a Last-In-First-Out (LIFO) data structure. In Java, Stack is a class that extends Vector and implements the Collection interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        
        // Adding elements (push)
        stack.push("First");
        stack.push("Second");
        stack.push("Third");
        
        // Peek at top element without removing it
        System.out.println(stack.peek());  // Output: Third
        
        // Remove and return top element (pop)
        String top = stack.pop();  // removes "Third"
        
        // Check if stack is empty
        boolean isEmpty = stack.empty();
        
        // Search for element (returns 1-based position from top)
        int position = stack.search("First");
        
        // Iterate through stack
        for(String element : stack) {
            System.out.println(element);
        }
    }
}

Common Stack methods:

  • push(E item): Adds an element to the top
  • pop(): Removes and returns the top element
  • peek(): Returns the top element without removing it
  • empty(): Returns true if stack is empty
  • search(Object o): Returns position of an object
  • size(): Returns number of elements in stack
This post is licensed under CC BY 4.0 by the author.