logo
eng-flag

Java Cheatsheet

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Flow
  6. Methods
  7. Arrays
  8. Object-Oriented Programming
  9. Exception Handling
  10. Collections
  11. File Handling
  12. Generics
  13. Multithreading

Basic Syntax

Comments

// This is a single-line comment

/*
This is a
multi-line comment
*/

/**
 * This is a Javadoc comment
 * Used for documentation
 */

Main Method

Every Java program starts from the main method:

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

Data Types

Primitive Data Types

byte b = 100;
short s = 10000;
int i = 100000;
long l = 1000000000L;
float f = 3.14f;
double d = 3.14159265359;
boolean bool = true;
char c = 'A';

Reference Data Types

String str = "Hello, World!";
Integer intObj = 100;
Double doubleObj = 3.14;

Variables

// Variable declaration
int number;

// Variable initialization
number = 10;

// Declaration and initialization
String name = "John";

// Constants
final double PI = 3.14159;

Operators

Arithmetic Operators

int a = 10, b = 3;

System.out.println(a + b);  // Addition: 13
System.out.println(a - b);  // Subtraction: 7
System.out.println(a * b);  // Multiplication: 30
System.out.println(a / b);  // Division: 3
System.out.println(a % b);  // Modulus: 1

Comparison Operators

int x = 5, y = 10;

System.out.println(x == y);  // Equal to: false
System.out.println(x != y);  // Not equal to: true
System.out.println(x > y);   // Greater than: false
System.out.println(x < y);   // Less than: true
System.out.println(x >= y);  // Greater than or equal to: false
System.out.println(x <= y);  // Less than or equal to: true

Logical Operators

boolean a = true, b = false;

System.out.println(a && b);  // Logical AND: false
System.out.println(a || b);  // Logical OR: true
System.out.println(!a);      // Logical NOT: false

Control Flow

If-Else Statement

int x = 10;

if (x > 0) {
    System.out.println("Positive");
} else if (x < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Switch Statement

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

For Loop

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

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

While Loop

int count = 0;
while (count < 5) {
    System.out.println(count);
    count++;
}

Do-While Loop

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);

Methods

// Method definition
public static int add(int a, int b) {
    return a + b;
}

// Method overloading
public static double add(double a, double b) {
    return a + b;
}

// Method call
int sum = add(5, 3);
double sumDouble = add(5.5, 3.3);

Arrays

// Array declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};

// Accessing array elements
System.out.println(numbers[0]);  // Prints 1

// Multi-dimensional array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Array length
System.out.println(numbers.length);  // Prints 5

Object-Oriented Programming

Class Definition

public class Car {
    // Fields
    private String brand;
    private String model;
    
    // Constructor
    public Car(String brand, String model) {
        this.brand = brand;
        this.model = model;
    }
    
    // Methods
    public void start() {
        System.out.println("The car is starting...");
    }
    
    // Getters and Setters
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

Object Creation and Usage

Car myCar = new Car("Toyota", "Corolla");
myCar.start();
System.out.println(myCar.getBrand());

Inheritance

public class ElectricCar extends Car {
    private int batteryCapacity;
    
    public ElectricCar(String brand, String model, int batteryCapacity) {
        super(brand, model);
        this.batteryCapacity = batteryCapacity;
    }
    
    @Override
    public void start() {
        System.out.println("The electric car is starting silently...");
    }
}

Interface

public interface Drivable {
    void drive();
    void stop();
}

public class Car implements Drivable {
    @Override
    public void drive() {
        System.out.println("The car is driving");
    }
    
    @Override
    public void stop() {
        System.out.println("The car has stopped");
    }
}

Exception Handling

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This always executes");
}

// Throwing an exception
public void checkAge(int age) throws IllegalArgumentException {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
}

Collections

ArrayList

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

System.out.println(list.get(0));  // Prints "Apple"
list.remove(1);
System.out.println(list.size());  // Prints 2

HashMap

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

System.out.println(map.get("Banana"));  // Prints 2
map.remove("Apple");
System.out.println(map.containsKey("Apple"));  // Prints false

File Handling

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

Generics

// Generic class
public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

// Usage
Box<Integer> integerBox = new Box<>();
integerBox.set(10);
Integer someInteger = integerBox.get();

// Generic method
public static <E> void printArray(E[] array) {
    for (E element : array) {
        System.out.print(element + " ");
    }
    System.out.println();
}

Multithreading

// Extending Thread class
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

// Implementing Runnable interface
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }
}

// Usage
MyThread thread1 = new MyThread();
thread1.start();

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

// Lambda expression with Runnable
new Thread(() -> {
    System.out.println("Thread is running");
}).start();

2024 © All rights reserved - buraxta.com