Java Cheat Sheet & Quick Reference
Java Cheat Sheet & Quick Reference
This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
# Getting Started
Hello.java
$ javac Hello.java
$ java Hello
Hello, world!
Variables
int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "quickref.me";
Strings
See: Loops
Arrays
See: Arrays
Swap
int a = 1;
int b = 2;
System.out.println(a + " " + b); // 1 2
int temp = a;
a = b;
b = temp;
Type Casting
// Widening
// byte<short<int<long<float<double
int i = 10;
long l = i; // 10
// Narrowing
double d = 10.02;
long l = (long)d; // 10
String.valueOf(10); // "10"
Integer.parseInt("10"); // 10
Double.parseDouble("10"); // 10.0
Conditionals
int j = 10;
if (j == 10) {
System.out.println("I get printed");
} else if (j > 10) {
System.out.println("I don't");
} else {
System.out.println("I also don't");
}
See: Conditionals
User Input
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);
# Java Strings
Basic
Concatenation
StringBuilder
sb.append("QuickRef");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7 8 9
sb.delete(5, 9);
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7 8 9
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7 8 9
sb.append("!");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
Comparison
s1 == s2 // false
s1.equals(s2) // true
"AB".equalsIgnoreCase("ab") // true
Manipulation
str.toUpperCase(); // ABCD
str.toLowerCase(); // abcd
str.concat("#"); // Abcd#
str.replace("b", "-"); // A-cd
Information
str.charAt(2); // c
str.indexOf("a") // 0
str.indexOf("z") // -1
str.length(); // 4
str.toString(); // abcd
str.substring(2); // cd
str.substring(2,3); // c
str.contains("c"); // true
str.endsWith("d"); // true
str.startsWith("a"); // true
str.isEmpty(); // false
Immutable
// Outputs: hello
System.out.println(str);
// Outputs: helloworld
System.out.println(concat);
# Java Arrays
Declare
int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = new int[]{1, 2, 3};
Modify
a[0] = 9;
System.out.println(a[0]); // 9
System.out.println(a.length); // 3
Loop (Read)
String[] arr = {"a", "b", "c"};
for (int a: arr) {
System.out.print(a + " ");
}
// Outputs: a b c
Multidimensional Arrays
int x = matrix[1][0]; // 4
// [[1, 2, 3], [4, 5]]
Arrays.deepToString(matrix)
Sort
// [a, b, c]
Arrays.toString(chars);
# Java Conditionals
Operators
+ - * /
% = ++ --
== != > >=
< <=
&& || ?:
instanceof
& ^ |
If else
int k = 15;
if (k > 20) {
System.out.println(1);
} else if (k > 10) {
System.out.println(2);
} else {
System.out.println(3);
}
Switch
int month = 3;
String str;
switch (month) {
case 1:
str = "January";
break;
case 2:
str = "February";
break;
case 3:
str = "March";
break;
default:
str = "Some other month";
break;
}
Ternary operator
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
// Outputs: 20
System.out.println(max);
# Java Loops
For Loop
While Loop
int count = 0;
Do While Loop
int count = 0;
do {
System.out.print(count);
count++;
} while (count < 5);
// Outputs: 01234
Continue Statement
Break Statement
for (int i = 0; i < 5; i++) {
System.out.print(i);
if (i == 3) {
break;
}
}
// Outputs: 0123
ArrayList List Y N N Y Y
Vector List Y N Y Y Y
CopyOnWriteArrayList List Y N Y Y Y
TreeSet Set Y Y N N N
ConcurrentSkipListSet Set Y Y Y N N
Collection Interface Ordered Sorted Thread safe Duplicate Nullable
ArrayDeque Deque Y N N Y N
PriorityQueue Queue Y N N Y N
ConcurrentLinkedQueue Queue Y N Y Y N
ConcurrentLinkedDeque Deque Y N Y Y N
ArrayBlockingQueue Queue Y N Y Y N
LinkedBlockingDeque Deque Y N Y Y N
PriorityBlockingQueue Queue Y N Y Y N
ArrayList
// Adding
nums.add(2);
nums.add(5);
nums.add(8);
// Retrieving
System.out.println(nums.get(0));
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slow
HashMap
// Retrieving
System.out.println(m.get(6));
// Lambda forEach
m.forEach((key, value) -> {
String msg = key + ": " + value;
System.out.println(msg);
});
HashSet
set.add("dog");
set.add("cat");
set.add("mouse");
set.add("snake");
set.add("bear");
if (set.contains("cat")) {
System.out.println("Contains cat");
}
set.remove("cat");
for (String element : set) {
System.out.println(element);
}
ArrayDeque
// Using add()
a.add("Dog");
// Using addFirst()
a.addFirst("Cat");
// Using addLast()
a.addLast("Horse");
// [Cat, Dog, Horse]
System.out.println(a);
// Access element
System.out.println(a.peek());
// Remove element
System.out.println(a.pop());
# Misc
Access Modifiers
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Regular expressions
// Splitting a String
text.split("\\|");
text split(Pattern quote("|"));
See: Regex in java
Comment
/*
And I am a
multi-line comment!
*/
/**
* This
* is
* documentation
* comment
*/
Keywords
super while
Math methods
Math.sqrt(a) Square-root of a
Math.pow(a,b) Power of b
try {
// something
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
Related Cheatsheet
C# Cheatsheet
Quick Reference