Java Basics Cheat Sheet

Java Programming Basics Cheat Sheet

Download PDF: Java Basics Cheat Sheet.pdf

Basic Structure of a Java Program

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

Variables and Data Types

Variables
int number = 10;           // Integer
double pi = 3.14;          // Double
char letter = 'A';         // Character
String greeting = "Hello"; // String
boolean isTrue = true;     // Boolean
Data Types
byte b = 100;              // 8-bit integer
short s = 10000;           // 16-bit integer
int i = 100000;            // 32-bit integer
long l = 100000L;          // 64-bit integer
float f = 10.5f;           // 32-bit floating point
double d = 10.5;           // 64-bit floating point
char c = 'A';              // Single 16-bit Unicode character
boolean bool = true;       // Boolean (true or false)

Control Flow

If Statements
if (condition) {
    // code block
} else if (anotherCondition) {
    // another code block
} else {
    // another code block
}
Switch Statements
int day = 2;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    // other cases
    default:
        System.out.println("Invalid day");
}
Loops
For Loop
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
While Loop
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}
Do-While Loop
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);

String Operations

String s = "Hello, World!";
System.out.println(s.length());           // Output: 13
System.out.println(s.toUpperCase());      // Output: HELLO, WORLD!
System.out.println(s.toLowerCase());      // Output: hello, world!
System.out.println(s.indexOf("World"));   // Output: 7
System.out.println(s.substring(7, 12));   // Output: World
System.out.println(s.replace("World", "Java")); // Output: Hello, Java!

File Operations

Reading from a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("filename.txt");
            Scanner reader = new Scanner(file);
            while (reader.hasNextLine()) {
                String data = reader.nextLine();
                System.out.println(data);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
Writing to a File
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("filename.txt");
            writer.write("Hello, file!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Comments

Single-Line Comments
// This is a single-line comment
int x = 10;  // This is an inline comment
Multi-Line Comments
/*
This is a multi-line comment
spanning multiple lines.
*/
int y = 20;

Basic Operators

Arithmetic Operators
+   // Addition
-   // Subtraction
*   // Multiplication
/   // Division
%   // Modulus
++  // Increment
--  // Decrement
Comparison Operators
==  // Equal to
!=  // Not equal to
>   // Greater than
<   // Less than
>=  // Greater than or equal to
<=  // Less than or equal to
Logical Operators
&&  // Logical AND
||  // Logical OR
!   // Logical NOT

Arrays

Defining and Using Arrays
int[] numbers = {1, 2, 3, 4, 5};

// Access elements
System.out.println(numbers[0]);  // Output: 1

// Loop through array
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// Enhanced for loop
for (int number : numbers) {
    System.out.println(number);
}

Methods

Defining and Calling Methods
public class Main {
    // Method definition
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Method call
        int sum = add(5, 3);
        System.out.println(sum);  // Output: 8
    }
}
Method Overloading
public class Main {
    // Method overloading
    public static int add(int a, int b) {
        return a + b;
    }

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

    public static void main(String[] args) {
        System.out.println(add(5, 3));      // Output: 8
        System.out.println(add(5.5, 3.3));  // Output: 8.8
    }
}

Data Structures

ArrayList
import java.util.ArrayList;

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

System.out.println(list.size());    // Output: 3
System.out.println(list.get(1));    // Output: Banana

list.remove(1);
System.out.println(list);           // Output: [Apple, Cherry]

for (String fruit : list) {
    System.out.println(fruit);
}
// Output:
// Apple
// Cherry
HashMap
import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);

System.out.println(map.get("Alice"));    // Output: 30
System.out.println(map.size());          // Output: 2

map.remove("Bob");
System.out.println(map);                 // Output: {Alice=30}

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}
// Output:
// Alice: 30
HashSet
import java.util.HashSet;

HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple");  // Duplicate, will not be added

System.out.println(set.size());  // Output: 2

for (String fruit : set) {
    System.out.println(fruit);
}
// Output (order may vary):
// Apple
// Banana

Exception Handling

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("This block always executes");
        }
    }
}

Common Libraries

Importing Libraries
import java.util.ArrayList;  // Import the ArrayList class
import java.util.HashMap;    // Import the HashMap class
import java.util.Scanner;    // Import the Scanner class
import java.io.File;         // Import the File class
import java.io.IOException;  // Import the IOException class