Java Cheatsheet

1. Basic Syntax

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

2. Data Types

Primitive Types:
- byte (8-bit integer)
- short (16-bit integer)
- int (32-bit integer)
- long (64-bit integer)
- float (32-bit floating point)
- double (64-bit floating point)
- char (16-bit Unicode character)
- boolean (true or false)

Reference Types:
- Objects
- Arrays

3. Variables and Operators

int a = 5;
int b = 10;

// Arithmetic Operators
int sum = a + b;
int diff = a - b;
int prod = a * b;
int div = a / b;

// Relational Operators
boolean isEqual = (a == b);
boolean isNotEqual = (a != b);
boolean isGreater = (a > b);

// Logical Operators
boolean result = (a > 5 && b < 10);
boolean resultOr = (a > 5 || b < 10);

4. Control Flow Statements

// If-else
if (a > b) {
  System.out.println("a is greater");
} else {
  System.out.println("b is greater");
}

// Switch
int day = 2;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  default:
    System.out.println("Other day");
}

// For loop
for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

// While loop
while (a < b) {
  a++;
}

// Enhanced for-loop
int[] numbers = {1, 2, 3};
for (int num : numbers) {
  System.out.println(num);
}

5. Object-Oriented Programming (OOP)

class Car {
  private String model;
  private int year;

  public Car(String model, int year) {
    this.model = model;
    this.year = year;
  }

  public void start() {
    System.out.println("Car started");
  }

  public String getModel() {
    return model;
  }
}

Car car = new Car("Toyota", 2020);
car.start();
System.out.println(car.getModel());

6. Inheritance and Polymorphism

class Animal {
  public void makeSound() {
    System.out.println("Animal sound");
  }
}

class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Bark");
  }
}

Animal myDog = new Dog();
myDog.makeSound(); // Outputs: Bark

7. Interfaces and Abstract Classes

// Interface
interface Animal {
  void eat();
}

class Dog implements Animal {
  @Override
  public void eat() {
    System.out.println("Dog eats");
  }
}

Dog dog = new Dog();
dog.eat();

// Abstract class
abstract class Shape {
  abstract void draw();
}

class Circle extends Shape {
  @Override
  void draw() {
    System.out.println("Drawing a circle");
  }
}

8. Generics

public class Box<T> {
  private T value;

  public Box(T value) {
    this.value = value;
  }

  public T getValue() {
    return value;
  }

  public void setValue(T value) {
    this.value = value;
  }
}

Box<Integer> integerBox = new Box<>(123);
System.out.println(integerBox.getValue());

9. Exception Handling

try {
  int result = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Cannot divide by zero");
} finally {
  System.out.println("Cleanup code here");
}

10. Collections Framework

import java.util.*;

// List
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Output: Apple

// Set
Set<String> set = new HashSet<>();
set.add("Orange");
set.add("Orange"); // Duplicate, will not be added
System.out.println(set.size()); // Output: 1

// Map
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map.get("Apple")); // Output: 1

11. Streams API

import java.util.*;
import java.util.stream.*;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Filtering
List<Integer> evenNumbers = numbers.stream()
  .filter(n -> n % 2 == 0)
  .collect(Collectors.toList());

// Mapping
List<Integer> squares = numbers.stream()
  .map(n -> n * n)
  .collect(Collectors.toList());

System.out.println(evenNumbers); // Output: [2, 4]
System.out.println(squares); // Output: [1, 4, 9, 16, 25]

12. Lambda Expressions

List<String> names = Arrays.asList("John", "Jane", "Jack");

// Using a lambda expression to print each name
names.forEach(name -> System.out.println(name));

// Lambda with custom functional interface
@FunctionalInterface
interface Calculator {
  int add(int a, int b);
}

Calculator calc = (a, b) -> a + b;
System.out.println(calc.add(5, 10)); // Output: 15

13. Concurrency (Threads & Executors)

// Creating a thread by extending Thread class
class MyThread extends Thread {
  public void run() {
    System.out.println("Thread running");
  }
}

MyThread thread = new MyThread();
thread.start();

// Using Runnable
class MyRunnable implements Runnable {
  public void run() {
    System.out.println("Runnable running");
  }
}

Thread runnableThread = new Thread(new MyRunnable());
runnableThread.start();

// Using ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task running"));
executor.shutdown();

14. Input/Output (I/O)

import java.io.*;

// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

// Writing to a file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
  writer.write("Hello, World!");
} catch (IOException e) {
  e.printStackTrace();
}

15. Annotations

@Override
public String toString() {
  return "This is an example";
}

// Custom annotation
@interface MyAnnotation {
  String value();
}

@MyAnnotation(value = "Example")
public class ExampleClass {
  // Class code
}

16. JDBC (Java Database Connectivity)

import java.sql.*;

try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password")) {
  Statement stmt = connection.createStatement();
  ResultSet rs = stmt.executeQuery("SELECT * FROM users");
  while (rs.next()) {
    System.out.println(rs.getString("name"));
  }
} catch (SQLException e) {
  e.printStackTrace();
}

17. Design Patterns

// Singleton Pattern
class Singleton {
  private static Singleton instance;
  private Singleton() {}
  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

Singleton singleton = Singleton.getInstance();

// Factory Pattern
interface Shape {
  void draw();
}

class Circle implements Shape {
  public void draw() {
    System.out.println("Drawing a Circle");
  }
}

class ShapeFactory {
  public Shape getShape(String shapeType) {
    if (shapeType.equalsIgnoreCase("CIRCLE")) {
      return new Circle();
    }
    return null;
  }
}

ShapeFactory factory = new ShapeFactory();
Shape shape = factory.getShape("CIRCLE");
shape.draw();