Java
Updated: September 8, 2025Categories: Languages, Backend, Mobile, Frontend
Printed from:
Java Cheatsheet
Language Overview
Java is a robust, object-oriented, statically-typed programming language developed by Sun Microsystems (now owned by Oracle). Key characteristics include:
- Platform independence ("Write Once, Run Anywhere")
- Strong typing
- Automatic memory management (Garbage Collection)
- Enterprise-level application development
- Used in web, mobile, desktop, and enterprise applications
Basic Syntax
Java
12345678910111213// Single-line comment
/* Multi-line comment */
// Basic program structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// Semicolons are required to end statements
// Curly braces {} define code blocks
Data Types
Primitive Types
Java
12345678910111213141516// Integers
byte byteVar = 127; // 8-bit signed two's complement integer
short shortVar = 32767; // 16-bit signed two's complement integer
int intVar = 2147483647; // 32-bit signed two's complement integer
long longVar = 9223372036854775807L; // 64-bit signed two's complement integer
// Floating-point
float floatVar = 3.14f; // 32-bit IEEE 754 floating point
double doubleVar = 3.14159; // 64-bit IEEE 754 floating point
// Character
char charVar = 'A'; // 16-bit Unicode character
// Boolean
boolean boolVar = true; // true or false
Collection Types
Java
123456789101112131415161718// Lists
List<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
// Sets
Set<Integer> hashSet = new HashSet<>();
hashSet.add(1);
hashSet.add(2);
// Maps
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("key", 42);
// Queues
Queue<String> queue = new LinkedList<>();
queue.add("First");
Variables and Constants
Java
12345678910111213141516// Variable declaration
int age = 30; // Mutable variable
final int MAX_SIZE = 100; // Constant (cannot be changed)
// Type inference (Java 10+)
var dynamicVar = "Hello"; // Type inferred at compile-time
// Scope
public class ScopeExample {
private int instanceVar; // Class-level variable
public void method() {
int localVar = 10; // Method-level variable
}
}
Operators
Arithmetic Operators
Java
1234567int a = 10, b = 5;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int div = a / b; // Division
int mod = a % b; // Modulus
Comparison Operators
Java
12345boolean result = (a == b); // Equal to
boolean notEqual = (a != b); // Not equal to
boolean greater = (a > b); // Greater than
boolean greaterEqual = (a >= b); // Greater than or equal to
Logical Operators
Java
12345boolean x = true, y = false;
boolean andResult = x && y; // Logical AND
boolean orResult = x || y; // Logical OR
boolean notResult = !x; // Logical NOT
Control Structures
Conditional Statements
Java
12345678910111213141516171819// If-Else
if (condition) {
// Code if true
} else if (anotherCondition) {
// Alternative condition
} else {
// Default case
}
// Ternary Operator
int result = (condition) ? valueIfTrue : valueIfFalse;
// Switch Statement (Java 12+)
switch (value) {
case 1 -> System.out.println("One");
case 2 -> System.out.println("Two");
default -> System.out.println("Other");
}
Loops
Java
123456789101112131415161718192021222324252627// For Loop
for (int i = 0; i < 10; i++) {
// Repeat code
}
// Enhanced For Loop (For-Each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// While Loop
while (condition) {
// Repeat while condition is true
}
// Do-While Loop
do {
// Execute at least once
} while (condition);
// Break and Continue
for (int i = 0; i < 10; i++) {
if (i == 5) break; // Exit loop
if (i % 2 == 0) continue; // Skip current iteration
}
Functions
Java
12345678910111213141516171819202122// Basic Method
public int add(int a, int b) {
return a + b;
}
// Method with Multiple Parameters
public void printDetails(String name, int age) {
System.out.println(name + " is " + age + " years old");
}
// Static Method (belongs to class, not instance)
public static void staticMethod() {
// Can be called without creating an object
}
// Lambda Expressions (Java 8+)
interface MathOperation {
int operate(int a, int b);
}
MathOperation addition = (a, b) -> a + b;
Object-Oriented Programming
Classes and Objects
Java
123456789101112131415161718192021222324public class Person {
// Fields (attributes)
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter and Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Object Creation
Person person = new Person("John", 30);
Inheritance
Java
12345678910111213141516171819public class Animal {
protected String name;
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
public void bark() {
System.out.println("Woof!");
}
}
Interfaces and Abstract Classes
Java
1234567891011121314// Interface
public interface Drawable {
void draw(); // Public and abstract by default
}
// Abstract Class
public abstract class Shape {
abstract double calculateArea();
public void display() {
System.out.println("This is a shape");
}
}
Error Handling
Java
12345678910111213141516171819202122232425262728// Try-Catch Block
try {
// Code that might throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
// Code that always runs
}
// Throwing Exceptions
public void checkAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
// Multiple Catch Blocks
try {
// Some code
} catch (NullPointerException e) {
// Handle null pointer
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index
} catch (Exception e) {
// Handle any other exception
}
File I/O
Java
12345678910111213141516171819import java.io.*;
// Reading a File
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Writing to a File
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
Stream API (Java 8+)
Java
123456789101112List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Filter and Collect
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
// Map and Reduce
int totalLength = names.stream()
.mapToInt(String::length)
.sum();
Common Libraries and Frameworks
Standard Library
java.util: Collections, Date/Time utilitiesjava.io: Input/Output operationsjava.nio: New I/O operationsjava.concurrent: Multithreading support
Popular Frameworks
- Spring Framework: Dependency Injection, Web Applications
- Spring Boot: Microservices, Auto-configuration
- Hibernate: ORM (Object-Relational Mapping)
- Apache Commons: Utility libraries
- JUnit: Unit Testing
- Mockito: Mocking Framework
Build Tools
Bash
12345678# Maven
mvn clean install # Build and install project
mvn test # Run tests
# Gradle
gradle build # Build project
gradle test # Run tests
Best Practices
- Follow Java naming conventions (camelCase for variables/methods, PascalCase for classes)
- Use meaningful variable and method names
- Keep methods small and focused
- Prefer composition over inheritance
- Use interfaces to define contracts
- Handle exceptions appropriately
- Use try-with-resources for automatic resource management
- Leverage generics for type safety
- Use final for immutability when possible
Testing with JUnit
Java
1234567891011import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
public void testAddition() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
Resources for Further Learning
- Official Java Documentation
- "Effective Java" by Joshua Bloch
- Oracle Java Tutorials
- Spring.io Documentation
- Coursera and Udemy Java Courses
- Stack Overflow Java Community
- GitHub Open Source Java Projects
Advanced Concepts
- Multithreading and Concurrency
- Java Memory Model
- Reflection
- Annotations
- Java Module System
- Performance Tuning
Continue Learning
Discover more cheatsheets to boost your productivity