Posted in

Java Complete Cheatsheet – 2025 Ultimate Edition

java cheatsheet

1. Basic Structure & Syntax

class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Comments

// Single line
/* Multi-line */

2. Data Types & Variables

TypeExampleBytes
byte1271
short320002
int1000004
long100000L8
float3.14f4
double3.141598
char‘A’2
booleantrue/false1
String“Hello”varies

Type Casting

int x = 10;
double y = x;       // implicit
int z = (int) y;    // explicit

3. Operators

+ - * / %, ++ --, == != > < >= <=, && || !, = += -= *= /=, & | ^ ~ << >> >>>

4. Control Flow

if (x > 10) { }
else if (x == 10) { }
else { }

Switch (Modern)

int day = 2;
String result = switch (day) {
    case 1 -> "Mon";
    case 2 -> "Tue";
    default -> "Weekend";
};

Loops

for (int i = 0; i < 5; i++) { }
while (condition) { }
do { } while (condition);
for (int i : arr) { }

5. Methods

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

Overloading

void print(int a) {}
void print(String s) {}

6. OOP: Classes & Objects

class Car {
    String color;
    Car(String color) { this.color = color; }
    void drive() { System.out.println(color + " car drives"); }
}
Car c = new Car("Red");
c.drive();

7. Access Modifiers

ModifierScope
publicEverywhere
protectedSame package + subclass
defaultSame package
privateSame class

8. Inheritance

class Vehicle { void move(){} }
class Car extends Vehicle { void move(){ System.out.println("Car moves"); } }

super() → calls parent constructor or method.

9. Polymorphism

Vehicle v = new Car();
v.move(); // Car’s version

10. Abstraction

Abstract Class

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

Interface

interface Animal {
    void eat();
    default void sleep() { System.out.println("Sleeping"); }
}

11. Encapsulation

class Person {
    private String name;
    public String getName(){ return name; }
    public void setName(String n){ this.name = n; }
}

12. Packages

package com.example;
import java.util.*;

13. Exception Handling

try {
    int x = 10/0;
} catch (ArithmeticException e) {
    System.out.println(e);
} finally {
    System.out.println("Always runs");
}

Custom Exception

class MyException extends Exception {
    MyException(String msg){ super(msg); }
}

Try-With-Resources

try (Scanner sc = new Scanner(System.in)) {
    sc.nextLine();
}

14. Arrays

int[] nums = {1,2,3};
int[][] matrix = {{1,2}, {3,4}};

15. Strings

String s = "Hello";
s.length(); s.charAt(0); s.equals("Hi");
s.toUpperCase(); s.substring(1);

16. Wrapper Classes

PrimitiveWrapper
intInteger
charCharacter
booleanBoolean
doubleDouble

17. Collections Framework

List

List<String> list = new ArrayList<>();
list.add("A");

Set

Set<Integer> set = new HashSet<>();

Map

Map<Integer, String> map = new HashMap<>();
map.put(1, "A");

Queue

Queue<String> q = new LinkedList<>();
q.add("Task");

18. Generics

class Box<T> { T val; Box(T val){this.val=val;} }
Box<Integer> b = new Box<>(5);

19. Lambda & Functional Programming

List<Integer> nums = List.of(1,2,3);
nums.forEach(n -> System.out.println(n));

Functional Interface

@FunctionalInterface
interface Greet { void say(String msg); }

20. Stream API

List<Integer> even = nums.stream()
                         .filter(n -> n%2==0)
                         .map(n -> n*2)
                         .toList();

Common methods: filter(), map(), reduce(), collect(), forEach()

21. Optional

Optional<String> name = Optional.ofNullable("Ravi");
name.ifPresent(System.out::println);

22. Multithreading

Extending Thread

class MyThread extends Thread {
    public void run(){ System.out.println("Running"); }
}
new MyThread().start();

Runnable Interface

Runnable r = () -> System.out.println("Thread running");
new Thread(r).start();

Executors (Modern)

ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("Task"));
pool.shutdown();

23. Synchronization

synchronized void printNumbers(){ ... }

24. Concurrent Utilities

Lock lock = new ReentrantLock();
CountDownLatch latch = new CountDownLatch(3);
AtomicInteger count = new AtomicInteger(0);

25. File I/O

try (FileWriter fw = new FileWriter("test.txt")) {
    fw.write("Hello");
}

BufferedReader br = new BufferedReader(new FileReader("test.txt"));
System.out.println(br.readLine());

26. Networking

Client-Server Example

// Server
ServerSocket ss = new ServerSocket(8080);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());

// Client
Socket s = new Socket("localhost", 8080);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello Server");

27. JDBC (Database Connectivity)

import java.sql.*;

Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/test", "root", "password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users");
while(rs.next()) System.out.println(rs.getString("name"));
con.close();

28. Reflection API

Class<?> c = Class.forName("java.lang.String");
Method[] methods = c.getDeclaredMethods();
for (Method m : methods) System.out.println(m.getName());

29. Annotations

@interface MyAnno { String value(); }
@MyAnno("Hello")
public class Test {}

Built-in: @Override, @Deprecated, @SuppressWarnings, @FunctionalInterface

30. Serialization

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.ser"));
oos.writeObject(obj);
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.ser"));
MyClass obj = (MyClass) ois.readObject();

31. Java Modules (Java 9+)

module-info.java

module com.app {
    requires java.sql;
    exports com.app.service;
}

32. Design Patterns (Essentials)

PatternDescription
SingletonOne instance globally
FactoryCreates objects without exposing logic
BuilderStep-by-step object creation
ObserverNotify all dependents on change
StrategyChoose algorithm dynamically
DecoratorAdd features dynamically
AdapterConvert one interface to another

33. JVM & Memory

AreaDescription
HeapObjects
StackMethod calls
Method AreaClass info
PC RegisterThread execution point
GCAutomatic cleanup

34. Performance & GC

Use flags:

java -Xms512m -Xmx1024m MyApp

GC Types: Serial, Parallel, G1, ZGC (Java 15+)

35. Security

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest("password".getBytes());

36. Modern Java Features (14–21)

VersionFeatureExample
14Switch Expressionscase 1 -> "One";
15Text Blocks"""Multi-line"""
16Recordsrecord Point(int x, int y) {}
17Sealed Classessealed class Shape permits Circle {}
19Virtual ThreadsThread.startVirtualThread(() -> {});
21Pattern Matching for Switchcase String s -> ...;

37. Testing (JUnit 5)

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CalcTest {
    @Test
    void addTest() {
        assertEquals(4, 2 + 2);
    }
}

38. Build Tools

Maven

pom.xml – dependency management

Gradle

build.gradle – modern alternative

39. Common Libraries

  • Lombok → boilerplate reduction (@Getter, @Setter)
  • Jackson/Gson → JSON parsing
  • Log4j / SLF4J → Logging
  • JUnit 5 → Testing

40. Compilation & Execution

javac Main.java
java Main

Checkout My YouTube Channel

Checkout All CheatSheets

  1. CSS Cheat Sheet

Personal Recommendation:

  1. CSS CheatSheet
  2. JavaScript CheatSheet
  3. React CheatSheet
  4. Python CheatSheet

Read my other Blogs

  1. Top 5 Mistakes Beginners Make While Learning to Code (And How to Avoid Them)
  2. Best Programming Languages to Learn in 2025 (and Why)
  3. Before You Learn Web Development: The Advice No One Gave Me
  4. How to Start Coding in 2025: Beginner’s Roadmap
  5. Why Coding is Important: The Language of the Future
  6. Are Coding and Programming the Same? – The Complete Truth You Need to Know
  7. Will Coding Be Replaced by AI?
  8. C++ Programming: Everything You Need to Know

I’m Shaurya, a developer simplifying tech with tutorials, tools, and projects to help you learn, build, and grow in the world of coding.

Leave a Reply

Your email address will not be published. Required fields are marked *