Java Cheatsheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

System.out.println("Hi!

");

main() method signature

Java
CHEAT SHEET

nextBoolean()

byte a = 13;
Basic Syntax

Class Declaration System output

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 an object of Scanner class: myObj


Method Declaration Scanner new operator
class
Create a method with name: demoMethod
Access Return type Method Signature Scanner myObj = new Scanner(System.in);
Specifier (Method Name & Parameter List)
Standard InputStream
public int demoMethod (int a, int b)
Object name
{
// Method body
}
Use one of these methods to take input:

nextBoolean() - Reads a boolean value from the user


nextByte()
main() method signature - Reads a byte value from the user

nextDouble() - Reads a double value from the user

Create a method with name: demoMethod nextFloat() - Reads a float value from the user

nextInt() - Reads an int value from the user


Belongs to
the class nextLine() - Reads a String value from the user
Accessible Return type Method name
Everywhere nextLong() - Reads a long value from the user

nextShort() - Reads a short value from the user


public static void main (String[] args)
{
String username = myObj.nextLine();
// Method body
Array of String
} as argument
// Take the whole line as string input

01 Java Cheatsheet
Primitive Data Types

Type Size Range Default Values

byte 8 bits -128 to 127 0


short 16 bits -32,768 to 32,767 0
int 32 bits -2^31 to 2^31 - 1 0
long 64 bits -2^63 to 2^63 - 1 0L
float 32 bits 1.4E-45 to 3.4028235E38 0.0f
double 64 bits 4.9E-324 to 1.797693E308 0.0d
char 16 bits '\u0000' to '\uffff' '\u0000'
boolean 1 bit true or false false

Byte:
Program Stack Memory
byte a = 13;

Memory
0 0 0 0 1 1 0 1
Allocation
a
(name to the
memory location)

Non-Primitive Data Types

Non-Primitive Data Type

Arrays String Class Interface

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

Final Variables Final Classes


(Once initialized, can't be changed) Final Methods (Restricts Inheritance)
(No Method Overriding)

Blank Final Variable


(Initialized in Constructor only)

Static Blank Final Variable


(Can be initialized in a static block)

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

System.out.println(5 / 3); // Division, Output: 1.6666666666666667

System.out.println(5 % 3); //Modulo, Output: 2

Assignment Operators

int x = 45; // Assignment operator

x /= 3; // Equivalent to x = x / 3;

x += 3; // Equivalent to x = x + 3;

x -= 10; // Equivalent to x = x - 10;


x %= 3; // Equivalent to x = x % 3;
System.out.println(x); // Output: 2

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

System.out.println(5 != 3); // Not equal, Output: true

System.out.println(5 > 3); // Greater than, Output: true

System.out.println(5 < 3); // Less than, Output: false

System.out.println(5 >= 3); // Greater than or equal to, Output: true

System.out.println(5 <= 3); // Less than or equal to, Output: false

04 Java Cheatsheet
Logical Operators (and/or/not)

System.out.println(true && false); // Logical AND, Output: false

System.out.println(true || false); // Logical OR, Output: true

System.out.println(!true); // Logical NOT, Output: false

X and Y X or Y

True True False False


X = True Y = True True X = True Y = True False

False False True True

False False True True

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

System.out.println(~5); // Bitwise NOT, Output: -6


System.out.println(5 >> 1); // Bitwise Right Shift, Output: 2
System.out.println(5 << 1); // Bitwise Left Shift, Output: 10

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 or if-else statements nested if statements


int age = 22; int age = 22;

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]

printf("Error! operator is not correct");


}

07 Java Cheatsheet
for statement

Signature:

for (initialization; test; update) {


STATEMENT(s);
}

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};

int[] arr = new int[]{1, 4, 21, 13, 55};

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.

class Child extends Parent {


int x = 4;
}

public class Hello {

public static void main(String args[]) {


Child ch = new Child();

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 {

// Private instance variable


private String name;

// Constructor
public Person(String name) {
this.name = name;
}

// Public getter for name


public String getName() {
return name;
}
Any access/modification to the "name" attribute
must happen through these two methods. No other way!!
// Public setter for name
public void setName(String name) {
this.name = name;
}

public static void main(String[] args) {


Person person = new Person("Alice");
System.out.println(person.getName()); // Alice

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();

public static void makeSound(Animal animal) {


System.out.println(animal.sound()); PolymorphimSound changes based on type of Animal passed.
}
}

class Cat implements Animal {


@Override make_sound
public String sound() {
return "meow"; catObj dogObj
}
}
meow woof

class Dog implements Animal {


@Override
public String sound() {The print() is not defined in the Child class.
return "woof"; It is defined in the Parent class.

}
}

public class Main {

public static void main(String[] args) {


Animal catObj = new Cat();
Animal dogObj = new Dog();

Animal.makeSound(catObj); // Output: meow


Animal.makeSound(dogObj); // Output: woof
}
}

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 {

public static void main(String[] args) {


int num = 10;
int divisor = 0;
int result = num / divisor; java.lang.ArithmeticException: / by zero
}
} * Detected at run time. Cannot detect at Compile time.

Try...Catch
Code
int num = 10;
int divisor = 0;

try {

java.lang.ArithmeticException occurs int result = num / divisor;

and control moves to catch block. System.out.println("Result: " + result);


}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}

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

Run the code under try block.

If an exception occurs

If no exception occurs catch

If the code under try throws an exception,


execute the code under except block.

finally

Always execute this block.

17 Java Cheatsheet
String, StringBuffer and StringBuilder

Immutable Mutable
-cannot be changed -can be changed

String s=new String StringBuffer s=new


(”Hello”); s+= “Hi”; StringBuffer(“Hello”);

s.append(“Hi”);

s “HelloHi”

s “Hello” s “HelloHi”

String Memory StringBuffer/ Memory


StringBuilder

Index String String Buffer String Builder

Storage Area Constant String Pool Heap Heap

Modifiable No(Immutable) Yes(mutable) Yes(mutable)

Thread Safe Yes Yes No

Thread Safe Fast Very slow Fast

For more details, visit: https://www.scaler.com/topics/string-class-in-java/


https://www.scaler.com/topics/java/stringbuffer-in-java/
https://www.scaler.com/topics/java/stringbuilder-in-java/

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.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> evenNumbers = numbers.stream()


.filter(n -> n % 2 == 0) Lambda expression
.collect(Collectors.toList());

.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 & Blocks

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.

public synchronized void synchronizedMethod() {


// method body
}

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.

public void someMethod() {


// non-critical section

synchronized(lockObject) {
// critical section
}

// other non-critical section


}

Synchronized Method/Block

Locked by thread1 Other threads waiting for lock

t1 t2 t3 t4 t5

JVM, JRE and JDK

Java JVM CPU


Java Program Java Bytecode Machine Code Output
Compiler

JVM

Runtime Libraries:
rt.jar, javac
javaws.jar, javap
jce.xar, javadoc
JVM + java.exe JVM + javaw, etc.
(Compilers and
Debuggers)

Other runtime files

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;

After this, original "obj1" object becomes unreachable.

Heap Memory Heap Memory

obj1 obj1 Becomes unreachable

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();
}

Reading from a file


Code
try {
File file = new File("example.txt"); File Content
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) { Output
System.out.println(line); Hello, world!
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}

22 Java Cheatsheet

You might also like