learn.fttgsolutions.com · Cheat Sheets
Write Once. Run Anywhere.
Getting Started
| Hello World | public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} | Every Java program needs a class with a main method as its entry point. |
| Print | System.out.println("text"); | Prints a line to the console. Use print() to omit the newline, or printf() for formatted output. |
| Comments | // single line
/* multi-line */
/** javadoc */ | Three comment styles: single-line (//), block (/* */), and Javadoc (/** */) for documentation. |
| Import | import java.util.ArrayList; | Import a class from a package to use it without its fully qualified name. |
Primitive Data Types
| int | int age = 25; | 32-bit signed integer. Range: -2,147,483,648 to 2,147,483,647. Default: 0. |
| long | long big = 10000000000L; | 64-bit signed integer. Suffix L for literals. Use when int is too small. |
| double | double price = 9.99; | 64-bit floating-point. Default choice for decimals. Default: 0.0. |
| float | float rate = 3.14f; | 32-bit floating-point. Suffix f for literals. Less precise than double. |
| boolean | boolean flag = true; | true or false only. Default: false. |
| char | char letter = 'A'; | Single 16-bit Unicode character. Use single quotes. |
| byte | byte b = 127; | 8-bit signed integer. Range: -128 to 127. Default: 0. |
| short | short s = 32000; | 16-bit signed integer. Range: -32,768 to 32,767. Default: 0. |
Variables & Type Casting
| Declare & assign | int x = 10; | Declare a variable with a type, name, and value in one statement. |
| Widening cast | int i = 42;
double d = i; | Automatically converts a smaller type to a larger type. No data loss. |
| Narrowing cast | double d = 9.99;
int i = (int) d; | Explicitly convert a larger type to a smaller type. May lose data (9.99 → 9). |
| String → int | int n = Integer.parseInt("42"); | Parse a String to an int. Throws NumberFormatException if the string is not a valid integer. |
| String → double | double d = Double.parseDouble("3.14"); | Parse a String to a double. |
| int → String | String s = String.valueOf(42); | Convert any primitive to a String using String.valueOf(). |
| var (Java 10+) | var list = new ArrayList<String>(); | Local variable type inference — the compiler infers the type from the right-hand side. |
Strings
| Create | String s = "Hello";
String s2 = new String("Hello"); | String literals are preferred — they are cached in the string pool. |
| Concatenate | String full = "Hello" + " " + "World"; | Use + to join strings. Numbers are automatically converted to strings. |
| Length | s.length() | Returns the number of characters in the string. |
| charAt() | s.charAt(0) | Returns the character at the given index (zero-based). |
| indexOf() | s.indexOf("lo") | Returns the index of the first occurrence of a substring, or -1 if not found. |
| substring() | s.substring(1, 4) | Extracts characters from start index (inclusive) to end index (exclusive). |
| toUpperCase() | s.toUpperCase() | Returns a new string with all characters converted to uppercase. |
| toLowerCase() | s.toLowerCase() | Returns a new string with all characters converted to lowercase. |
| trim() | s.trim() | Removes leading and trailing whitespace from the string. |
| replace() | s.replace("old", "new") | Returns a new string with all occurrences of the first argument replaced by the second. |
| contains() | s.contains("ell") | Returns true if the string contains the specified sequence of characters. |
| startsWith() | s.startsWith("He") | Returns true if the string begins with the specified prefix. |
| endsWith() | s.endsWith("lo") | Returns true if the string ends with the specified suffix. |
| equals() | s.equals(s2) | Compares two strings by value. Use equals() not == for string comparison. |
| isEmpty() | s.isEmpty() | Returns true if the string has length zero. |
| split() | String[] parts = s.split(","); | Splits the string around matches of the given regex and returns a String array. |
| StringBuilder | StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString(); | Mutable string builder — use instead of concatenating with + in loops for better performance. |
Arrays
| Declare & init | int[] nums = {1, 2, 3, 4, 5}; | Declare and initialize an array with literal values. |
| Declare with size | String[] names = new String[3]; | Create an array of a fixed size. Elements default to null (objects) or 0 (primitives). |
| Access element | nums[0] | Access element at index 0. Arrays are zero-indexed. |
| Length | nums.length | The .length property (not a method) returns the number of elements. |
| Sort | Arrays.sort(nums); | Sorts the array in ascending order in-place. Import java.util.Arrays. |
| To string | Arrays.toString(nums) | Returns a readable string representation like [1, 2, 3]. |
| 2D array | int[][] grid = {{1,2},{3,4}}; | Declare a 2D array with nested initializers. |
| 2D access | grid[0][1] | Access the element at row 0, column 1. |
Operators
| Arithmetic | + - * / % | Add, subtract, multiply, divide, and modulus (remainder). |
| Increment | i++ / ++i | Post-increment (i++) returns current value then adds 1. Pre-increment (++i) adds 1 first. |
| Decrement | i-- / --i | Post-decrement returns current value then subtracts 1. Pre-decrement subtracts 1 first. |
| Comparison | == != > < >= <= | Compare two values. Return a boolean. Use .equals() for object comparison. |
| Logical | && || ! | AND (&&), OR (||), NOT (!). Short-circuit — the right side isn't evaluated if the result is determined by the left. |
| Assignment | += -= *= /= %= | Compound assignment operators. x += 5 is shorthand for x = x + 5. |
| Ternary | int max = (a > b) ? a : b; | Shorthand if/else. condition ? valueIfTrue : valueIfFalse. |
| instanceof | obj instanceof String | Returns true if obj is an instance of String (or a subclass/interface). |
| Bitwise | & | ^ ~ << >> | AND, OR, XOR, NOT, left-shift, right-shift — operate on individual bits. |
Conditionals
| if / else if / else | if (x > 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
} | Standard conditional branching. Only one branch executes. |
| switch | switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
default: System.out.println("Other");
} | Matches a value against cases. Always include break to prevent fall-through. default is optional. |
| switch expression (Java 14+) | String result = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
default -> "Other";
}; | Arrow syntax returns a value directly. No break needed. |
Loops
| for loop | for (int i = 0; i < 5; i++) {
System.out.println(i);
} | Classic counted loop with init, condition, and update expressions. |
| enhanced for (for-each) | for (String item : list) {
System.out.println(item);
} | Iterate over arrays or collections without index management. |
| while loop | while (condition) {
// ...
} | Repeats while the condition is true. May not execute at all if condition is false initially. |
| do-while loop | do {
// ...
} while (condition); | Like while, but the body always executes at least once before the condition is checked. |
| break | if (i == 3) break; | Immediately exits the loop body. |
| continue | if (i == 3) continue; | Skips the rest of the current iteration and moves to the next. |
Collections
| ArrayList | List<String> list = new ArrayList<>();
list.add("a");
list.get(0);
list.size();
list.remove(0); | Ordered, resizable list backed by an array. Fast random access but slow inserts/removes in the middle. |
| HashMap | Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.get("a");
map.containsKey("a");
map.remove("a"); | Key-value store with O(1) average lookup. Unordered. Keys and values must be objects. |
| HashSet | Set<String> set = new HashSet<>();
set.add("x");
set.contains("x");
set.remove("x"); | Unordered collection of unique values. O(1) average add/contains/remove. |
| LinkedList | Queue<String> q = new LinkedList<>();
q.add("first");
q.poll(); | Doubly-linked list. Use as a Queue (FIFO) or Deque. Slow random access. |
| ArrayDeque | Deque<String> dq = new ArrayDeque<>();
dq.addFirst("a");
dq.addLast("b");
dq.peek();
dq.pop(); | Resizable array-based deque. Use as a Stack (LIFO) or Queue. Generally faster than LinkedList. |
| Iterate map | map.forEach((key, val) -> System.out.println(key + ":" + val)); | Iterate all key/value pairs using forEach with a lambda. |
| Collections.sort() | Collections.sort(list); | Sort a List in natural order. Pass a Comparator for custom ordering. |
Classes & Objects
| Class definition | public class Dog {
String name;
Dog(String name) { this.name = name; }
void bark() { System.out.println("Woof!"); }
} | A class is a blueprint. The constructor initializes a new object instance. |
| Create object | Dog d = new Dog("Rex"); | Instantiate a class with new and call its constructor. |
| this keyword | this.name = name; | Refers to the current object instance. Used to distinguish fields from constructor/method parameters. |
| Inheritance | public class Poodle extends Dog {
Poodle(String name) { super(name); }
} | extends sets the parent class. super() calls the parent constructor. |
| Interface | interface Swimmable { void swim(); }
class Duck extends Animal implements Swimmable { ... } | Interfaces define a contract of methods a class must implement. A class can implement multiple interfaces. |
| Static method | public static int add(int a, int b) { return a + b; } | Belongs to the class, not an instance. Call as ClassName.method() without creating an object. |
| Getter / Setter | public String getName() { return name; }
public void setName(String name) { this.name = name; } | Encapsulate private fields with public accessor and mutator methods. |
Exception Handling
| try / catch / finally | try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Always runs");
} | try wraps risky code, catch handles specific exceptions, finally always executes (cleanup). |
| throws declaration | public void readFile() throws IOException { ... } | Declares that a method may throw a checked exception — callers must handle or rethrow it. |
| throw | throw new IllegalArgumentException("Bad input"); | Explicitly throw an exception. Use custom messages to aid debugging. |
| Common exceptions | NullPointerException
ArrayIndexOutOfBoundsException
ClassCastException
NumberFormatException
IllegalArgumentException
IOException | Frequently encountered Java exceptions. RuntimeExceptions are unchecked; IOException requires handling. |
Access Modifiers
| public | public int value; | Accessible from any class in any package. |
| protected | protected int value; | Accessible within the same package and by subclasses in other packages. |
| default (package-private) | int value; | No modifier — accessible only within the same package. |
| private | private int value; | Accessible only within the declaring class. Used for encapsulation. |
| final | final int MAX = 100; | Variable: cannot be reassigned. Method: cannot be overridden. Class: cannot be extended. |
| static | static int count = 0; | Belongs to the class rather than any instance. Shared across all objects. |
Math Methods
| max() / min() | Math.max(10, 20) // 20
Math.min(10, 20) // 10 | Return the larger or smaller of two values. |
| abs() | Math.abs(-7) // 7 | Returns the absolute (non-negative) value. |
| pow() | Math.pow(2, 10) // 1024.0 | Returns the first argument raised to the power of the second. |
| sqrt() | Math.sqrt(16) // 4.0 | Returns the positive square root. |
| round() | Math.round(3.7) // 4 | Rounds to the nearest integer. |
| random() | Math.random() // 0.0 to <1.0 | Returns a random double in [0, 1). Multiply and cast to get integers: (int)(Math.random() * 10). |
| floor() / ceil() | Math.floor(3.9) // 3.0
Math.ceil(3.1) // 4.0 | floor() rounds down; ceil() rounds up. |
User Input
| Scanner setup | import java.util.Scanner;
Scanner sc = new Scanner(System.in); | Import Scanner and create an instance connected to standard input. |
| Read string | String line = sc.nextLine(); | Reads a full line of input as a String. |
| Read int | int n = sc.nextInt(); | Reads the next token as an integer. Throws InputMismatchException for non-integers. |
| Read double | double d = sc.nextDouble(); | Reads the next token as a double. |
| Close scanner | sc.close(); | Release the scanner resource when done reading input. |