Java cheat sheet
96 one-line examples for Java. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Print and Variables
| Code | What it does |
|---|---|
System.out.println("Hi"); | Print text and move to a new line. |
System.out.print("Hi"); | Print text and stay on the same line. |
int age = 20; | Declare a whole number variable. |
double price = 9.99; | Declare a decimal number variable. |
String name = "Ana"; | Declare a text variable. |
boolean ok = true; | Declare a true or false variable. |
char grade = 'A'; | Declare a single character variable. |
final int MAX = 10; | Declare a constant that cannot change. |
int x = 5, y = 6; | Declare two variables on one line. |
var count = 3; | Let Java infer the type of a local variable. |
System.out.println(age); | Print the value of a variable. |
System.out.printf("%d%n", age); | Print a number with a format string. |
Operators and Conditions
| Code | What it does |
|---|---|
int sum = a + b; | Add two numbers and store the result. |
int diff = a - b; | Subtract one number from another. |
int prod = a * b; | Multiply two numbers. |
int quot = a / b; | Divide two whole numbers and drop the remainder. |
int rem = a % b; | Get the remainder of a division. |
a++; | Increase a variable by one. |
a += 5; | Add five to a variable in place. |
if (a > b) { } | Run a block only when the test is true. |
if (a > b) { } else { } | Run one block or the other block. |
else if (a == b) { } | Test another condition when the first is false. |
boolean t = a > b && b > 0; | Combine two tests that must both be true. |
String s = (a > b) ? "yes" : "no"; | Choose one of two values with a short test. |
Loops
| Code | What it does |
|---|---|
for (int i = 0; i < 5; i++) { } | Repeat a block a fixed number of times. |
for (int i = 5; i > 0; i--) { } | Count down from five to one. |
while (n > 0) { n--; } | Repeat while a condition stays true. |
do { n--; } while (n > 0); | Run the block once before the first test. |
for (int x : list) { } | Visit each item in a collection. |
break; | Leave the loop immediately. |
continue; | Skip to the next loop step. |
for (int i = 0; i < 3; i++) { } | Loop three times with a counter. |
while (true) { break; } | Loop forever until a break runs. |
for (int i = 0; i < a.length; i++) { } | Loop over an array by index. |
int i = 0; while (i < 5) { i++; } | Loop with a counter declared outside. |
outer: for (int i = 0; i < 2; i++) { } | Give a loop a label for a labeled break. |
Methods
| Code | What it does |
|---|---|
void greet() { } | Define a method that returns nothing. |
int add(int a, int b) { return a + b; } | Define a method that returns a number. |
greet(); | Call a method with no arguments. |
int r = add(2, 3); | Call a method and store its result. |
static int square(int n) { return n * n; } | Define a method that belongs to the class. |
public int getAge() { return age; } | Return a field value from a method. |
void setAge(int a) { age = a; } | Change a field value with a method. |
return; | Exit a void method early. |
int max(int a, int b) { return a > b ? a : b; } | Return the larger of two numbers. |
String join(String a, String b) { return a + b; } | Return two joined text values. |
boolean isEven(int n) { return n % 2 == 0; } | Return true when a number is even. |
void printAll(int... nums) { } | Accept a variable number of arguments. |
Strings
| Code | What it does |
|---|---|
int len = s.length(); | Get the number of characters in a string. |
String u = s.toUpperCase(); | Make a copy with all letters uppercase. |
String l = s.toLowerCase(); | Make a copy with all letters lowercase. |
boolean e = s.isEmpty(); | Check if a string has no characters. |
char c = s.charAt(0); | Get the character at a given index. |
String t = s.trim(); | Remove spaces from both ends. |
boolean b = s.contains("ab"); | Check if a string holds a piece of text. |
String p = s.substring(1, 3); | Copy characters from index one to index two. |
String[] parts = s.split(","); | Split a string into parts by a separator. |
String r = s.replace("a", "b"); | Make a copy with text replaced. |
int i = s.indexOf("ab"); | Find the first position of a piece of text. |
boolean q = s.equals("yes"); | Compare two strings by their content. |
Arrays and Lists
| Code | What it does |
|---|---|
int[] nums = {1, 2, 3}; | Create an array with three numbers. |
int[] a = new int[5]; | Create an array of five zeros. |
int n = nums.length; | Get the size of an array. |
int first = nums[0]; | Read the item at index zero. |
nums[1] = 9; | Change the item at index one. |
List<String> list = new ArrayList<>(); | Create an empty list of strings. |
list.add("a"); | Add an item to the end of a list. |
String x = list.get(0); | Read an item from a list by index. |
list.set(0, "b"); | Replace an item in a list. |
list.remove(0); | Remove an item from a list by index. |
int size = list.size(); | Get the number of items in a list. |
boolean has = list.contains("a"); | Check if a list holds an item. |
Classes and Objects
| Code | What it does |
|---|---|
class Dog { } | Define a new class. |
Dog d = new Dog(); | Create an object from a class. |
class Dog { int age; } | Add a field to a class. |
d.age = 3; | Set a field on an object. |
int a = d.age; | Read a field from an object. |
Dog(String n) { name = n; } | Define a constructor that sets a field. |
new Dog("Rex"); | Create an object and pass an argument. |
private int age; | Hide a field from other classes. |
public int getAge() { return age; } | Expose a field through a getter. |
class Puppy extends Dog { } | Define a class that inherits from another. |
@Override public String toString() { return name; } | Replace the default text form of an object. |
this.name = name; | Use this to tell a field from a parameter. |
Errors and Input
| Code | What it does |
|---|---|
try { } catch (Exception e) { } | Run code and handle any error. |
catch (ArithmeticException e) { } | Handle one specific kind of error. |
finally { } | Run a block after try, with or without an error. |
throw new IllegalArgumentException(); | Stop and report a bad argument. |
e.getMessage(); | Read the text that describes an error. |
import java.util.Scanner; | Import the Scanner class for input. |
Scanner sc = new Scanner(System.in); | Create a scanner that reads the keyboard. |
int n = sc.nextInt(); | Read a whole number from input. |
String s = sc.nextLine(); | Read a full line of text from input. |
sc.close(); | Close the scanner when it is no longer needed. |
Objects.requireNonNull(x); | Throw an error when a value is null. |
assert n > 0 : "bad"; | Check a condition when assertions are on. |