Bytes
Web Development

Java Cheat Sheet (Basics to Advanced Java Cheat Sheet)

Last Updated: 23rd October, 2024
icon

Jay Abhani

Senior Web Development Instructor at almaBetter

Get the Ultimate perfect for all developers Java Cheat Sheet! From basics to advanced, get a quick reference on syntax, OOP, collections, streams, and more

Java is one of the most widely used programming languages due to its versatility, object-oriented nature, and platform independence. Whether you are preparing for an interview or need a quick reference for core Java concepts, this Java cheat sheet will help you navigate Java's syntax, data structures, OOP principles, and more. Below, we’ll dive into all essential areas, including a java syntax cheat sheet, core java cheat sheet, java data structures cheat sheet, java oops cheat sheet, and java DSA cheat sheet.

Java Syntax Cheat Sheet

Java syntax forms the backbone of your coding abilities in the language. Below is a quick reference for basic syntax elements.

Data Types

Java is a statically-typed language, meaning all variables must be declared with a data type. The following are the primitive data types in Java:

  • int: for integers (e.g., int x = 10;)
  • float: for floating-point numbers (e.g., float y = 3.14f;)
  • double: for double-precision floating-point numbers (e.g., double z = 9.81;)
  • char: for single characters (e.g., char a = 'A';)
  • boolean: for true/false values (e.g., boolean flag = true;)
  • byte: for very small numbers (e.g., byte b = 127;)
  • short: for short integers (e.g., short s = 1000;)
  • long: for long integers (e.g., long l = 100000L;)

Variables

int num = 10; // Declaration and initialization
double pi = 3.1415;
String name = "Java"; // Object type

Conditional Statements

if (num > 0) {
    System.out.println("Positive");
} else if (num < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Loops

for (int i = 0; i < 5; i++) {
    System.out.println(i);  // Output: 0 1 2 3 4
}

while (num > 0) {
    System.out.println(num);
    num--;
}

Methods

public static int addNumbers(int a, int b) {
    return a + b;
}

public static void main(String[] args) {
    System.out.println(addNumbers(5, 10)); // Output: 15
}

Arrays

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Output: 1

Core Java Cheat Sheet

This section covers the core concepts of Java, which are essential for every Java developer to understand.

Java Virtual Machine (JVM)

  • JVM: The Java Virtual Machine is responsible for running Java bytecode. It enables Java's platform independence.
  • JRE (Java Runtime Environment): Provides the libraries and other components that the JVM uses.
  • JDK (Java Development Kit): A bundle containing JRE and development tools like the Java compiler.

Object-Oriented Programming (OOP)

Java is primarily an object-oriented programming language, which means it emphasizes the use of objects and classes.

Exception Handling

try {
int division = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}

Java OOPs Cheat Sheet

Object-Oriented Programming is a key aspect of Java. Below are the pillars of OOP and how they are implemented in Java.

Classes and Objects

  • Class: Blueprint of an object. Defines properties (fields) and behaviors (methods).
  • Object: Instance of a class.
class Car {
    String color;
    int speed;

    void accelerate() {
        System.out.println("Accelerating");
    }
}

Car myCar = new Car();
myCar.color = "Red";
myCar.accelerate();

Inheritance

Inheritance allows one class to inherit properties and behaviors from another class.

class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks");
    }
}

Dog dog = new Dog();
dog.eat();  // Output: This animal eats food
dog.bark(); // Output: The dog barks

Polymorphism

  • Method Overloading: Same method name with different parameters.
  • Method Overriding: Subclass provides a specific implementation of a method already defined in its superclass.
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

Encapsulation

Encapsulation restricts direct access to data fields and provides getter/setter methods.

class Employee {
    private int salary;

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

Abstraction

Abstraction is the concept of hiding the implementation details and showing only functionality.

abstract class Animal {
    abstract void makeSound();
}

class Cat extends Animal {
    void makeSound() {
        System.out.println("Meow");
    }
}

Java Data Structures Cheat Sheet

Understanding common data structures is crucial for coding interviews. This section of the java data structures cheat sheet covers important data structures in Java.

Arrays

Arrays are fixed-size data structures in Java.

int[] array = new int[5];
array[0] = 10;
System.out.println(array[0]); // Output: 10

ArrayList

ArrayLists are dynamic arrays and part of Java’s collection framework.

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list.get(0)); // Output: Java

HashMap

HashMap is a key-value pair data structure.

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Java", 1);
map.put("Python", 2);
System.out.println(map.get("Java")); // Output: 1

Stack

Stack follows the LIFO (Last In, First Out) principle.

import java.util.Stack;

Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop()); // Output: 20

Queue

Queue follows the FIFO (First In, First Out) principle.

import java.util.LinkedList;
import java.util.Queue;

Queue<Integer> queue = new LinkedList<>();
queue.add(10);
queue.add(20);
System.out.println(queue.remove()); // Output: 10

Java DSA Cheat Sheet

For coding interviews, knowledge of data structures and algorithms (DSA) is essential. Here is a java DSA cheat sheet to help you prepare for interviews.

Searching Algorithms

  • Linear Search: Traverse through the array to find the target element.
public static int linearSearch(int[] array, int target) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            return i;
        }
    }
    return -1;
}
  • Binary Search: Requires a sorted array and divides the search space in half.
public static int binarySearch(int[] array, int target) {
    int left = 0, right = array.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (array[mid] == target)
            return mid;
        if (array[mid] < target)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return -1;
}

Sorting Algorithms

  • Bubble Sort: Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
public static void bubbleSort(int[] array) {
    for (int i = 0; i < array.length - 1; i++) {
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
}
  • Merge Sort: Divide and conquer algorithm that splits the array into halves, recursively sorts them, and merges them back together.
public static void mergeSort(int[] array, int left, int right) {
    if (left < right) {
        int mid = (left + right) / 2;
        mergeSort(array, left, mid);
        mergeSort(array, mid + 1, right);
        merge(array, left, mid, right);
    }
}

private static void merge(int[] array, int left, int mid, int right) {
    int n1 = mid - left + 1;
    int n2 = right - mid;

    int[] L = new int[n1];
    int[] R = new int[n2];

    System.arraycopy(array, left, L, 0, n1);
    System.arraycopy(array, mid + 1, R, 0, n2);

    int i = 0, j = 0;
    int k = left;

    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            array[k] = L[i];
            i++;
        } else {
            array[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
        array[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
        array[k] = R[j];
        j++;
        k++;
    }
}

Recursion

Recursion is a technique where a function calls itself.

public static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}

Conclusion

This comprehensive Java cheat sheet for interview preparation and general coding provides a complete guide to the fundamental concepts of Java. From basic syntax, OOP principles, core Java topics, data structures, and algorithms, mastering these will put you on the right track to excel in your coding journey. Whether it’s java data structures cheat sheet or java DSA cheat sheet, this guide can be a valuable reference for both beginners and advanced learners preparing for interviews.

More Cheat Sheets and Top Picks

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter