Java Language Cheat Sheet
A searchable reference of common Java syntax and what each snippet does.
| Snippet | What it does |
|---|---|
public class Main {} | Declare a public class named Main; the source file must be named Main.java. |
public static void main(String[] args) {} | Program entry point that the JVM calls to start the application. |
System.out.println("Hello"); | Print a line of text to standard output followed by a newline. |
int count = 10; | Declare a 32-bit integer variable and assign it the value 10. |
long big = 9000000000L; | Declare a 64-bit integer; the L suffix marks the literal as a long. |
double price = 9.99; | Declare a 64-bit floating point number. |
boolean ok = true; | Declare a boolean that holds only true or false. |
char grade = 'A'; | Declare a single 16-bit character; character literals use single quotes. |
String name = "Ada"; | Declare a String, an object that holds immutable text. |
var list = new ArrayList<String>(); | Let the compiler infer the local variable type from the initializer (Java 10+). |
final int MAX = 100; | Declare a constant whose value cannot be reassigned after it is set. |
int n = (int) 3.9; | Cast a double to int; the fraction is dropped, giving 3. |
int[] nums = {1, 2, 3}; | Create a fixed size array of ints with three elements. |
nums.length | Get the number of elements in an array; length is a field, not a method. |
List<String> list = new ArrayList<>(); | Create a resizable list backed by an ArrayList. |
list.add("x"); | Append an element to the end of the list. |
list.get(0); | Read the element stored at index 0. |
Map<String, Integer> m = new HashMap<>(); | Create a key to value map backed by a HashMap. |
m.put("a", 1); | Store the value 1 under the key a, replacing any existing value. |
m.get("a"); | Look up the value for key a, or null when the key is absent. |
m.keySet(); | Get a Set view of every key in the map. |
List<Integer> ids = List.of(1, 2, 3); | Create an immutable list of the given elements (Java 9+). |
for (String s : list) {} | For-each loop that visits every element of a collection or array. |
Arrays.sort(nums); | Sort an array in place into ascending order. |
list.stream().filter(s -> s.length() > 2).count(); | Start a stream pipeline to filter elements and count the matches. |
if (x > 0) {} else {} | Run one block when the condition is true and another when it is false. |
for (int i = 0; i < n; i++) {} | Counting loop with an init, a condition, and an update step. |
for (int v : arr) {} | Enhanced for loop that reads each array or collection element in turn. |
while (cond) {} | Repeat the block while the condition holds, checking before each pass. |
do {} while (cond); | Repeat the block and check the condition after each pass, so it runs at least once. |
switch (day) { case 1: break; default: } | Branch to the matching case; use break to stop fall through. |
String s = switch (day) { case 1 -> "Mon"; default -> "?"; }; | Arrow form switch expression that returns a value with no fall through (Java 14+). |
int max = a > b ? a : b; | Ternary conditional expression that returns one of two values. |
break; | Exit the nearest enclosing loop or switch immediately. |
continue; | Skip the rest of this iteration and start the next one. |
class Dog {} | Define a class, the blueprint that objects are created from. |
Dog(String name) { this.name = name; } | Constructor that runs when an object is created to set up its fields. |
class Puppy extends Dog {} | Declare that Puppy inherits the fields and methods of Dog. |
class Dog implements Animal {} | Declare that Dog supplies every method the Animal interface requires. |
interface Animal { void speak(); } | Declare an interface, a contract of methods that implementers must provide. |
abstract class Shape { abstract double area(); } | Abstract class that cannot be instantiated and may leave methods unimplemented. |
this.count = count; | Refer to the current object, often to set a field from a parameter with the same name. |
super(name); | Call the parent class constructor or a parent method. |
static int count = 0; | Declare a member that belongs to the class itself rather than any instance. |
if (obj instanceof String s) {} | Test the type and bind it to a typed variable in one step (Java 16+). |
record Point(int x, int y) {} | Immutable data carrier that auto generates the constructor, accessors, equals, and hashCode (Java 16+). |
enum Color { RED, GREEN, BLUE } | Define a fixed set of named constants as their own type. |
int add(int a, int b) { return a + b; } | Declare a method that takes two ints and returns their sum. |
return value; | Exit the method and hand a value back to the caller. |
int area(int w) {} int area(int w, int h) {} | Overloading: reuse a method name with a different parameter list; the compiler picks by arguments. |
int sum(int... nums) {} | Varargs method that accepts any number of int arguments as an array. |
static int square(int n) { return n * n; } | Static method called on the class itself, with no object needed. |
<T> T first(List<T> items) { return items.get(0); } | Generic method with a type parameter T that works for any element type. |
try {} catch (IOException e) {} | Run code that may fail and handle the exception when it is thrown. |
try {} catch (Exception e) {} finally {} | Add a finally block that always runs, whether or not an exception occurred. |
try (var f = new FileReader("a.txt")) {} | Open a resource that is closed automatically at the end of the block (Java 7+). |
throw new IllegalArgumentException("bad"); | Raise an exception to signal an error condition. |
void read() throws IOException {} | Declare that a method may pass a checked exception up to its caller. |
class MyError extends Exception {} | Define your own checked exception by extending Exception. |
catch (IOException | SQLException e) {} | Multi-catch: handle several exception types in one block using the pipe symbol. |
No snippets match your search.
Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.
What this tool does
This is a searchable quick reference for the Java syntax you reach for every day, spanning the basics, collections, control flow, object-oriented keywords, method forms, and exception handling. Each row pairs a short snippet with a plain-English note on what it does, aimed at modern Java (version 17 and later). Type in the filter box to search across both columns, or tap a category button to focus on one topic. The whole list is built into the page, so it works offline and sends nothing anywhere.
How to use it
Start typing in the Filter box. Entering println jumps
to the print statement; entering HashMap surfaces the map operations;
entering switch shows both switch forms; entering record
finds the modern data carrier. The category buttons (Basics,
Collections, Control flow, OOP, Methods, Exceptions) narrow the table to one topic and
combine with the text filter, so you can pick Collections and type Map to
zero in on map methods. Clear the box to see the full sheet again.
Common use cases
- Recalling the exact form of a construct you use rarely, like the enhanced for loop or a switch expression.
- Copying a correct snippet into your editor instead of guessing the syntax.
- Comparing when to use a plain array versus an
ArrayList. - Reviewing the object-oriented keywords such as
extends,implements, andabstractbefore an interview. - Checking modern features like
record,var, and pattern matching forinstanceof.
Common pitfalls
- Comparing objects with ==. Using
==on two String values compares references, not text, so equal-looking strings can fail the check. Useequalsto compare values. - Integer division surprises. Dividing two ints performs integer
division and drops the remainder, so
5 / 2is2. Cast one operand with(double)first to keep the fractional part. - Modifying a list while looping. Removing an element inside a for-each loop throws a ConcurrentModificationException. Loop with an explicit iterator, or collect the items to remove and delete them afterward.
- Ignoring checked exceptions. Calling a method that declares
throwsforces you to either catch the exception or declarethrowson your own method. Swallowing it in an empty catch block hides real failures.
Frequently asked questions
- What is the difference between an array and an ArrayList?
- An array has a fixed length that you set when you create it and cannot grow or shrink, while an ArrayList is a resizable list from the java.util package that can add and remove elements at runtime. Arrays can hold primitives like int directly and use square bracket indexing, whereas an ArrayList stores objects and is used through methods such as add, get, and size. Use an array when the size is known and fixed, and an ArrayList when the number of elements changes.
- What is the difference between == and equals in Java?
- The == operator compares whether two references point to the exact same object in memory, while the equals method compares whether two objects are meaningfully equal in value. For objects such as String you almost always want equals, because two different String objects can hold the same text yet fail an == check. For primitive types like int there is no equals method and == correctly compares the values themselves.
- What are generics in Java?
- Generics let you write classes and methods that work with a type parameter supplied later, so one List type can be reused to hold String, Integer, or any other type with full compile time checking. Declaring a list of String tells the compiler that every element is a String, which removes the need for casts and catches type errors before the program runs. Generics improve both safety and readability without any runtime cost.
- What is a record in Java?
- A record, added in Java 16, is a compact way to declare an immutable class whose main job is to carry data. From a short header listing the components, the compiler generates the constructor, a private final field and accessor for each component, and sensible equals, hashCode, and toString methods. Records are ideal for simple value holders such as coordinates or data transfer objects where you would otherwise write a lot of boilerplate.
- What is try-with-resources?
- Try-with-resources is a form of the try statement, added in Java 7, that declares one or more resources in parentheses right after the try keyword. Any resource that implements AutoCloseable is closed automatically when the block finishes, whether it ends normally or through an exception, so you do not need a manual finally block to close files, streams, or database connections. This prevents the resource leaks that come from forgetting to close things by hand.
- Does this cheat sheet send my searches anywhere?
- No. The entire snippet list is baked into the page at build time and every search and filter runs locally in your browser with JavaScript, so nothing you type is sent to any server. You can open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.
Cite this tool
For academic, journalistic, or technical references. Pick a format:
Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.