iZONE

Java Cheatsheet

A practical Java guide covering syntax, OOP, collections, streams, concurrency, JVM fundamentals, and modern Java features.

Resources

What is Java?

Java is a programming language built around one idea: write the code once, run it anywhere. It compiles to bytecode that runs on the JVM — so the same program works on Windows, Mac, and Linux without changes.

how java runs — the JVM model

source code (.java)you write this
  • The file you write — plain text with Java syntax.
  • Every file has the same name as the class inside it.
compiler (javac)javac Hello.java
  • Turns your .java file into bytecode.
  • Output is a .class file — not machine code yet.
JVM (Java Virtual Machine)java Hello
  • Reads the .class file and runs it on your machine.
  • Every OS has its own JVM — your code stays the same.

your first java program

Java

// filename must be: Hello.java
public class Hello {

    // program starts here
    public static void main(String[] args) {

        // print with newline
        System.out.println("Hello, World!");

        // print without newline
        System.out.print("Hello ");

        // formatted output
        System.out.printf("Age: %d%n", 25);
    }
}

compile and run

Bash

# step 1: compile the source file
javac Hello.java
# creates Hello.class

# step 2: run the compiled program
java Hello
# output: Hello, World!

# check your Java version
java -version

# compile all .java files in a folder
javac *.java

comments

Java

// single-line comment

/*
  multi-line comment
  can span many lines
*/

/**
 * Javadoc comment — used to generate
 * official documentation.
 *
 * @param name the user's name
 * @return     a greeting string
 */
public String greet(String name) {
    return "Hello, " + name;
}

Variables & Data Types

Java has eight primitive types built into the language. Everything else — Strings, arrays, objects — is a reference type. That distinction matters more than it sounds.

the eight primitive types

Java

byte   b = 100;
short  s = 30_000;
int    i = 2_000_000;
long   l = 9_000_000_000L;  // needs L

float  f = 3.14f;           // needs f
double d = 3.14159265;

boolean flag = true;
char    c    = 'A';

// underscores make big numbers readable
int million = 1_000_000;

declaring and initialising variables

Java

// declare with explicit type
int age = 25;
String name = "Alice";

// var: Java infers the type (Java 10+)
var score = 100;       // int
var city  = "Colombo"; // String
var price = 9.99;      // double

// constant: cannot be reassigned
final double PI = 3.14159;

// class-level constant
static final int MAX_SIZE = 100;

// declare now, assign later
int count;
count = 0; // must assign before using

type casting — converting between types

Java

// widening — automatic, no data loss
int    i = 42;
long   l = i;      // int → long
double d = i;      // int → double

// narrowing — manual cast required
double price = 9.99;
int    cents = (int) price; // 9 (decimal lost)

long big = 1234567890123L;
int  n   = (int) big;       // data may be lost

// String ↔ number conversions
String s = String.valueOf(42);    // "42"
int    x = Integer.parseInt("42"); // 42
double y = Double.parseDouble("3.14"); // 3.14
long   z = Long.parseLong("9999");     // 9999

Strings

Strings in Java are objects, not primitives. That's worth knowing early — because it changes how you compare them and how you build them efficiently.

creating strings and concatenation

Java

// two ways to create a String
String s1 = "Hello";
String s2 = new String("Hello");

// concatenation with +
String name = "Alice";
String msg  = "Hello, " + name + "!";
// "Hello, Alice!"

// + order matters
String a = 3 + "str" + 3;   // "3str3"
String b = 3 + 3 + "str";   // "6str"
String c = "str" + 3 + 3;   // "str33"

// convert anything to String
String n = String.valueOf(42);     // "42"
String f = String.valueOf(3.14);   // "3.14"
String k = String.valueOf(true);   // "true"

common string methods

Java

String s = "Hello, World!";

// length and access
s.length();          // 13
s.charAt(0);         // 'H'
s.charAt(7);         // 'W'

// search
s.indexOf("o");      // 4 (first match)
s.lastIndexOf("o");  // 8 (last match)
s.contains("World"); // true
s.startsWith("Hello"); // true
s.endsWith("!");       // true

// extract
s.substring(7);      // "World!"
s.substring(7, 12);  // "World"

// modify (returns new String)
s.toLowerCase();     // "hello, world!"
s.toUpperCase();     // "HELLO, WORLD!"
s.trim();            // removes leading/trailing spaces
s.replace("World", "Java"); // "Hello, Java!"

// split into array
"a,b,c".split(",");  // ["a", "b", "c"]

// check empty
"".isEmpty();        // true
"  ".isBlank();      // true (Java 11+)

== vs .equals() — the most common bug

Java

String a = new String("hello");
String b = new String("hello");

// ❌ compares memory addresses
a == b              // false (different objects)

// ✅ compares content
a.equals(b)         // true

// case insensitive comparison
a.equalsIgnoreCase("HELLO")  // true

// alphabetical comparison
"apple".compareTo("banana")  // negative (a < b)
"banana".compareTo("apple")  // positive (b > a)
"apple".compareTo("apple")   // 0 (equal)

// safe null check — put the literal first
"hello".equals(someVariable)
// won't throw NullPointerException
// if someVariable is null

Using == to compare Strings can return false even when both Strings contain identical text. Always use .equals() for content comparison.

StringBuilder — efficient string building

Java

// ❌ slow: creates a new String every iteration
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i; // 1000 new String objects
}

// ✅ fast: modifies in place
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i);
}
String result = sb.toString();

// StringBuilder methods
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World");   // "Hello, World"
sb.insert(5, "!");      // "Hello!, World"
sb.delete(5, 6);        // "Hello, World"
sb.replace(7, 12, "Java"); // "Hello, Java"
sb.reverse();           // "avaJ ,olleH"
sb.length();            // current length
sb.toString();          // convert to String

Operators

Operators are the symbols that do the actual work on your data. Most are familiar, but a few Java-specific behaviours trip people up — especially integer division and the ternary.

arithmetic and assignment operators

Java

// arithmetic
int a = 10, b = 3;
a + b   // 13
a - b   // 7
a * b   // 30
a / b   // 3   (decimal dropped!)
a % b   // 1   (remainder)

// fix integer division
(double) a / b  // 3.333...
10.0 / 3        // 3.333...

// increment and decrement
int x = 5;
x++;   // x = 6 (post-increment)
x--;   // x = 5 (post-decrement)
++x;   // x = 6 (pre-increment)

// assignment shorthand
x += 3;  // x = x + 3
x -= 2;  // x = x - 2
x *= 4;  // x = x * 4
x /= 2;  // x = x / 2
x %= 3;  // x = x % 3

comparison, logical, and ternary operators

Java

// comparison — always return boolean
int a = 5, b = 10;
a == b   // false
a != b   // true
a > b    // false
a < b    // true
a >= b   // false
a <= b   // true

// logical operators
boolean x = true, y = false;
x && y   // false (AND — both must be true)
x || y   // true  (OR  — one must be true)
!x       // false (NOT — flips the value)

// short-circuit evaluation
// && stops at first false
// || stops at first true
int n = 0;
if (n != 0 && 10 / n > 2) {
    // safe: won't divide by zero
    // because n != 0 is false, && stops
}

// ternary: condition ? valueIfTrue : valueIfFalse
int age = 20;
String label = (age >= 18) ? "Adult" : "Minor";

// ternary in a method call
System.out.println(
    (age >= 18) ? "Adult" : "Minor"
);

Control Flow

Control flow decides which code runs and when. Java's if/else is exactly what you'd expect. The switch statement got a significant upgrade in Java 14 — worth knowing both forms.

if, else if, else

Java

int score = 75;

// basic if-else
if (score >= 90) {
    System.out.println("A");
} else if (score >= 75) {
    System.out.println("B");
} else if (score >= 60) {
    System.out.println("C");
} else {
    System.out.println("F");
}

// single-line (no braces for one statement)
// only use for very simple cases
if (score > 50)
    System.out.println("Passed");

// nested if
if (score >= 50) {
    if (score >= 90) {
        System.out.println("Excellent pass");
    } else {
        System.out.println("Passed");
    }
}

switch — classic and arrow syntax

Java

// classic switch — break required
String day = "MON";
switch (day) {
    case "MON":
        System.out.println("Monday");
        break;  // without break, falls through
    case "TUE":
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Other day");
}

// arrow switch (Java 14+) — no break needed
switch (day) {
    case "MON" -> System.out.println("Monday");
    case "TUE" -> System.out.println("Tuesday");
    case "SAT", "SUN" -> System.out.println("Weekend");
    default    -> System.out.println("Weekday");
}

// switch expression — returns a value (Java 14+)
String label = switch (day) {
    case "MON" -> "Monday";
    case "TUE" -> "Tuesday";
    default    -> "Other";
};

Loops

Java has four kinds of loops. The for loop is the most common. The enhanced for-each is the cleanest when you just need to read every item. And do-while is the one that always runs at least once.

for loop and enhanced for-each

Java

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

// count down
for (int i = 5; i > 0; i--) {
    System.out.println(i); // 5 4 3 2 1
}

// loop through an array by index
int[] nums = {10, 20, 30, 40};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

// enhanced for-each — cleaner for reading
for (int n : nums) {
    System.out.println(n);
}

// for-each over a String array
String[] names = {"Alice", "Bob", "Carol"};
for (String name : names) {
    System.out.println("Hello, " + name);
}

while, do-while, break, continue

Java

// while — checks condition first
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

// do-while — runs at least once
int j = 10;
do {
    System.out.println(j); // prints 10
    j++;
} while (j < 5);
// condition false, but body ran once

// break — exit the loop immediately
for (int k = 0; k < 10; k++) {
    if (k == 5) break;
    System.out.print(k + " "); // 0 1 2 3 4
}

// continue — skip this iteration
for (int k = 0; k < 5; k++) {
    if (k == 2) continue;
    System.out.print(k + " "); // 0 1 3 4
}

// labelled break — exit outer loop
outer:
for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 3; c++) {
        if (r == 1 && c == 1) break outer;
        System.out.println(r + "," + c);
    }
}

Arrays

An array holds a fixed number of values of the same type. Fixed means once you set the size, it doesn't grow. If you need a resizable list, use ArrayList instead.

declare, initialise, and access

Java

// declare and create with size
int[] scores = new int[5];
// [0, 0, 0, 0, 0] — defaults to 0

// declare and initialise at once
int[]    nums  = {10, 20, 30, 40, 50};
String[] names = {"Alice", "Bob", "Carol"};

// access by index (starts at 0)
System.out.println(nums[0]); // 10
System.out.println(nums[4]); // 50

// update a value
nums[2] = 99;

// get the length
System.out.println(nums.length); // 5

// last element
System.out.println(nums[nums.length - 1]);

multidimensional arrays

Java

// 2D array — rows and columns
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// access: [row][column]
matrix[0][0]; // 1
matrix[1][2]; // 6
matrix[2][1]; // 8

// iterate a 2D array
for (int r = 0; r < matrix.length; r++) {
    for (int c = 0; c < matrix[r].length; c++) {
        System.out.print(matrix[r][c] + " ");
    }
    System.out.println();
}

// for-each on 2D array
for (int[] row : matrix) {
    for (int val : row) {
        System.out.print(val + " ");
    }
}

Arrays utility class

Java

import java.util.Arrays;

int[] nums = {5, 2, 8, 1, 9, 3};

// sort in place
Arrays.sort(nums);
// [1, 2, 3, 5, 8, 9]

// print array contents
System.out.println(Arrays.toString(nums));
// [1, 2, 3, 5, 8, 9]

// fill with a value
Arrays.fill(nums, 0);
// [0, 0, 0, 0, 0, 0]

// copy (new array, different length)
int[] copy = Arrays.copyOf(nums, 3);
// [0, 0, 0]

// copy a range
int[] partial = Arrays.copyOfRange(nums, 1, 4);

// binary search (array must be sorted first)
int[] sorted = {1, 3, 5, 7, 9};
Arrays.binarySearch(sorted, 7); // returns 3

// 2D array to string
int[][] grid = {{1,2},{3,4}};
System.out.println(Arrays.deepToString(grid));
// [[1, 2], [3, 4]]

Methods

A method is a named block of code you can call as many times as you need. Java methods always belong to a class. If you need a method available without creating an object, mark it static.

defining and calling methods

Java

public class Calculator {

    // static method — no object needed
    public static int add(int a, int b) {
        return a + b;
    }

    // returns nothing
    public static void printSum(int a, int b) {
        System.out.println(a + b);
    }

    // multiple parameters
    public static double average(
        int a, int b, int c
    ) {
        return (a + b + c) / 3.0;
    }

    public static void main(String[] args) {
        int sum = add(3, 4);        // 7
        printSum(5, 6);             // 11
        double avg = average(3,6,9); // 6.0
    }
}

method overloading

Java

// three versions of the same method name
static int add(int a, int b) {
    return a + b;
}

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

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

// Java picks the right one automatically
add(1, 2);        // calls int version  → 3
add(1.5, 2.5);    // calls double version → 4.0
add(1, 2, 3);     // calls three-param  → 6

recursion and varargs

Java

// recursion — a method that calls itself
// always needs a base case to stop
static int factorial(int n) {
    if (n == 0) return 1;    // base case
    return n * factorial(n - 1);
}

factorial(5); // 5*4*3*2*1 = 120

// fibonacci
static int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

// varargs — accept any number of arguments
// must be the last parameter
static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) {
        total += n;
    }
    return total;
}

sum(1, 2);          // 3
sum(1, 2, 3, 4, 5); // 15
sum();               // 0

OOP — Classes & Objects

Everything in Java is a class. A class is the blueprint — an object is a copy of that blueprint filled with real values. Understanding this difference is the foundation of Java.

class structure and creating objects

Java

// define the class
public class Person {

    // fields (instance variables)
    String name;
    int    age;

    // constructor — runs when object is created
    public Person(String name, int age) {
        // 'this' refers to the current object
        this.name = name;
        this.age  = age;
    }

    // instance method
    public void introduce() {
        System.out.println(
            "Hi, I'm " + name
            + " and I'm " + age
        );
    }
}

// create objects with 'new'
Person alice = new Person("Alice", 28);
Person bob   = new Person("Bob",   32);

// access fields and methods
System.out.println(alice.name); // Alice
alice.introduce();  // Hi, I'm Alice and I'm 28
bob.introduce();    // Hi, I'm Bob and I'm 32

access modifiers and encapsulation

Java

public class BankAccount {

    // private: only this class can access
    private double balance;
    private String owner;

    public BankAccount(String owner, double balance) {
        this.owner   = owner;
        this.balance = balance;
    }

    // getter — read the value
    public double getBalance() {
        return balance;
    }

    // setter — write the value with validation
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

BankAccount acc = new BankAccount("Alice", 1000);
acc.deposit(500);
acc.getBalance(); // 1500.0
// acc.balance = 9999; ← compile error (private)

constructors and static members

Java

public class Counter {

    // static field — shared across ALL instances
    private static int totalCreated = 0;

    // instance field — unique per object
    private int count;

    // no-arg constructor (default)
    public Counter() {
        this.count = 0;
        totalCreated++;
    }

    // overloaded constructor
    public Counter(int startValue) {
        this.count = startValue;
        totalCreated++;
    }

    public void increment() { count++; }
    public int  getCount()  { return count; }

    // static method — call on class, not object
    public static int getTotalCreated() {
        return totalCreated;
    }
}

Counter a = new Counter();    // count = 0
Counter b = new Counter(10);  // count = 10
a.increment(); // a.count = 1

// call static method on the class
Counter.getTotalCreated(); // 2

OOP — Inheritance & Interfaces

Inheritance lets one class reuse and extend another. Interfaces define a contract — a list of methods a class must provide. Together they're the backbone of how large Java programs are organised.

extends — inheriting from a class

Java

// parent class
public class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " makes a sound");
    }
}

// subclass — inherits from Animal
public class Dog extends Animal {

    public Dog(String name) {
        super(name); // call parent constructor
    }

    // override the parent method
    @Override
    public void speak() {
        System.out.println(name + " barks");
    }

    // new method only in Dog
    public void fetch() {
        System.out.println(name + " fetches!");
    }
}

Dog d = new Dog("Rex");
d.speak();  // Rex barks
d.fetch();  // Rex fetches!

// parent reference can hold child object
Animal a = new Dog("Buddy");
a.speak();  // Buddy barks (polymorphism)

abstract classes and interfaces

Java

// abstract class — cannot be instantiated
public abstract class Shape {
    // abstract method — must be implemented
    public abstract double area();

    // concrete method — shared by all shapes
    public void describe() {
        System.out.println(
            "Area: " + area()
        );
    }
}

public class Circle extends Shape {
    double radius;

    Circle(double r) { this.radius = r; }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

// interface — defines a contract
public interface Printable {
    void print(); // implicitly public abstract

    // default method (Java 8+)
    default void printTwice() {
        print();
        print();
    }
}

// implement multiple interfaces
public class Report
    extends Document
    implements Printable, Saveable {

    @Override
    public void print() {
        System.out.println("Printing report...");
    }
}

instanceof and casting objects

Java

Animal a = new Dog("Rex");

// instanceof: check before casting
if (a instanceof Dog) {
    Dog d = (Dog) a; // safe downcast
    d.fetch();
}

// Java 16+ pattern matching — cleaner
if (a instanceof Dog d) {
    // d is already cast — no separate line
    d.fetch();
}

// upcasting — always safe, implicit
Dog dog = new Dog("Rex");
Animal animal = dog; // Dog IS-A Animal

// downcasting — must be explicit
// throws ClassCastException if wrong type
Animal a2 = new Animal("Cat");
Dog d2 = (Dog) a2; // ← ClassCastException!
// use instanceof check to avoid this

Collections

The Collections Framework gives you resizable lists, sets with no duplicates, and key-value maps. These three cover the vast majority of real Java programming needs.

ArrayList — resizable list

Java

import java.util.ArrayList;

// <String> is the generic type parameter
ArrayList<String> names = new ArrayList<>();

// add items
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add(1, "Dave"); // insert at index 1

// access
names.get(0);        // "Alice"
names.size();        // 4
names.contains("Bob"); // true
names.indexOf("Carol"); // 2

// update and remove
names.set(0, "Adam");      // replace index 0
names.remove("Bob");       // remove by value
names.remove(0);           // remove by index

// iterate
for (String name : names) {
    System.out.println(name);
}

// clear and check
names.clear();
names.isEmpty(); // true

HashMap — key-value pairs

Java

import java.util.HashMap;

// <KeyType, ValueType>
HashMap<String, Integer> scores = new HashMap<>();

// add / update entries
scores.put("Alice", 90);
scores.put("Bob",   85);
scores.put("Carol", 92);
scores.put("Alice", 95); // updates existing key

// access
scores.get("Alice");            // 95
scores.getOrDefault("Dave", 0); // 0 (safe default)
scores.containsKey("Bob");      // true
scores.containsValue(85);       // true
scores.size();                  // 3

// remove
scores.remove("Bob");

// iterate entries
for (var entry : scores.entrySet()) {
    System.out.println(
        entry.getKey() + ": " + entry.getValue()
    );
}

// iterate keys only
for (String key : scores.keySet()) {
    System.out.println(key);
}

// iterate values only
for (int val : scores.values()) {
    System.out.println(val);
}

HashSet — unique values only

Java

import java.util.HashSet;

HashSet<String> tags = new HashSet<>();

// add items — duplicates are silently ignored
tags.add("java");
tags.add("backend");
tags.add("java"); // ignored — already exists

tags.size();           // 2
tags.contains("java"); // true

// remove
tags.remove("backend");

// iterate (order is not guaranteed)
for (String tag : tags) {
    System.out.println(tag);
}

// useful: remove duplicates from a list
import java.util.ArrayList;
ArrayList<Integer> withDupes =
    new ArrayList<>();
withDupes.add(1);
withDupes.add(2);
withDupes.add(1); // duplicate

HashSet<Integer> unique = new HashSet<>(withDupes);
// {1, 2}

Exception Handling

Things go wrong at runtime — a file doesn't exist, a number can't be parsed, a network call fails. Exceptions are Java's way of handling those situations without crashing the whole program.

try, catch, finally

Java

// basic try-catch
try {
    int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
    System.out.println(e.getMessage()); // / by zero
}

// multiple catch blocks
try {
    String s = null;
    s.length(); // throws NullPointerException
} catch (NullPointerException e) {
    System.out.println("Null value: " + e.getMessage());
} catch (Exception e) {
    // catch-all — put most specific first
    System.out.println("Error: " + e.getMessage());
}

// finally — always runs
try {
    int[] arr = new int[3];
    arr[5] = 10; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index out of bounds");
} finally {
    System.out.println("This always runs");
}

throws, custom exceptions, try-with-resources

Java

// throws: declare that a method can throw
// caller must handle or declare it too
public static void readFile(String path)
    throws IOException {
    // code that might throw IOException
}

// throw: manually throw an exception
public static void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException(
            "Age cannot be negative"
        );
    }
}

// custom exception
public class InsufficientFundsException
    extends Exception {
    public InsufficientFundsException(String msg) {
        super(msg);
    }
}

// try-with-resources — auto-closes resources
// no need for finally to close the file
try (FileReader fr = new FileReader("file.txt")) {
    // fr is automatically closed after this block
    int data = fr.read();
} catch (IOException e) {
    System.out.println("File error: " + e.getMessage());
}

common exceptions to know

Java

// NullPointerException
String s = null;
s.length(); // ← NullPointerException

// ArrayIndexOutOfBoundsException
int[] arr = new int[3];
arr[5] = 10; // ← only indices 0,1,2 exist

// NumberFormatException
Integer.parseInt("abc"); // ← not a number

// ClassCastException
Object obj = "hello";
Integer i = (Integer) obj; // ← it's a String!

// StackOverflowError
void infinite() {
    infinite(); // ← no base case, never stops
}

// prevention pattern for NullPointerException
if (s != null) {
    s.length(); // safe
}
// or use Objects.requireNonNull()
import java.util.Objects;
Objects.requireNonNull(s, "s must not be null");

Tips & Good Habits

These are the habits that make Java code safer and easier to read. Some of them prevent bugs that are genuinely hard to track down — which makes them worth building into how you work from the start.

always use .equals() for object comparison

Java

// ❌ wrong — compares memory addresses
String a = new String("hello");
String b = new String("hello");
a == b       // false (different objects)

// ✅ correct — compares content
a.equals(b)  // true

// ✅ null-safe — put the literal first
"hello".equals(userInput);
// won't crash if userInput is null

// Integer comparison
Integer x = 200;
Integer y = 200;
x == y       // false (outside -128..127 cache)
x.equals(y)  // true ✅

use try-with-resources for anything that opens

Java

// ❌ easy to forget the close
FileReader fr = null;
try {
    fr = new FileReader("data.txt");
    // read file...
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fr != null) {
        try { fr.close(); }
        catch (IOException e) { }
    }
}

// ✅ try-with-resources closes automatically
// even if an exception is thrown
try (FileReader fr = new FileReader("data.txt")) {
    // read file...
} catch (IOException e) {
    e.printStackTrace();
}
// fr is guaranteed to be closed here

Not closing a file, database connection, or network socket is a resource leak. On a server, enough leaks will crash your application.

naming conventions — follow them

Java

// ✅ correct naming
public class UserAccount {                // PascalCase
    private static final int MAX_LOGIN = 3; // ALL_CAPS

    private String userName;               // camelCase
    private int    loginAttempts;

    public String getUserName() {          // camelCase
        return userName;
    }

    public void resetAttempts() {
        loginAttempts = 0;
    }
}

// ❌ avoid
public class user_account {    // wrong style
    private String UserName;   // looks like a class
    public void Reset() { }    // looks like a class
    static final int maxlogin = 3; // looks like variable
}

handy one-liners worth bookmarking

Java

// Math utility methods
Math.max(10, 20);        // 20
Math.min(10, 20);        // 10
Math.abs(-42);           // 42
Math.pow(2, 10);         // 1024.0
Math.sqrt(144);          // 12.0
Math.round(3.6);         // 4
Math.random();           // 0.0 to <1.0

// random int between 1 and 100
int rand = (int)(Math.random() * 100) + 1;

// String.format — like printf but returns a String
String msg = String.format(
    "Name: %s, Age: %d, Score: %.2f",
    "Alice", 28, 95.5678
);
// "Name: Alice, Age: 28, Score: 95.57"

// Collections utility methods
import java.util.Collections;
import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<>();
list.add(3); list.add(1); list.add(2);

Collections.sort(list);     // [1, 2, 3]
Collections.reverse(list);  // [3, 2, 1]
Collections.max(list);      // 3
Collections.min(list);      // 1
Collections.shuffle(list);  // random order

// swap two variables without a temp variable
int a = 1, b = 2;
a = a + b; b = a - b; a = a - b;
// a=2, b=1
Was this helpful?

No login required to share feedback

More Cheatsheets

Keep your reference handy

Explore more zero-to-hero cheatsheets for the tools you use daily.