
A quick reference for Java syntax covering the fundamentals. Bookmark this page for when you need a fast reminder.
Program Structure
// Every Java file needs a class matching the filename
public class MyProgram {
// Entry point - execution starts here
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Variables and Data Types
Primitive Types
// Integers
byte b = 127; // 8-bit, -128 to 127
short s = 32000; // 16-bit
int i = 2147483647; // 32-bit (most common)
long l = 9223372036854775807L; // 64-bit, note the L suffix
// Floating point
float f = 3.14f; // 32-bit, note the f suffix
double d = 3.14159265359; // 64-bit (default for decimals)
// Other primitives
boolean flag = true; // true or false
char c = 'A'; // Single character, use single quotes
Reference Types
String text = "Hello"; // Strings use double quotes
int[] numbers = {1, 2, 3}; // Arrays
Integer num = 42; // Wrapper class (nullable)
Type Inference (Java 10+)
var count = 10; // Compiler infers int
var name = "Alice"; // Compiler infers String
var list = new ArrayList<String>(); // Compiler infers ArrayList<String>
Constants
final int MAX_SIZE = 100; // Cannot be reassigned
static final double PI = 3.14159; // Class-level constant
Operators
Arithmetic
int a = 10, b = 3;
a + b // 13 (addition)
a - b // 7 (subtraction)
a * b // 30 (multiplication)
a / b // 3 (integer division)
a % b // 1 (modulo/remainder)
a++ // Post-increment (returns a, then adds 1)
++a // Pre-increment (adds 1, then returns)
a-- // Post-decrement
--a // Pre-decrement
Comparison
a == b // Equal to
a != b // Not equal to
a > b // Greater than
a < b // Less than
a >= b // Greater than or equal
a <= b // Less than or equal
Logical
&& // AND (short-circuit)
|| // OR (short-circuit)
! // NOT
// Examples
if (a > 0 && b > 0) { } // Both must be true
if (a > 0 || b > 0) { } // At least one must be true
if (!flag) { } // Negation
Assignment
a = 10; // Assign
a += 5; // a = a + 5
a -= 5; // a = a - 5
a *= 2; // a = a * 2
a /= 2; // a = a / 2
a %= 3; // a = a % 3
Ternary
// condition ? valueIfTrue : valueIfFalse
int max = (a > b) ? a : b;
String status = (age >= 18) ? "adult" : "minor";
Strings
// Creation
String s1 = "Hello";
String s2 = new String("Hello");
// Concatenation
String full = "Hello" + " " + "World";
String msg = "Value: " + 42; // Auto-converts int to String
// Common methods
s1.length() // 5
s1.charAt(0) // 'H'
s1.substring(1, 4) // "ell"
s1.toLowerCase() // "hello"
s1.toUpperCase() // "HELLO"
s1.trim() // Remove leading/trailing whitespace
s1.replace("l", "x") // "Hexxo"
s1.contains("ell") // true
s1.startsWith("He") // true
s1.endsWith("lo") // true
s1.indexOf("l") // 2
s1.split(",") // Split into array
// Comparison (NEVER use == for strings)
s1.equals(s2) // true
s1.equalsIgnoreCase("HELLO") // true
s1.compareTo(s2) // 0 if equal
// Formatting
String.format("Name: %s, Age: %d", "Alice", 30);
String.format("Price: $%.2f", 19.99);
// Text blocks (Java 15+)
String json = """
{
"name": "Alice",
"age": 30
}
""";
Control Flow
If-Else
if (condition) {
// code
} else if (otherCondition) {
// code
} else {
// code
}
Switch
// Traditional switch
switch (value) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Other");
}
// Enhanced switch (Java 14+)
String result = switch (day) {
case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
case "SAT", "SUN" -> "Weekend";
default -> "Unknown";
};
For Loop
// Standard for loop
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// Iterate over collection
List<String> names = List.of("Alice", "Bob");
for (String name : names) {
System.out.println(name);
}
While Loop
// While
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
// Do-while (executes at least once)
do {
System.out.println(i);
i++;
} while (i < 10);
Loop Control
break; // Exit loop immediately
continue; // Skip to next iteration
// Labeled break (for nested loops)
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (condition) break outer;
}
}
Arrays
// Declaration and initialization
int[] arr1 = new int[5]; // Array of 5 zeros
int[] arr2 = {1, 2, 3, 4, 5}; // Initialize with values
int[] arr3 = new int[]{1, 2, 3}; // Explicit initialization
// Access and modify
arr1[0] = 10; // Set first element
int first = arr1[0]; // Get first element
int len = arr1.length; // Array length (property, not method)
// Multi-dimensional arrays
int[][] matrix = new int[3][3];
int[][] grid = {{1, 2}, {3, 4}, {5, 6}};
grid[0][1] = 10; // Access element
// Common operations (use Arrays class)
import java.util.Arrays;
Arrays.sort(arr2); // Sort in place
Arrays.fill(arr1, 0); // Fill with value
int idx = Arrays.binarySearch(arr2, 3); // Search (must be sorted)
int[] copy = Arrays.copyOf(arr2, arr2.length);
boolean equal = Arrays.equals(arr1, arr2);
String str = Arrays.toString(arr2); // "[1, 2, 3, 4, 5]"
Methods
// Basic method
public void sayHello() {
System.out.println("Hello");
}
// Method with parameters and return value
public int add(int a, int b) {
return a + b;
}
// Static method (call without instance)
public static double square(double x) {
return x * x;
}
// Method overloading (same name, different parameters)
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
// Variable arguments (varargs)
public int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
// Call: sum(1, 2, 3) or sum(1, 2, 3, 4, 5)
Classes and Objects
public class Person {
// Fields (instance variables)
private String name;
private int age;
// Static field (shared by all instances)
private static int count = 0;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
count++;
}
// Default constructor
public Person() {
this("Unknown", 0); // Call other constructor
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
// Instance method
public String greet() {
return "Hi, I'm " + name;
}
// Static method
public static int getCount() {
return count;
}
// toString for printing
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
// Usage
Person p = new Person("Alice", 30);
p.getName(); // "Alice"
p.greet(); // "Hi, I'm Alice"
Person.getCount(); // Static method call
Inheritance
// Parent class
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println("Some sound");
}
}
// Child class
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // Call parent constructor
this.breed = breed;
}
@Override
public void speak() {
System.out.println(name + " says Woof!");
}
public void fetch() {
System.out.println(name + " fetches the ball");
}
}
// Usage
Dog dog = new Dog("Buddy", "Labrador");
dog.speak(); // "Buddy says Woof!"
dog.fetch(); // "Buddy fetches the ball"
Interfaces
public interface Drawable {
void draw(); // Abstract method
default void print() { // Default method (Java 8+)
System.out.println("Printing...");
}
static void info() { // Static method
System.out.println("Drawable interface");
}
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing circle");
}
}
// Multiple interfaces
public class Shape implements Drawable, Comparable<Shape> {
// Must implement all abstract methods
}
Abstract Classes
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// Abstract method (must be implemented by subclasses)
public abstract double area();
// Concrete method
public void displayColor() {
System.out.println("Color: " + color);
}
}
public class Rectangle extends Shape {
private double width, height;
public Rectangle(String color, double width, double height) {
super(color);
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
Exception Handling
// Try-catch-finally
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Always executes");
}
// Multiple catch blocks
try {
// risky code
} catch (FileNotFoundException e) {
// handle file not found
} catch (IOException e) {
// handle other IO errors
} catch (Exception e) {
// handle any other exception
}
// Multi-catch (Java 7+)
try {
// risky code
} catch (IOException | SQLException e) {
// handle either exception type
}
// Try-with-resources (auto-closes resources)
try (FileReader reader = new FileReader("file.txt");
BufferedReader br = new BufferedReader(reader)) {
String line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// Throwing exceptions
public void validate(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
// Declaring checked exceptions
public void readFile(String path) throws IOException {
// code that might throw IOException
}
Common Collections
import java.util.*;
// List (ordered, allows duplicates)
List<String> list = new ArrayList<>();
list.add("item");
list.get(0);
list.remove(0);
list.size();
// Set (no duplicates)
Set<String> set = new HashSet<>();
set.add("item");
set.contains("item");
set.remove("item");
// Map (key-value pairs)
Map<String, Integer> map = new HashMap<>();
map.put("key", 100);
map.get("key");
map.containsKey("key");
map.remove("key");
map.keySet();
map.values();
// Iterate collections
for (String item : list) { }
for (Map.Entry<String, Integer> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
// Immutable collections (Java 9+)
List<String> immutable = List.of("a", "b", "c");
Set<Integer> immutableSet = Set.of(1, 2, 3);
Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);
Lambda Expressions
// Basic syntax: (parameters) -> expression
// No parameters
Runnable r = () -> System.out.println("Hello");
// One parameter (parentheses optional)
Consumer<String> print = s -> System.out.println(s);
// Multiple parameters
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
// Block body
Comparator<String> comp = (a, b) -> {
int result = a.length() - b.length();
return result;
};
// Method references
list.forEach(System.out::println); // Instance method
list.sort(String::compareToIgnoreCase); // Instance method
list.stream().map(String::toUpperCase); // Instance method
numbers.stream().map(Integer::parseInt); // Static method
Streams
List<String> names = List.of("Alice", "Bob", "Charlie");
// Filter
names.stream()
.filter(n -> n.length() > 3)
.forEach(System.out::println);
// Map (transform)
List<Integer> lengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
// Common operations
names.stream().count(); // Count elements
names.stream().findFirst(); // Optional<String>
names.stream().anyMatch(n -> n.startsWith("A")); // boolean
names.stream().sorted(); // Sort
names.stream().distinct(); // Remove duplicates
names.stream().limit(2); // Take first 2
// Reduce
int sum = numbers.stream().reduce(0, Integer::sum);
Input/Output
import java.util.Scanner;
import java.io.*;
// Console input
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
int num = scanner.nextInt();
double d = scanner.nextDouble();
scanner.close();
// Console output
System.out.println("With newline");
System.out.print("Without newline");
System.out.printf("Formatted: %s, %d%n", "text", 42);
// File reading (modern way)
String content = Files.readString(Path.of("file.txt"));
List<String> lines = Files.readAllLines(Path.of("file.txt"));
// File writing
Files.writeString(Path.of("file.txt"), "content");
Files.write(Path.of("file.txt"), lines);
Access Modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | No |
| (default) | Yes | Yes | No | No |
| private | Yes | No | No | No |
Useful Keywords
final // Cannot be changed (variable), overridden (method), or extended (class)
static // Belongs to class, not instance
abstract // Must be implemented by subclass
synchronized // Thread-safe access
volatile // Variable may be modified by multiple threads
transient // Skip during serialization
this // Reference to current object
super // Reference to parent class
instanceof // Check object type
// Examples
if (obj instanceof String s) { // Pattern matching (Java 16+)
System.out.println(s.length());
}
Related: Java String Methods Cheat Sheet | Java Collections Cheat Sheet | Java Variables and Data Types | Java Operators Explained
Sources
- Oracle. “The Java Language Specification.” docs.oracle.com/javase/specs
- Oracle. “Java SE Documentation.” docs.oracle.com/en/java/javase/21


