Java Cheatsheet

Deepak Ranolia
6 min readDec 4, 2023

--

Basic Level

In the basic level of this Java cheatsheet, fundamental concepts such as printing, variables, data types, conditional statements, loops, and functions are covered. This level provides a solid foundation for anyone new to Java programming.

1. Hello World

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

2. Variables and Data Types

public class VariablesExample {
public static void main(String[] args) {

// Declare variables
int age = 25;
double salary = 50000.5;
char grade = 'A';
boolean isStudent = true;

// Print variables
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Is Student: " + isStudent);
}
}

3. Conditional Statements

public class ConditionalExample {
public static void main(String[] args) {
int number = 10;

// If statement
if (number > 0) {
System.out.println("Number is positive");
} else if (number < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
}
}

4. Loops

public class LoopExample {
public static void main(String[] args) {

// For loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}

// While loop
int count = 0;
while (count < 3) {
System.out.println("While Loop: " + count);
count++;
}
}
}

5. Functions

public class FunctionExample {
public static void main(String[] args) {
// Call a function
greet("John");
}

// Function definition
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

This basic Java cheatsheet covers fundamental concepts like printing, variables, data types, conditional statements, loops, and functions.

Intermediate Level

Moving on to the intermediate level, concepts like arrays, object-oriented programming (OOP), exception handling, file I/O, and collections (List, Map) are introduced. This level expands on the basics and delves into more advanced programming structures.

1. Arrays

public class ArrayExample {
public static void main(String[] args) {

// Declare and initialize an array
int[] numbers = {1, 2, 3, 4, 5};

// Access and modify array elements
System.out.println("First Element: " + numbers[0]);
numbers[1] = 10;

// Loop through array elements
for (int num : numbers) {
System.out.println("Number: " + num);
}
}
}

2. Object-Oriented Programming (OOP)

// Class definition
class Car {
// Fields
String model;
int year;

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

// Method
public void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}

public class OOPExample {
public static void main(String[] args) {

// Create an object of the Car class
Car myCar = new Car("Toyota", 2022);

// Call a method on the object
myCar.displayInfo();
}
}

3. Exception Handling

public class ExceptionExample {
public static void main(String[] args) {
try {

// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {

// Handle the exception
System.out.println("Error: " + e.getMessage());
}
}

// Function that throws an exception
static int divide(int a, int b) {
return a / b;
}
}

4. File I/O

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileIOExample {
public static void main(String[] args) {
// Read from a file
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}

5. Collections (List, Map)

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionsExample {
public static void main(String[] args) {

// List example
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

// Map example
Map<String, Integer> ages = new HashMap<>();
ages.put("John", 25);
ages.put("Alice", 30);

// Access elements in the collections
System.out.println("Fruit: " + fruits.get(0));
System.out.println("Age of John: " + ages.get("John"));
}
}

This intermediate Java cheatsheet introduces concepts like arrays, object-oriented programming (OOP), exception handling, file I/O, and collections (List, Map).

Advanced Level

At the advanced level, the cheatsheet explores threads and concurrency, generics, lambda expressions, the Stream API, and annotations. These concepts empower developers to write more efficient and expressive code.

1. Threads and Concurrency

class PrintNumbers extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " - " + i);
}
}
}

public class ConcurrencyExample {
public static void main(String[] args) {

// Create two threads and start them
PrintNumbers thread1 = new PrintNumbers();
PrintNumbers thread2 = new PrintNumbers();
thread1.start();
thread2.start();
}
}

2. Generics

// Generic class
class Box<T> {
private T content;

public void setContent(T content) {
this.content = content;
}

public T getContent() {
return content;
}
}

public class GenericsExample {
public static void main(String[] args) {

// Create a generic box for Integer and String
Box<Integer> integerBox = new Box<>();
integerBox.setContent(42);
System.out.println("Integer Value: " + integerBox.getContent());
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello, Generics!");
System.out.println("String Value: " + stringBox.getContent());
}
}

3. Lambda Expressions

// Functional interface
interface Calculator {
int calculate(int a, int b);
}

public class LambdaExample {
public static void main(String[] args) {

// Using lambda expression for addition
Calculator add = (a, b) -> a + b;
System.out.println("Addition: " + add.calculate(10, 5));

// Using lambda expression for multiplication
Calculator multiply = (a, b) -> a * b;
System.out.println("Multiplication: " + multiply.calculate(3, 4));
}
}

4. Stream API

import java.util.Arrays;
import java.util.List;

public class StreamExample {
public static void main(String[] args) {

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

// Using Stream API to filter and print even numbers
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}

5. Annotations

import java.lang.annotation.*;

// Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value() default "Default Value";
}

public class AnnotationExample {
@MyAnnotation("Custom Value")
public void myMethod() {
// Method implementation
}

public static void main(String[] args) {
// Accessing annotation value
MyAnnotation annotation = AnnotationExample.class.getDeclaredMethod("myMethod")
.getAnnotation(MyAnnotation.class);
System.out.println("Annotation Value: " + annotation.value());
}
}

This advanced Java cheatsheet introduces concepts like threads and concurrency, generics, lambda expressions, the Stream API, and annotations.

Expert Level

In the expert level, the cheatsheet covers advanced topics like reflection for dynamic class loading, design patterns (Singleton), serialization and deserialization, JDBC for database connectivity, and JavaFX for building graphical user interfaces. This level is designed for experienced developers seeking mastery in Java programming.

1. Reflection

import java.lang.reflect.Method;

public class ReflectionExample {
public static void main(String[] args) {
try {

// Using reflection to invoke a method dynamically
Class<?> clazz = Class.forName("MyClass");
Object obj = clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getDeclaredMethod("myMethod");
method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}

class MyClass {
public void myMethod() {
System.out.println("Dynamic Method Invocation");
}
}

2. Design Patterns (Singleton)

public class Singleton {
private static Singleton instance;

private Singleton() {
// Private constructor to prevent instantiation
}

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

3. Serialization and Deserialization

import java.io.*;

public class SerializationExample {
public static void main(String[] args) {

// Serialize an object
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("data.ser"))) {
MyClass obj = new MyClass();
outputStream.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}

// Deserialize an object
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("data.ser"))) {
MyClass obj = (MyClass) inputStream.readObject();
obj.myMethod();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

class MyClass implements Serializable {
public void myMethod() {
System.out.println("Serialization and Deserialization");
}
}

4. JDBC (Java Database Connectivity)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcExample {
public static void main(String[] args) {

// JDBC connection to a database
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password")) {
String query = "SELECT * FROM users";
try (PreparedStatement statement = connection.prepareStatement(query);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.println("User ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

5. JavaFX (Graphical User Interface)

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXExample extends Application {

public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX Example");
Button btn = new Button("Click Me");
btn.setOnAction(e -> System.out.println("Button Clicked!"));
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}

}

This expert-level Java cheatsheet covers topics like reflection, design patterns (Singleton), serialization and deserialization, JDBC for database connectivity, and JavaFX for building graphical user interfaces.

--

--

Deepak Ranolia
Deepak Ranolia

Written by Deepak Ranolia

Strong technical skills, such as Coding, Software Engineering, Product Management & Finance. Talk about finance, technology & life https://rb.gy/9tod91

No responses yet