Java Cheat Sheet

Here’s a Java cheat sheet:

Basic Syntax

Hello World:

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

Comments:

// Single-line comment

/*
 * Multi-line comment
 */

/**
 * Javadoc comment
 */

Data Types

Primitive Data Types:

  • int, long, float, double, char, boolean

String:

String myString = "Hello, Java!";

Variables and Constants

Variable Declaration:

int age;

Variable Initialization:

int age = 25;

Constants:

final double PI = 3.14;

Control Flow

If-Else Statement:

if (condition) {
    // code block if true
} else {
    // code block if false
}

Switch Statement:

switch (variable) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // code block if none match
}

Loops

For Loop:

for (int i = 0; i < 5; i++) {
    // code block
}

While Loop:

while (condition) {
    // code block
}

Do-While Loop:

do {
    // code block
} while (condition);

Arrays

Declaration:

int[] numbers;

Initialization:

int[] numbers = {1, 2, 3, 4, 5};

Accessing Elements:

int value = numbers[2];

Methods

Method Declaration:

public void myMethod() {
    // code block
}

Method with Parameters:

public int add(int a, int b) {
    return a + b;
}

Classes and Objects

Class Declaration:

public class MyClass {
    // code block
}

Object Instantiation:

MyClass myObject = new MyClass();

Exception Handling

Try-Catch Block:

try {
    // code block
} catch (ExceptionType e) {
    // handle exception
}

Java Collections

List:

List<String> myList = new ArrayList<>();
myList.add("Item 1");

Map:

Map<String, Integer> myMap = new HashMap<>();
myMap.put("Key", 42);

Here is a dedicated Java Collections Cheat Sheet.

Input/Output

Reading from Console:

Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();

Writing to Console:

System.out.println("Output");

This Java cheat sheet covers syntax, data types, variables and constants, control flow, loops, arrays, methods, classes and objects, exception handling, Java collections, and input/output operations. Adjust as needed based on your specific Java version and requirements.