Java Cheat Sheet

This Java Cheat Sheet is designed to serve as a quick reference guide for Java developers, summarizing key concepts, syntax, and best practices. Whether you're a beginner learning Java or an experienced developer needing a quick reminder, this cheat sheet aims to assist you in your Java programming journey.

A.2 Java Basics

A.2.1 Hello World Program

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

A.2.2 Data Types

Primitive Data Types:

  • byte, short, int, long (integer types)
  • float, double (floating-point types)
  • char (character type)
  • boolean (boolean type)

Reference Data Types:

  • Objects (e.g., String, ArrayList)
  • Arrays

A.2.3 Variables

// Example: Variables
int age = 25;
double salary = 50000.50;
char grade = 'A';
boolean isStudent = true;
String name = "John";
    

A.2.4 Constants

// Example: Constants
final double PI = 3.14;
    

A.2.5 Operators

Arithmetic Operators: +, -, *, /, %

Comparison Operators: ==, !=, <, >, <=, >=

Logical Operators: &&, ||, !

A.3 Control Flow

A.3.1 Conditional Statements

if Statement

// Example: if Statement
if (condition) {
    // code
} else if (anotherCondition) {
    // code
} else {
    // code
}
    

switch Statement

// Example: switch Statement
switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}
    

A.3.2 Looping Statements

for Loop

// Example: for Loop
for (int i = 0; i < 5; i++) {
    // code
}
    

while Loop

// Example: while Loop
while (condition) {
    // code
}
    

do-while Loop


// Example: do-while Loop
do {
    // code
} while (condition);
    

A.4 Methods

A.4.1 Method Declaration


// Example: Method Declaration
public returnType methodName(parameterType parameterName) {
    // code
    return result;
}
    

A.4.2 Calling a Method


// Example: Calling a Method
int result = methodName(argument);
    

A.4.3 Overloading


// Example: Overloading
void printMessage() {
    // code
}

void printMessage(String message) {
    // code
}
    

A.5 Object-Oriented Programming (OOP)

A.5.1 Classes and Objects


// Example: Classes and Objects
public class MyClass {
    // fields (variables)
    private int age;
    
    // constructor
    public MyClass(int initialAge) {
        this.age = initialAge;
    }
    
    // methods
    public void printAge() {
        System.out.println("Age: " + age);
    }
}

// Creating an object
MyClass myObject = new MyClass(30);

// Accessing fields and methods
myObject.printAge();
    

A.5.2 Inheritance


// Example: Inheritance
public class ChildClass extends ParentClass {
    // code
}
    

A.5.3 Polymorphism


// Example: Polymorphism
public interface Shape {
    void draw();
}

public class Circle implements Shape {
    public void draw() {
        // code to draw a circle
    }
}

public class Square implements Shape {
    public void draw() {
        // code to draw a square
    }
}

// Using polymorphism
Shape circle = new Circle();
Shape square = new Square();
    

A.6 Exception Handling

A.6.1 Try-Catch Block


// Example: Try-Catch Block
try {
    // code that may throw an exception
} catch (ExceptionType1 e1) {
    // handle exception type 1
} catch (ExceptionType2 e2) {
    // handle exception type 2
} finally {
    // code to be executed regardless of exceptions
}
    

A.6.2 Throwing Exceptions


// Example: Throwing Exceptions
if (condition) {
    throw new CustomException("This is a custom exception.");
}
    

A.7 Collections

A.7.1 List


// Example: List
List<String> list = new ArrayList<>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");

for (String item : list) {
    System.out.println(item);
}
    

A.7.2 Set


// Example: Set
Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(30);

for (int number : set) {
    System.out.println(number);
}
    

A.7.3 Map


// Example: Map
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
    

A.8 Input/Output (I/O)

A.8.1 Reading from Console


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

A.8.2 File I/O


// Example: File I/O
// Reading from a file
try (BufferedReader reader = new BufferedReader(new FileReader("filename.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Writing to a file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
    writer.write("Hello, World!");
} catch (IOException e) {
    e.printStackTrace();
}
    

A.9 Java 8 Features

A.9.1 Lambda Expressions


// Example: Lambda Expressions
// Syntax: (parameters) -> expression
MathOperation add = (a, b) -> a + b;
System.out.println("Result: " + add.operation(5, 3));
    

A.9.2 Stream API


// Example: Stream API
List<String> programmingLanguages = Arrays.asList("Java", "Python", "JavaScript", "C++", "Ruby");

// Using stream to filter and print languages starting with 'J'
programmingLanguages.stream()
    .filter(language -> language.startsWith("J"))
    .forEach(System.out::println);
    

A.9.3 Optional Class


// Example: Optional Class
Optional<String> language = Optional.of("Java");
System.out.println("Language: " + language.orElse("Unknown"));
    

A.10 Best Practices

A.10.1 Code Organization

  • Use meaningful names for packages, classes, methods, and variables.
  • Follow the Java Naming Conventions.

A.10.2 Code Formatting

  • Use consistent indentation (preferably 4 spaces).
  • Place opening braces on the same line as control statements.

A.10.3 Comments

  • Use JavaDoc comments for documenting classes and methods.
  • Write comments for complex or non-intuitive code.

A.10.4 Exception Handling

  • Catch specific exceptions rather than using a generic Exception catch.
  • Log exceptions using a logging framework.

A.10.5 Testing

  • Write unit tests for each method in your codebase.
  • Integrate automated builds and tests into a continuous integration system.

0 comments:

Post a Comment