Java Cheatsheet
10xdev.blog/cheatsheets
# 1. Basics
// Every Java application has a class with a main method
public class Basics {
    public static void main(String[] args) {
        // Variable declaration
        String message = "Hello, Java!";
        System.out.println(message);

        // Primitive Types
        int anInt = 42;
        double aDouble = 3.14;
        boolean isJavaStrong = true;
        char aChar = 'J';

        // Operators
        int result = anInt + 10; // 52
        System.out.println("Result: " + result);
    }
}
# 2. Data Structures (Collections)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DataStructures {
    public static void main(String[] args) {
        // List (ordered, allows duplicates)
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        System.out.println("First name: " + names.get(0));

        // Map (key-value pairs)
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 30);
        ages.put("Bob", 35);
        System.out.println("Alice's age: " + ages.get("Alice"));

        // Set (unordered, unique elements)
        Set<String> uniqueNames = new HashSet<>();
        uniqueNames.add("Alice");
        uniqueNames.add("Alice"); // This will be ignored
        System.out.println("Unique names: " + uniqueNames);
    }
}
# 3. Control Flow
public class ControlFlow {
    public static void main(String[] args) {
        int score = 85;
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else {
            System.out.println("C or lower");
        }

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

        // Enhanced for loop (for-each)
        List<String> fruits = List.of("Apple", "Banana");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
# 4. Object-Oriented Programming
// Interface
interface Animal {
    void speak();
}

// Class implementing an interface
class Dog implements Animal {
    private String name;

    // Constructor
    public Dog(String name) {
        this.name = name; // `this` refers to the current object
    }

    // Getter
    public String getName() {
        return name;
    }

    @Override // Annotation for overriding a method
    public void speak() {
        System.out.println("Woof!");
    }
}

// Inheritance
class GoldenRetriever extends Dog {
    public GoldenRetriever(String name) {
        super(name); // Call parent constructor
    }

    // Overriding the parent method
    @Override
    public void speak() {
        System.out.println(getName() + " says: Gentle Woof!");
    }
}
# 5. Error Handling
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ErrorHandling {
    public static void main(String[] args) {
        try {
            File myFile = new File("nonexistent.txt");
            Scanner scanner = new Scanner(myFile);
        } catch (FileNotFoundException e) {
            // This is a checked exception, must be caught or declared
            System.err.println("Error: File not found.");
            // e.printStackTrace();
        } finally {
            System.out.println("This block always executes.");
        }
    }

    // A method can also declare that it throws an exception
    public void myMethod() throws CustomException {
        throw new CustomException("Something went wrong!");
    }
}

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
# 6. Streams API (Java 8+)
import java.util.List;
import java.util.stream.Collectors;

public class Streams {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie", "Anna");

        // Filter names that start with 'A' and collect to a new list
        List<String> aNames = names.stream()
            .filter(name -> name.startsWith("A"))
            .map(String::toUpperCase)
            .collect(Collectors.toList());

        System.out.println(aNames); // [ALICE, ANNA]
    }
}
# 7. Build Tools (Maven)
<!-- pom.xml is the configuration file for Maven -->
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- Example dependency: JUnit 5 for testing -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

<!--
Common Maven Commands:
- mvn compile: Compile the source code
- mvn test: Run tests
- mvn package: Package the compiled code into a JAR or WAR
- mvn clean: Remove target directory
-->
master* 0 0