Java Cheatsheet
Java Cheatsheet
Java Cheatsheet
");
Java
CHEAT SHEET
nextBoolean()
byte a = 13;
Basic Syntax
Create a class with name: Main Create a method with name: demoMethod
A class declaration begins with the "class" keyword. System Method to print
Class
After the class keyword, put the class name.
class Main
System.out.println("Hi, I am Java!");
{
int x = 5;
Standard OutputStream Message to print
(static member)
void printX() {
Class body
System.out.println(this.x);
}
}
System input
Create a method with name: demoMethod nextFloat() - Reads a float value from the user
01 Java Cheatsheet
Primitive Data Types
Byte:
Program Stack Memory
byte a = 13;
Memory
0 0 0 0 1 1 0 1
Allocation
a
(name to the
memory location)
Java Variables
Memory
int age = 22; Variables in Java are only a name to the
Name to the
memory location where value is stored.
memory location
Data type Variable Name Value age 22
02 Java Cheatsheet
Final Keyword in Java
Final Variable
03 Java Cheatsheet
Operators
Arithmetic Operators
System.out.println(5 + 3); // Addition, Output: 8
System.out.println(5 - 3); // Subtraction, Output: 2
System.out.println(5 * 3); // Multiplication, Output: 15
Assignment Operators
x /= 3; // Equivalent to x = x / 3;
x += 3; // Equivalent to x = x + 3;
x /= 3 x += 3 x -= 10 x %= 3
Memory Container 45 15 18 8 2
Name of the memory location x x x x x
Comparison Operators
System.out.println(5 == 3); // Equal, Output: false
04 Java Cheatsheet
Logical Operators (and/or/not)
X and Y X or Y
Not X
False True
X = True
True False
Bitwise Operators
System.out.println(5 & 3); // Bitwise AND, Output: 1
System.out.println(5 | 3); // Bitwise OR, Output: 7
System.out.println(5 ^ 3); // Bitwise XOR, Output: 6
Pluck it out
5 >> 1 0 0 0 0 0 1 0 1 >> 1
Convert to Binary
0 0 0 0 0 0 1 0
Insert a bit
same as the leftmost bit
05 Java Cheatsheet
Control Structures
if (age < 18) { [Condition False] if (age < 18) { [Condition False]
X
System.out.println("Teenager!"); X if (age < 12) {
} System.out.println("Child");
else { }
System.out.println("Adult!"); else {
} System.out.println("Teenager");
}
}
else {
if or else-if or
if (age < 40) { [Condition True]
if-else statements
System.out.println("Adult");
}
int age = 22;
else {
if (age < 12) { [Condition False]
X System.out.println("Old Age");
System.out.println("Child");
}
}
}
else if (age < 18) { [Condition False]
X
System.out.println("Teenager");
}
else if (age < 40) { [Condition True]
System.out.println("Adult");
}
else { [Ignored]
System.out.println("Old age");
}
System.out.println("End");
06 Java Cheatsheet
switch-case statement
char op = '*';
int n1 = 5, n2 = 7;
switch(op) {
X
case '+': [Not Matched]
printf("n1 + n2 = %d",n1+n2);
break;
X
case '-': [Not Matched]
printf("n1 - n2 = %d",n1-n2);
break;
case '*':
printf("n1 * n2 = %d",n1*n2);
break;
case '/': [Ignored]
printf("n1 / n2 = %d",n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default: [Ignored]
07 Java Cheatsheet
for statement
Signature:
Example: 5 * 1 = 5
Output 5 * 2 = 10
for(int i = 1; i <= 5; i = i + 1) {
5 * 3 = 15
int val = 5 * i;
5 * 4 = 20
System.out.println("5 * " + i + " = " + val);
5 * 5 = 25
}
Initialization
i = 1
Condition Update
i < 5 i = i + 1
True
Statements
False
int val = 5 * i;
System.out.println("5 * " + i + " = " + val);
End for
08 Java Cheatsheet
while statement
Signature:
while(test) {
STATEMENT(s);
}
Example:
int i = 1; 5 * 1 = 5
while (i <= 5) { Output 5 * 2 = 10
int val = 5 * i; 5 * 3 = 15
System.out.println("5 * " + i + " = " + val); 5 * 4 = 20
5 * 5 = 25
i = i + 1;
}
Initialization
i = 1
Condition
i < 5
True
Statements
int val = 5 * i;
System.out.println("5 * " + i + " = " + val);
i = i + 1;
End while
09 Java Cheatsheet
do-while statement
Signature:
do {
STATEMENT(s);
} while(test);
Example:
int i = 5; 5
do{ Output 4
System.out.println(i); 3
i = i - 1; 2
1
} while(i > 0);
Initialization
i = 5
Statements
System.out.println(i);
i = i - 1;
True
Condition
i > 0
False
End while
10 Java Cheatsheet
Break and Continue
int i = 0; int i = 0;
while (i <= 5) { while (i <= 5) {
0 1
if (i == 4) { i = i + 1; Output
Output 1
break; 2
} 2 if (i == 4) { 3
3 continue; 5
System.out.println(i); } 6
i = i + 1; System.out.println(i);
} }
Initialization Initialization
i = 0 i = 0
Condition Condition
i < 5 i < 5
True True
False Remaining i = i + 1;
False i==4 False
Statements
True
Break condition True
i==4
End while
Continue
System.out.println(i);
condition False
End while
11 Java Cheatsheet
Arrays
Declaration:
Method 1:
int[] arr = new int[5];
Method 2:
int[] arr = new int[]{3, 5, 1, 2, 3};
arr[4] = 55
1 4 22 13 55
Indices 0 1 2 3 4
12 Java Cheatsheet
Four Pillars of OOP
Inheritance
1. Inheritance is the process by which an object of one class acquires the properties of another class.
2. Reusable code
3. It resembles real life models.
4. Base class: The class which is inherited is called the base class.
5. Derived class: The class which inherits is called derived class.
Code
class Parent {
public void print() {
System.out.println("This is a function of Parent class.");
}
}
extends keyword is used to establish "Parent-Child" Relationship.
ch.print();
}
} The print() is not defined in the Child class.
It is defined in the Parent class.
Encapsulation
1. Data and the methods which operate on that data are defined inside a single unit.
This concept is called encapsulation.
2. No manipulation or access is allowed directly from outside the capsule or class.
13 Java Cheatsheet
Code
public class Person {
// Constructor
public Person(String name) {
this.name = name;
}
person.setName("Bob");
System.out.println(person.getName()); // Bob
}
}
14 Java Cheatsheet
Polymorphism
1. Polymorphism is the capability of a method, class, or object to take on multiple forms.
2. It primarily manifests through:
a. Inheritance
b. Interfaces
c. Method Overriding & Overloading
Code
interface Animal {
String sound();
}
}
15 Java Cheatsheet
Errors and Exception Handling
Syntax Errors
Code
public class HelloWorld
public static void main(String[] args) { error: '{' expected
System.out.println("Hello, World!"); public class HelloWorld
}
} * Detected at Compile time.
Exceptions
Code
public class DivisionException {
Try...Catch
Code
int num = 10;
int divisor = 0;
try {
16 Java Cheatsheet
The Finally Clause
The code block under finally is always executed.
Code
try {
int result = num / divisor;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
finally {
System.out.println("This block is always executed");
}
"finally" block is always executed!!
try
If an exception occurs
finally
17 Java Cheatsheet
String, StringBuffer and StringBuilder
Immutable Mutable
-cannot be changed -can be changed
s.append(“Hi”);
s “HelloHi”
s “Hello” s “HelloHi”
18 Java Cheatsheet
Java Streams
1. A stream represents a sequence of elements and supports various operations on these elements.
2. Intermediate Operations: Transform a stream into another stream, e.g., filter, map, and sorted. They are always lazily executed.
3. Terminal Operations: When the intermediate operation is complete, the resultant stream is produced using methods like collect,
reduce, toArray, etc.
4. One of the significant advantages of the Stream API is its inherent ability to parallelize operations.
.stream()
numbers 1 2 3 4 5 6 7 8 9 10
(as a List) (as a stream)
filter:
Lambda expression: n -> n % 2 == 0
.collect()
2 4 6 8 10 evenNumbers
As a list
(as a stream) (as a List)
Synchronized Method
* A method that is declared as synchronized ensures that at most one thread
can execute this method at any given time on the same object.
* It's achieved by putting a lock on the object for which the method is called.
19 Java Cheatsheet
Synchronized Block
* Sometimes, synchronizing the entire method might be overkill. In such cases, you can use a synchronized block to only lock that
specific section of the code.
* A synchronized block requires an object. The object's lock will be acquired by the block.
synchronized(lockObject) {
// critical section
}
Synchronized Method/Block
t1 t2 t3 t4 t5
JVM
Runtime Libraries:
rt.jar, javac
javaws.jar, javap
jce.xar, javadoc
JVM + java.exe JVM + javaw, etc.
(Compilers and
Debuggers)
JRE JDK
20 Java Cheatsheet
Garbage Collection
1. Automatic Memory Reclamation: Frees memory from unreferenced objects automatically.
2. Performance Overhead: Can introduce occasional application pauses.
3. Memory Efficiency: Garbage collection ensures that non-reachable allocated memory is freed.
Code
MyClass obj1 = new MyClass("Object 1");
MyClass obj2 = new MyClass("Object 2");
obj1 = obj2;
obj1 = obj2
obj2 obj2
21 Java Cheatsheet
File Handling
Create a file
Code
try { dir
File file = new File("example.txt"); ├── Main.java
file.createNewFile(); ├── Main.class
} catch (IOException e) { ├── example.txt
e.printStackTrace();
}
Writing to a file
Code
try {
FileWriter writer = new FileWriter("example.txt"); "example.txt" file content
writer.write("Hello, World!");
writer.close();
} "Hello, World!"
catch (IOException e) {
e.printStackTrace();
}
22 Java Cheatsheet