Java Cheatsheet
Basics
Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Program Structure
Every Java program lives inside a class. The entry point is main. If you are learning to code, moving through a free coding curriculum, or using Java as your first typed language, start by getting this small program structure automatic before you add collections, classes, and interview-style problems.
// HelloWorld.java — file name must match public class name exactly public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Compile and run:
javac HelloWorld.java java HelloWorld java HelloWorld arg1 arg2 // pass command-line args java -cp . HelloWorld // explicit classpath
Packages and Imports
package com.example.myapp; // must be first non-comment statement import java.util.List; // single class import java.util.ArrayList; import java.util.*; // wildcard (all classes in package) import static java.lang.Math.sqrt; // static import — call sqrt() directly import static java.lang.Math.*; // all static members // Same package — no import needed // java.lang — always auto-imported (String, Integer, Math, System, etc.)
Variables and Assignment
int x = 10; // declare + initialize double pi = 3.14; boolean flag = true; char letter = 'A'; String name = "Alice"; // String is a class, not a primitive // Multiple declarations (same type) int a = 1, b = 2, c = 3; // Constants final int MAX = 100; final double TAX_RATE = 0.08; // var — local type inference (Java 10+) var count = 42; // inferred as int var message = "hello"; // inferred as String var list = new ArrayList<String>(); // inferred as ArrayList<String> // var is only for local variables; cannot use for fields or method params
Primitive Types at a Glance
| Type | Size | Default | Range / Notes |
|---|---|---|---|
byte | 8-bit | 0 | -128 to 127 |
short | 16-bit | 0 | -32,768 to 32,767 |
int | 32-bit | 0 | -2^31 to 2^31-1 (~2.1 billion) |
long | 64-bit | 0L | suffix L — 9_999L |
float | 32-bit | 0.0f | suffix f — 3.14f; ~7 significant digits |
double | 64-bit | 0.0d | default decimal literal; ~15 digits |
char | 16-bit | '\0' | Unicode code unit, single quotes 'A' |
boolean | — | false | true or false only |
Numeric Literals
int dec = 1_000_000; // underscores for readability (Java 7+) int hex = 0xFF; // hexadecimal (255) int oct = 0755; // octal (493) int bin = 0b1010_1100; // binary (Java 7+) long big = 9_876_543_210L; float f = 1.5f; double d = 1.5e10; // scientific notation → 15000000000.0
Arithmetic Operators
int a = 10, b = 3; a + b // 13 a - b // 7 a * b // 30 a / b // 3 (integer division, truncates toward zero) a % b // 1 (remainder; sign follows dividend) // Floating-point division (double) a / b // 3.333... // Increment / decrement a++; // post-increment — returns old value, then increments ++a; // pre-increment — increments first, returns new value a--; --a; // Compound assignment a += 5; a -= 5; a *= 2; a /= 2; a %= 3; a <<= 1; a >>= 1; a &= 0xFF; a |= 0x80; a ^= 1;
Comparison and Logical Operators
// Comparison (return boolean) a == b // equal — primitives: value; objects: reference (use .equals() for objects) a != b // not equal a > b a < b a >= b a <= b // Logical true && false // AND — false (short-circuit: right side skipped if left is false) true || false // OR — true (short-circuit: right side skipped if left is true) !true // NOT — false // Bitwise variants (no short-circuit — evaluate both sides) true & false // AND (always evaluates both) true | false // OR (always evaluates both) true ^ false // XOR (exclusive or) // Ternary int max = (a > b) ? a : b; String label = (n == 1) ? "item" : "items";
Bitwise Operators
int x = 0b1010, y = 0b1100; x & y // AND → 0b1000 (8) x | y // OR → 0b1110 (14) x ^ y // XOR → 0b0110 (6) ~x // NOT → bitwise complement (all bits flipped) x << 2 // left shift (multiply by 2^n) x >> 1 // signed right shift (divide by 2, sign-extends) x >>> 1 // unsigned right shift (zero-fills from left)
Type Casting
// Widening (automatic, no data loss) int i = 42; long l = i; // 42L float f = i; // 42.0f double d = i; // 42.0 // Narrowing (explicit cast, possible data loss) double pi = 3.99; int n = (int) pi; // 3 — truncates toward zero long big = 3_000_000_000L; int small = (int) big; // overflow possible // char ↔ int char c = (char) 65; // 'A' int code = (int) 'A'; // 65 // String conversions int x2 = Integer.parseInt("42"); double y2 = Double.parseDouble("3.14"); long l2 = Long.parseLong("999"); String s = String.valueOf(42); String s2 = Integer.toString(42); String s3 = "" + 42; // concatenation trick
Output
System.out.println("line + newline"); System.out.print("no newline"); System.out.printf("Name: %s, Age: %d%n", "Alice", 30); System.out.printf("Pi: %.4f%n", Math.PI); // Formatted string (Java 15+) String msg = "Hello %s!".formatted("Bob"); String msg2 = String.format("Score: %d", 99); // stderr System.err.println("error message");
printf / format Specifiers
| Specifier | Type | Example |
|---|---|---|
%d | decimal integer | 42 |
%f | float/double | 3.140000 |
%.2f | 2 decimal places | 3.14 |
%s | String | "hello" |
%c | char | 'A' |
%b | boolean | true |
%n | newline (portable) | — |
%x | hex lowercase | ff |
%X | hex uppercase | FF |
%o | octal | 377 |
%e | scientific notation | 3.140000e+00 |
%,d | thousands separator | 1,000,000 |
%-10s | left-align in 10-char field | — |
%10s | right-align in 10-char field | — |
%05d | zero-pad to width 5 | 00042 |
Input (Scanner)
import java.util.Scanner; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double d = sc.nextDouble(); long l = sc.nextLong(); boolean b = sc.nextBoolean(); String word = sc.next(); // one token (whitespace-delimited) String line = sc.nextLine(); // entire line including spaces sc.close();
After
nextInt()/nextDouble(), callsc.nextLine()to consume the trailing newline before reading the next full line.
// Check before reading if (sc.hasNextInt()) { int x = sc.nextInt(); } if (sc.hasNextDouble()) { double d2 = sc.nextDouble(); } if (sc.hasNextLine()) { String l2 = sc.nextLine(); } // Read file with Scanner Scanner fileSc = new Scanner(new java.io.File("input.txt")); while (fileSc.hasNextLine()) { System.out.println(fileSc.nextLine()); } fileSc.close();
Scope and Access Modifiers
// Block scope { int local = 5; // only visible inside this block } // local not accessible here // Method scope — parameters and local vars public void method(int param) { int local = 10; // param and local exist until method returns } // Access modifiers (applied to classes, fields, methods, constructors) public // accessible everywhere protected // same package + all subclasses (default) // same package only (no keyword — also called "package-private") private // same class only
Static Members
public class Counter { private static int count = 0; // class-level (shared by all instances) public static final int MAX = 999; // class constant public Counter() { count++; } public static int getCount() { return count; } // no 'this', no instance access // static methods cannot call instance methods or access instance fields } // Called on the class, not an object Counter.getCount(); int max = Counter.MAX;
Math Utilities
Math.abs(-5) // 5 Math.abs(-3.7) // 3.7 Math.max(3, 7) // 7 Math.min(3, 7) // 3 Math.pow(2, 10) // 1024.0 (returns double) Math.sqrt(16.0) // 4.0 Math.cbrt(27.0) // 3.0 Math.floor(3.9) // 3.0 Math.ceil(3.1) // 4.0 Math.round(3.5) // 4 (returns long for double input) Math.round(3.4) // 3 Math.log(Math.E) // 1.0 (natural log) Math.log10(1000) // 3.0 Math.exp(1) // 2.718... (e^x) Math.sin(Math.PI/2) // 1.0 Math.cos(0) // 1.0 Math.tan(Math.PI/4) // ~1.0 Math.atan2(1, 1) // PI/4 Math.hypot(3, 4) // 5.0 Math.signum(-5.0) // -1.0 Math.random() // [0.0, 1.0) — prefer java.util.Random for seeded Math.PI // 3.141592653589793 Math.E // 2.718281828459045
Autoboxing and Wrapper Classes
// Autoboxing: primitive → wrapper (automatic) Integer a = 42; // int → Integer Double d = 3.14; // double → Double Boolean b = true; // boolean → Boolean // Unboxing: wrapper → primitive (automatic) int x = a; // Integer → int double y = d; // Double → Double // Wrapper class methods Integer.parseInt("123") // "123" → 123 Integer.toString(123) // 123 → "123" Integer.MAX_VALUE // 2147483647 Integer.MIN_VALUE // -2147483648 Integer.MAX_VALUE + 1 // -2147483648 (integer overflow — wraps!) Integer.toBinaryString(10) // "1010" Integer.toHexString(255) // "ff" Integer.toOctalString(8) // "10" Integer.bitCount(255) // 8 Integer.compare(a, b) // negative/0/positive Integer.sum(a, b) // a + b Integer.max(a, b) // max of two Integer.min(a, b) // min of two Double.parseDouble("3.14") Double.isNaN(0.0 / 0.0) // true Double.isInfinite(1.0 / 0.0) // true Character.isDigit('5') // true Character.isLetter('a') // true Character.isWhitespace(' ') // true Character.toUpperCase('a') // 'A' // NullPointerException trap! Integer n = null; int y2 = n; // NPE during unboxing!
Command-Line Arguments
public static void main(String[] args) { System.out.println("Number of args: " + args.length); for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] = " + args[i]); } // Enhanced for for (String arg : args) { System.out.println(arg); } } // java MyProgram hello world 42 // args[0]="hello", args[1]="world", args[2]="42" // args are always Strings — parse as needed
Comments