Java Cheat Sheet
1. Basic Syntax
- Class Declaration:
class ClassName {
public static void main(String[] args) {
// Code goes here
}
}Printing Output:
System.out.println("Hello, World!");2. Data Types
Primitive Types:
int(4 bytes) – whole numbersfloat(4 bytes) – single precision floating pointdouble(8 bytes) – double precision floating pointchar(2 bytes) – characterboolean(1 bit) – true or falsebyte(1 byte) – small numbersshort(2 bytes) – numberslong(8 bytes) – large numbers
- Non-Primitive Types:
- Arrays, Classes, Interfaces, Strings
3. Operators
- Arithmetic:
+,-,*,/,% - Relational:
==,!=,<,>,<=,>= - Logical:
&&,||,! - Assignment:
=,+=,-=,*=,/= - Unary:
++,--
4. Control Structures
- if-else:
if (condition) {
// if block
} else {
// else block
}- switch:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}- for loop:
for (int i = 0; i < n; i++) {
// code
}- while loop:
while (condition) {
// code
}- do-while loop:
do {
// code
} while (condition);5. Arrays
- Declaration & Initialization:
int[] arr = new int[5]; // declaration
int[] arr = {1, 2, 3, 4, 5}; // initialization- Accessing Elements:
System.out.println(arr[0]); // first element6. Object-Oriented Programming (OOP)
Classes and Objects:
class Animal {
String name;
void makeSound() {
System.out.println("Animal sound");
}
}
Animal dog = new Animal(); // object creation- Constructors:
class Animal {
Animal(String name) {
this.name = name;
}
}- Inheritance:
class Dog extends Animal {
// additional methods and properties
}- Polymorphism:
Animal myDog = new Dog(); // parent class reference for child object- Encapsulation:
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}- Abstraction:
abstract class Animal {
abstract void makeSound();
}- Interfaces:
interface Animal {
void eat();
}7. Exception Handling
- try-catch block:
try {
// code that might throw exception
} catch (Exception e) {
System.out.println(e);
} finally {
// code that always runs
}- throw keyword:
throw new Exception("Error Message");8. Collections Framework
- List (ArrayList):
ArrayList<String> list = new ArrayList<>();
list.add("Apple");- Set (HashSet):
HashSet<String> set = new HashSet<>();
set.add("Banana");- Map (HashMap):
HashMap<String, Integer> map = new HashMap<>();
map.put("Key", 100);9. String Handling
- String Declaration:
String str = "Hello";- String Methods:
str.length()str.toUpperCase()str.substring(1, 4)str.equals("Hello")
10. File Handling
- Reading a File:
try {
File file = new File("filename.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}- Writing to a File:
try {
FileWriter writer = new FileWriter("filename.txt");
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}11. Multithreading
- Extending Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
MyThread t1 = new MyThread();
t1.start();- Implementing Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}
Thread t1 = new Thread(new MyRunnable());
t1.start();12. Lambda Expressions (Java 8+)
- Syntax:
(parameters) -> expression
- Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(n -> System.out.println(n));13. Streams (Java 8+)
- Basic Stream Operations:
List<String> names = Arrays.asList("John", "Jane", "Tom");
names.stream()
.filter(name -> name.startsWith("J"))
.forEach(System.out::println);14. Java 8 Features
- Optional:
Optional<String> optional = Optional.ofNullable("Hello");
optional.ifPresent(System.out::println);15. Java 11 Features
- var keyword:
var list = new ArrayList<String>();
list.add("Hello");16. Enums
- Enum Declaration:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}- Using Enums:
Day day = Day.MONDAY;
switch(day) {
case MONDAY:
System.out.println("It's Monday!");
break;
}17. Generics
- Generic Class:
class Box<T> {
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
Box<Integer> intBox = new Box<>();
intBox.set(10);- Generic Method:
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}18. Annotations
- Built-in Annotations:
@Override– used to override a method in the subclass.@Deprecated– marks a method as deprecated.@SuppressWarnings– suppresses specific compiler warnings.
- Custom Annotation:
@interface MyAnnotation {
String value();
}
@MyAnnotation(value = "Test")
public void myMethod() {
// Code
}19. Serialization
- Serializable Interface:
import java.io.Serializable;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
}- Writing Object to File:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.ser"));
out.writeObject(new Employee("John", 123));
out.close();- Reading Object from File:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.ser"));
Employee e = (Employee) in.readObject();
in.close();20. Inner Classes
- Static Nested Class:
class Outer {
static class Nested {
void display() {
System.out.println("Inside static nested class");
}
}
}
Outer.Nested obj = new Outer.Nested();
obj.display();- Non-static Inner Class:
class Outer {
class Inner {
void display() {
System.out.println("Inside inner class");
}
}
}
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();21. Reflection
- Basic Reflection Example:
Class<?> objClass = obj.getClass();Method[] methods = objClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}- Invoking Method via Reflection:
Method method = objClass.getDeclaredMethod("methodName", null);
method.invoke(obj, null);22. Java Memory Management
- Garbage Collection:
Java automatically handles memory management and reclaims memory via the Garbage Collector (GC). You can request GC with
System.gc(), though it doesn't guarantee immediate action. - Heap and Stack Memory:
- Heap: Stores objects and their associated data.
- Stack: Stores method calls and local variables.
23. Java Concurrency (Advanced)
- Synchronization:
synchronized (this) { // synchronized block
}
or
public synchronized void syncMethod() {
// synchronized method
}- ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Task is running");
});
executor.shutdown();- Future Interface:
Future<Integer> future = executor.submit(() -> {
return 5;
});
System.out.println(future.get());24. Java Modules (Java 9+)
- Module Declaration:
module com.myapp {
exports com.myapp.api;
}- Requires and Exports:
module com.myapp {
requires java.sql;
exports com.myapp.util;
}25. JavaFX (GUI Development)
- Basic JavaFX Application:
import javafx.application.Application; import javafx.stage.Stage; public class MyApp extends Application { @Override public void start(Stage primaryStage) { primaryStage.setTitle("Hello JavaFX"); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
26. Functional Interfaces (Java 8+)
- Functional Interface Example:
@FunctionalInterface interface MyFunction { void apply(); } MyFunction function = () -> System.out.println("Lambda executed"); function.apply();
27. Default Methods in Interfaces (Java 8+)
- Interface with Default Method:
interface MyInterface { default void display() { System.out.println("Default Method"); } } class MyClass implements MyInterface { // Can override or use the default method }
28. Streams API (Advanced)
- Collecting Streams:
List<String> names = Arrays.asList("John", "Jane", "Tom");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());- Stream Map and Reduce:
int sum = Arrays.asList(1, 2, 3, 4, 5)
.stream()
.mapToInt(Integer::intValue)
.reduce(0, (a, b) -> a + b);29. Optional Class (Java 8+)
Creating Optional Object:
Optional<String> optional = Optional.of("Hello");optional.ifPresent(System.out::println);Handling Null Values:
Optional<String> nullableString = Optional.ofNullable(null);String defaultValue = nullableString.orElse("Default");FAQ
1. What is the difference between JDK, JRE, and JVM?
- JDK (Java Development Kit): A full-featured software development kit that includes the JRE and tools like the compiler (javac) to develop Java applications.
- JRE (Java Runtime Environment): Provides the libraries, Java Virtual Machine (JVM), and other components to run Java applications.
- JVM (Java Virtual Machine): It is the engine that executes Java bytecode and provides platform independence by converting bytecode into machine code for different operating systems.
2. What is the concept of 'Garbage Collection' in Java?
Garbage Collection in Java is the process of automatically reclaiming memory by deleting objects that are no longer reachable or used in the program. Java handles memory management via its built-in garbage collector, which runs in the background and frees up unused memory to avoid memory leaks.
3. What is the difference between ‘==’ and ‘equals()’ in Java?
- ‘==’: This operator checks if two references point to the same memory location (i.e., reference equality).
- ‘equals()’: This method checks whether two objects are logically equivalent (i.e., content equality). For example, two different
Stringobjects containing the same characters are considered equal withequals()but not with==.
4. What is an interface in Java, and how is it different from an abstract class?
An interface in Java is a collection of abstract methods that a class can implement. Unlike abstract classes, interfaces support multiple inheritance (a class can implement multiple interfaces). The key differences are:
- Interfaces cannot have constructors, while abstract classes can.
- Abstract classes can have non-abstract methods, whereas interfaces (until Java 8) can only have abstract methods. However, Java 8+ allows default and static methods in interfaces.
5. What is the purpose of the ‘final’ keyword in Java?
The final keyword in Java is used in three contexts:
- final variable: Makes the variable's value constant and prevents it from being reassigned.
- final method: Prevents a method from being overridden by subclasses.
- final class: Prevents a class from being subclassed or inherited.
