Java Syntax Quick Reference
Reference · Print-friendly
Primitive Types
| Type |
Size |
Default |
Range |
byte |
1 B |
0 |
-128 to 127 |
short |
2 B |
0 |
-32,768 to 32,767 |
int |
4 B |
0 |
-2B to 2B |
long |
8 B |
0L |
-9e18 to 9e18 |
float |
4 B |
0.0f |
±3.4e38 |
double |
8 B |
0.0d |
±1.7e308 |
char |
2 B |
'\u0000' |
0 to 65,535 (Unicode) |
boolean |
1 bit |
false |
true / false |
Access Modifiers
| Modifier |
Class |
Package |
Subclass |
World |
public |
Y |
Y |
Y |
Y |
protected |
Y |
Y |
Y |
N |
| default |
Y |
Y |
N |
N |
private |
Y |
N |
N |
N |
Non-Access Modifiers
static — belongs to class, not instance
final — class: can't extend; method: can't override; variable: constant
abstract — class: can't instantiate; method: no body, must override
synchronized — thread-safe access
transient — skip field during serialization
volatile — always read from main memory
Class Structure
public class MyClass extends Parent implements Interface1, Interface2 { // Fields (prefer private) private int x; // Constructor — same name as class, no return type public MyClass(int x) { this.x = x; } // Getter public int getX() { return x; } // Setter public void setX(int x) { this.x = x; } // Static method public static void main(String[] args) { } // Inner class static class Helper { }}
Constructor Patterns
// Default constructor (Java provides if none defined)public MyClass() { }// Parameterized constructorpublic MyClass(int x) { this.x = x; }// Constructor chainingpublic MyClass() { this(0); }public MyClass(int x) { this.x = x; }
Common Patterns
// For-each over array/Iterablefor (Type item : collection) { }// Scanner inputScanner sc = new Scanner(System.in);// String builderStringBuilder sb = new StringBuilder();sb.append("a").append("b");// try-with-resources (Java 7+)try (Scanner sc = new Scanner(new File("x.txt"))) { }// Enhanced switch (Java 14+)String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Unknown";};
Common Gotchas
-
== compares references for objects, use
.equals()
-
Strings are immutable —
+ in loops creates many objects, use
StringBuilder
-
Integer caching:
Integer.valueOf(127) == Integer.valueOf(127) is true, but 128 is
false
- Switch needs
break or fall-through happens
- Array index out of bounds is a runtime exception, not compile-time