Java Cheat Sheet

12 min read Oct 13, 2024
Java Cheat Sheet

Java Cheat Sheet: A Quick Guide to Java Fundamentals

Java is a powerful and versatile programming language that is widely used for developing applications across various platforms. Whether you're a seasoned developer or just starting your journey, a handy cheat sheet can be a valuable resource to keep essential Java concepts at your fingertips. This cheat sheet covers the fundamental aspects of Java, providing a concise overview of syntax, data types, operators, control flow, and more.

1. Data Types

Java uses various data types to represent different kinds of information. Understanding these data types is crucial for working with variables and performing operations. Here's a breakdown of common data types in Java:

  • Primitive Data Types:
    • byte: Stores whole numbers in the range of -128 to 127.
    • short: Stores whole numbers in the range of -32,768 to 32,767.
    • int: Stores whole numbers in a wider range than short.
    • long: Stores very large whole numbers.
    • float: Stores single-precision floating-point numbers (numbers with decimal points).
    • double: Stores double-precision floating-point numbers, providing greater precision than float.
    • char: Stores a single character, enclosed in single quotes.
    • boolean: Stores a truth value, either true or false.
  • Reference Data Types:
    • String: Stores sequences of characters.
    • Arrays: Store collections of elements of the same data type.
    • Classes: Define custom data types with their own properties (fields) and behaviors (methods).
    • Interfaces: Define contracts that classes can implement, specifying methods that they must provide.

Example:

int age = 25; // Declaring an integer variable
double balance = 100.50; // Declaring a double variable
char initial = 'A'; // Declaring a character variable
boolean isLoggedIn = false; // Declaring a boolean variable
String name = "John Doe"; // Declaring a string variable

2. Operators

Operators are symbols that perform specific operations on data. Java supports various operators, including:

  • Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulo).
  • 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).
  • Assignment Operators: = (assignment), += (addition assignment), -= (subtraction assignment), *= (multiplication assignment), /= (division assignment), %= (modulo assignment).
  • Bitwise Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise complement), << (left shift), >> (right shift), >>> (unsigned right shift).

Example:

int sum = 10 + 5; // Addition
boolean isEqual = 10 == 5; // Comparison
boolean isTrue = true && false; // Logical AND
int x = 10;
x += 5; // Addition assignment

3. Control Flow

Control flow statements determine the order in which statements are executed. Here are some common control flow statements in Java:

  • Conditional Statements:

    • if-else: Executes a block of code based on a condition.
    • switch-case: Selects a block of code to execute based on a variable's value.
  • Looping Statements:

    • for: Executes a block of code a specified number of times.
    • while: Executes a block of code repeatedly as long as a condition is true.
    • do-while: Executes a block of code at least once, then repeatedly as long as a condition is true.

Example:

if (age >= 18) {
    System.out.println("You are an adult.");
} else {
    System.out.println("You are a minor.");
}

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

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

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

4. Classes and Objects

Object-oriented programming (OOP) is a fundamental programming paradigm in Java. Classes are blueprints for creating objects, which are instances of classes.

  • Classes: Define the structure and behavior of objects.
  • Objects: Instances of classes, representing real-world entities.
  • Methods: Functions associated with a class, defining its actions.
  • Fields: Variables within a class, representing its data.
  • Constructors: Special methods used to initialize objects.

Example:

class Car {
    String model;
    int year;

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

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

    public void stop() {
        System.out.println("Car stopped.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota Camry", 2022);
        myCar.start();
        myCar.stop();
    }
}

5. Arrays

Arrays are data structures that store collections of elements of the same data type.

  • Declaration: Use square brackets [] to declare an array.
  • Initialization: Assign values to array elements.
  • Access: Use index numbers (starting from 0) to access individual elements.

Example:

int[] numbers = new int[5]; // Declare an array of 5 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

System.out.println(numbers[2]); // Output: 30

6. Collections

Java's Collections Framework provides a set of classes and interfaces for working with collections of objects.

  • List: Ordered collections of elements, allowing duplicates.
  • Set: Unordered collections of elements, not allowing duplicates.
  • Map: Collections of key-value pairs.

Example:

List names = new ArrayList<>();
names.add("John");
names.add("Jane");
names.add("Peter");

Set numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

Map ages = new HashMap<>();
ages.put("John", 25);
ages.put("Jane", 30);
ages.put("Peter", 28);

7. Exceptions

Exceptions are runtime errors that can occur during program execution.

  • Try-Catch: Use try to enclose code that may throw an exception, and catch to handle it.
  • Finally: Use finally to execute code regardless of whether an exception is thrown or caught.

Example:

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

8. Input/Output

Java provides classes for handling input and output operations.

  • Scanner: Reads input from the user.
  • System.out: Prints output to the console.
  • File: Represents files on the system.

Example:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");

9. Threads

Threads allow multiple tasks to execute concurrently within a program.

  • Thread: Represents a single thread of execution.
  • Runnable: Interface that defines the run() method for a thread.

Example:

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

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

10. Generics

Generics allow you to create reusable classes and methods that can work with different data types.

  • Type Parameters: Use angle brackets < > to specify type parameters.

Example:

class MyList {
    private T[] items;

    public MyList(T[] items) {
        this.items = items;
    }

    public T get(int index) {
        return items[index];
    }
}

public class Main {
    public static void main(String[] args) {
        MyList intList = new MyList<>(new Integer[] { 1, 2, 3 });
        System.out.println(intList.get(1)); // Output: 2

        MyList strList = new MyList<>(new String[] { "a", "b", "c" });
        System.out.println(strList.get(0)); // Output: a
    }
}

Conclusion

This Java cheat sheet provides a concise overview of fundamental Java concepts. Mastering these concepts is essential for building robust and efficient Java applications. Keep this cheat sheet handy as a quick reference guide for syntax, data types, operators, control flow, classes, objects, arrays, collections, exceptions, input/output, threads, and generics. Remember, practice is key to becoming proficient in Java. So, dive in and explore the vast possibilities of this powerful language!