Java Basics Cheat Sheet
Types, operators, strings, input and output, conditions, loops, arrays, and methods at a glance.
Updated
Program structure#
public class Main { // file must be Main.java
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}javac Main.java
java Main
java Main.java # run a single file directly (Java 11+)Types and variables#
int count = 42; // whole numbers (32-bit)
long big = 9_000_000_000L; // 64-bit, note the L
double price = 49.99; // decimals (default choice)
char grade = 'A'; // single quotes
boolean ok = true;
String name = "Asha"; // double quotes, a class
var total = price * count; // inferred: double
final double TAX = 0.18; // cannot change
static final int MAX_USERS = 100; // class constant (field)Operators#
int a = 7 / 2; // 3
double b = 7.0 / 2; // 3.5
int c = 7 % 2; // 1
double d = (double) 7 / 2; // 3.5
double p = Math.pow(2, 10); // 1024.0
long r = Math.round(2.5); // 3Conversions#
int n = Integer.parseInt("42"); // String -> int (NumberFormatException if invalid)
double x = Double.parseDouble("3.75");
String s = String.valueOf(99); // number -> String
int i = (int) 99.99; // 99 (truncates)
int digit = '7' - '0'; // 7Output and input#
System.out.println("Line"); // with newline
System.out.print("No newline");
System.out.printf("%s is %d, %.2f%n", "Asha", 21, 92.5);
String text = String.format("%05d", 42); // "00042"
Scanner in = new Scanner(System.in); // import java.util.Scanner;
int age = in.nextInt();
in.nextLine(); // consume the leftover newline
String line = in.nextLine();Strings#
String s = "Hello, Java";
s.length(); // 11
s.charAt(0); // 'H'
s.substring(7); // "Java"
s.indexOf("Java"); // 7 (-1 if missing)
s.contains("Java"); // true
s.toUpperCase(); // new string: "HELLO, JAVA"
s.replace("Java", "World"); // "Hello, World"
" hi ".strip(); // "hi"
"a,b,c".split(","); // ["a", "b", "c"]
String.join("-", "a", "b"); // "a-b"
s.equals("Hello, Java"); // compare text (never ==)
"ab".repeat(3); // "ababab"
StringBuilder sb = new StringBuilder();
sb.append("x").append(1).reverse(); // build text in loopsConditions#
if (score >= 90) {
grade = 'A';
} else if (score >= 75) {
grade = 'B';
} else {
grade = 'C';
}
String kind = switch (day) { // switch expression (Java 14+)
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> "invalid";
};Loops#
for (int i = 0; i < 5; i++) { } // 0..4
for (String item : items) { } // for-each
while (balance < target) { } // check first
do { } while (choice != 0); // at least once
break; // leave the loop
continue; // next iteration
outer: // labeled break leaves nested loops
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (r * c == 2) break outer;
}
}Arrays#
int[] nums = {42, 7, 19};
int[] zeros = new int[5]; // 0 0 0 0 0
int len = nums.length; // 3 (a field, no parentheses)
int first = nums[0]; // 42 (index out of range throws)
Arrays.sort(nums); // import java.util.Arrays;
String shown = Arrays.toString(nums); // "[7, 19, 42]"
int[] firstTwo = Arrays.copyOf(nums, 2); // [7, 19]
int[][] grid = new int[3][4]; // 3 rows, 4 columnsMethods#
static int square(int n) { // call from main without an object
return n * n;
}
static double average(double... values) { return 0; } // varargs
static int area(int side) { return side * side; } // overloads:
static int area(int width, int height) { return width * height; } // same name, different parametersJava passes arguments by value: primitives are copied, and object references are copied (the object itself is shared).
Common errors#
Want the full explanations? Go to the Learn Java course →