Skip to content

Java Notes

Mattscreative edited this page Mar 9, 2026 · 4 revisions

Java Study Notes

Exam Preparation Guide

This guide covers all essential Java topics in a format perfect for studying and exam preparation. Each section includes explanations, examples, and common patterns.


Table of Contents

  1. Variables and Data Types
  2. Operators
  3. Control Flow
  4. Methods
  5. Arrays
  6. Object-Oriented Programming
  7. Inheritance and Polymorphism
  8. Interfaces and Abstract Classes
  9. Exception Handling
  10. Collections Framework
  11. Generics
  12. Lambda Expressions and Streams
  13. Common Methods Quick Reference
  14. Syntax Rules Summary
  15. Common Errors and Fixes

1. Variables and Data Types

What Are Variables?

Variables are containers for storing data values. Think of them as labeled boxes where you can put information. Each box has a type that tells Java what kind of data it holds.

Primitive Data Types

Java has 8 primitive types that represent the most basic data:

Integer Types (Whole Numbers)

Type Size Typical Use
byte 8 bits Small numbers, memory-efficient
short 16 bits Small integers
int 32 bits Most common for whole numbers
long 64 bits Very large numbers

Example: int age = 25;

Decimal Types (Floating-Point)

Type Size Typical Use
float 32 bits Decimal numbers (less precise)
double 64 bits Most common for decimals

Example: double price = 19.99;

Other Types

Type Size Typical Use
boolean 1 bit True or false values
char 16 bits Single character

Example: boolean isActive = true; Example: char grade = 'A';

Reference Types

Reference types store objects (instances of classes). The most common is String:

String name = "Alice";
String message = "Hello, World!";

Declaring Variables

Basic declaration:

int number;
String text;
boolean flag;

Declaration with initialization:

int count = 10;
String name = "Bob";

Constants (final keyword)

Use final to create a constant - a value that cannot be changed:

final int MAX_SIZE = 100;
final double PI = 3.14159;

Type Conversion

Implicit (Automatic) Conversion

Java automatically converts smaller types to larger types:

int num = 100;
long bigNum = num;    // int converts to long automatically
double decimal = bigNum; // long converts to double

Explicit (Manual) Conversion

Use casting when converting larger to smaller:

double decimal = 9.99;
int whole = (int) decimal;  // Result: 9 (decimal part lost)

String Conversions

Converting to String:

int num = 42;
String str = String.valueOf(num);      // "42"
String str2 = Integer.toString(num);   // "42"
String str3 = num + "";                // "42" (quick trick)

Converting from String:

String str = "123";
int num = Integer.parseInt(str);       // 123
double d = Double.parseDouble("3.14"); // 3.14

Variable Naming Rules

  • Must start with a letter, underscore, or dollar sign
  • Can contain letters, numbers, underscores, dollar signs
  • Case sensitive (age and Age are different)
  • Cannot use Java keywords

Naming Conventions (Best Practices)

  • Variables: camelCase (firstName, userAge)
  • Constants: UPPER_SNAKE_CASE (MAX_SIZE, PI)
  • Classes: PascalCase (Person, BankAccount)
  • Methods: camelCase with verb (calculateTotal, printMessage)

2. Operators

Arithmetic Operators

These perform mathematical calculations:

Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 3 1 (integer)
% Modulus (remainder) 5 % 3 2

Important Notes:

  • Integer division truncates decimals: 5 / 2 = 2, not 2.5
  • Use double for decimal division: 5.0 / 2 = 2.5
int result = 10 + 5;      // 15
result = result - 3;      // 12
result = result * 2;      // 24
result = result / 4;      // 6
result = result % 4;      // 2

Increment and Decrement

int x = 5;
x++;      // x is now 6 (post-increment)
++x;      // x is now 7 (pre-increment)
x--;      // x is now 6 (post-decrement)
--x;      // x is now 5 (pre-decrement)

Difference between post and pre:

int a = 5;
int b = a++;  // b = 5, a = 6 (assigns then increments)

int c = 5;
int d = ++c;  // d = 6, c = 6 (increments then assigns)

Compound Assignment Operators

Shorthand for combining operations:

int num = 10;
num += 5;    // num = num + 5  -> 15
num -= 3;    // num = num - 3  -> 12
num *= 2;    // num = num * 2  -> 24
num /= 4;    // num = num / 4  -> 6
num %= 5;    // num = num % 5  -> 1

Comparison Operators

These return boolean (true or false):

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater or equal 5 >= 5 true
<= Less or equal 5 <= 3 false

Logical Operators

Combine boolean values:

Operator Meaning True When
&& AND Both are true
|| OR At least one is true
! NOT Value is false
boolean a = true;
boolean b = false;

a && b   // false (both must be true)
a || b   // true (at least one is true)
!a       // false (inverts the value)

Ternary Operator

A compact if-else in one line:

// syntax: condition ? valueIfTrue : valueIfFalse

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
// Result: "Adult"

Operator Precedence

Order of operations (PEMDAS):

  1. Parentheses ()
  2. Unary ! ++ --
  3. Multiplicative * / %
  4. Additive + -
  5. Comparison < > <= >=
  6. Equality == !=
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment = += -= etc

3. Control Flow

If-Else Statements

Execute code based on conditions:

if (condition) {
    // runs if condition is true
}

if (condition) {
    // runs if true
} else {
    // runs if false
}

if (grade >= 90) {
    System.out.println("A");
} else if (grade >= 80) {
    System.out.println("B");
} else if (grade >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}

Switch Statement

Choose between multiple options:

int day = 3;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Unknown";
        break;
}

Switch Expression (Java 14+):

String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Unknown";
};

Grouping Cases:

switch (grade) {
    case 'A':
    case 'B':
    case 'C':
        System.out.println("Pass");
        break;
    case 'D':
    case 'F':
        System.out.println("Fail");
        break;
}

For Loop

Repeat code a specific number of times:

// Basic structure
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
// Output: 0, 1, 2, 3, 4

Parts:

  • int i = 0 - Starting point
  • i < 5 - Condition (run while true)
  • i++ - Increment after each iteration

Countdown:

for (int i = 10; i > 0; i--) {
    System.out.println(i);
}

Step by 2:

for (int i = 0; i <= 20; i += 2) {
    System.out.println(i);  // 0, 2, 4, 6... 20
}

Enhanced For-Loop (For-Each)

Loop through arrays or collections without index:

String[] names = {"Alice", "Bob", "Charlie"};

for (String name : names) {
    System.out.println(name);
}

While Loop

Repeat while condition is true:

int count = 1;

while (count <= 5) {
    System.out.println(count);
    count++;
}

Do-While Loop

Runs at least once (checks condition after):

int num = 10;

do {
    System.out.println(num);
    num--;
} while (num > 0);

Break and Continue

  • break - Exit the loop immediately
  • continue - Skip to next iteration
// Break example - find first even number
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        System.out.println("Found: " + i);
        break;  // Exit loop
    }
}

// Continue example - skip odd numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 != 0) {
        continue;  // Skip to next iteration
    }
    System.out.println(i);  // Only prints even: 2, 4, 6, 8, 10
}

4. Methods

What Are Methods?

Methods are blocks of code that perform specific tasks. They let you reuse code without repeating it.

Method Structure

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

Parts:

  • public - Access modifier
  • static - Can call without creating object
  • int - Return type
  • add - Method name
  • (int a, int b) - Parameters
  • return a + b - Return value

Types of Methods

No return (void):

public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}
// Call: greet("Alice");

With return:

public static int square(int num) {
    return num * num;
}
// Call: int result = square(5);  // result = 25

No parameters:

public static String getMessage() {
    return "Welcome!";
}

Multiple parameters:

public static int calculate(int a, int b, String operation) {
    if (operation.equals("add")) {
        return a + b;
    } else if (operation.equals("subtract")) {
        return a - b;
    }
    return 0;
}

Method Overloading

Same method name, different parameters:

// Different parameter types
public static int add(int a, int b) {
    return a + b;
}

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

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

// Usage:
add(5, 3);        // Calls first version
add(5.5, 3.2);    // Calls second version
add(1, 2, 3);     // Calls third version

Static vs Instance Methods

  • Static - Call using class name, no object needed
  • Instance - Must create object first
class Calculator {
    static int add(int a, int b) {
        return a + b;
    }
    
    int subtract(int a, int b) {
        return a - b;
    }
}

// Static call:
int sum = Calculator.add(5, 3);

// Instance call:
Calculator calc = new Calculator();
int diff = calc.subtract(5, 3);

5. Arrays

What Are Arrays?

Arrays store multiple values of the same type in a single variable.

Creating Arrays

// Method 1: Specify size
int[] numbers = new int[5];  // Array of 5 integers

// Method 2: Initialize with values
int[] numbers = {1, 2, 3, 4, 5};

// Method 3: String array
String[] names = {"Alice", "Bob", "Charlie"};

Accessing Elements

Array indices start at 0:

int[] scores = {95, 87, 92, 78, 88};

scores[0]   // First element: 95
scores[1]   // Second element: 87
scores[4]   // Fifth element: 88

Modifying Elements

int[] numbers = {1, 2, 3, 4, 5};
numbers[0] = 10;        // Change first element
System.out.println(numbers[0]);  // 10

Array Length

int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr.length);  // 5

Looping Through Arrays

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

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

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

Common Array Operations

Find maximum:

int[] numbers = {5, 12, 3, 8, 99, 1};
int max = numbers[0];

for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}
System.out.println("Max: " + max);  // 99

Calculate sum:

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

for (int num : numbers) {
    sum += num;
}
System.out.println("Sum: " + sum);  // 15

Search for value:

String[] names = {"Alice", "Bob", "Charlie", "Diana"};
String searchName = "Charlie";
boolean found = false;

for (String name : names) {
    if (name.equals(searchName)) {
        found = true;
        break;
    }
}
System.out.println("Found: " + found);  // true

Two-Dimensional Arrays

Array of arrays (like a table):

int[][] grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

grid[0][0]   // First row, first column: 1
grid[1][2]   // Second row, third column: 6

Loop through 2D array:

for (int row = 0; row < grid.length; row++) {
    for (int col = 0; col < grid[row].length; col++) {
        System.out.print(grid[row][col] + " ");
    }
    System.out.println();
}

6. Object-Oriented Programming

What is OOP?

Object-Oriented Programming organizes code around objects - things that have properties (data) and behaviors (methods). Think of real-world objects: a Car has color, speed (properties) and can drive, brake (methods).

The Four Pillars

  1. Encapsulation - Protecting data by controlling access
  2. Inheritance - Child classes inherit from parents
  3. Polymorphism - Same action, different behavior
  4. Abstraction - Hiding complex details

Creating a Class

public class Person {
    // Properties (also called fields)
    private String name;
    private int age;
    
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Method
    public void introduce() {
        System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
    }
    
    // Getter
    public String getName() {
        return name;
    }
    
    // Setter
    public void setName(String name) {
        this.name = name;
    }
}

Creating Objects

Person person = new Person("Alice", 25);
person.introduce();  // "Hi, I'm Alice and I'm 25 years old."

String name = person.getName();  // "Alice"
person.setName("Bob");

Access Modifiers

Control who can access what:

Modifier Same Class Same Package Subclass Everywhere
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

Why Use Encapsulation?

Protects data from invalid values:

public class BankAccount {
    private double balance;  // Private - can't access directly
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;  // Can validate before setting
        }
    }
    
    public double getBalance() {
        return balance;
    }
}

Getters and Setters

Provide controlled access to private fields:

public class Student {
    private String name;
    private int grade;
    
    // Getter
    public String getName() {
        return name;
    }
    
    // Setter
    public void setName(String name) {
        this.name = name;
    }
    
    public int getGrade() {
        return grade;
    }
    
    public void setGrade(int grade) {
        if (grade >= 0 && grade <= 100) {
            this.grade = grade;
        }
    }
}

7. Inheritance and Polymorphism

What is Inheritance?

Inheritance lets a class (child) inherit properties and methods from another class (parent). The child gets everything from the parent automatically.

Basic Inheritance

// Parent class
class Animal {
    String name;
    
    public void eat() {
        System.out.println(name + " is eating");
    }
    
    public void sleep() {
        System.out.println(name + " is sleeping");
    }
}

// Child class
class Dog extends Animal {
    String breed;
    
    // Dog inherits eat() and sleep() automatically
    
    public void bark() {
        System.out.println("Woof woof!");
    }
}

// Using inheritance
Dog dog = new Dog();
dog.name = "Buddy";
dog.eat();    // "Buddy is eating" (inherited)
dog.bark();   // "Woof woof!" (Dog-specific)

The super Keyword

super refers to the parent class:

class Animal {
    String name;
    
    public Animal(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Call parent constructor
        this.breed = breed;
    }
}

Method Overriding

Child class can change parent method behavior:

class Animal {
    public void makeSound() {
        System.out.println("Some sound");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

What is Polymorphism?

Same method call, different behavior based on object type:

Animal animal1 = new Cat();
Animal animal2 = new Dog();

animal1.makeSound();  // "Meow!"
animal2.makeSound();  // "Woof!"

This is useful for storing different objects in one collection:

Animal[] animals = new Animal[3];
animals[0] = new Cat();
animals[1] = new Dog();
animals[2] = new Bird();

for (Animal animal : animals) {
    animal.makeSound();  // Each makes its own sound
}

The @Override Annotation

Marks a method as overriding a parent method. The compiler checks if the method actually exists in the parent:

class Parent {
    public void display() { }
}

class Child extends Parent {
    @Override
    public void display() { }  // Compiler verifies this exists in Parent
}

8. Interfaces and Abstract Classes

What is an Interface?

An interface is a contract that defines what methods a class must have, but doesn't provide the implementation.

Interface Example

interface Drawable {
    void draw();  // Abstract method - no body
    
    default void print() {  // Default method (Java 8+)
        System.out.println("Printing...");
    }
}

class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Square implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a square");
    }
}

What is an Abstract Class?

An abstract class is a class that cannot be instantiated. It can have both abstract methods (no body) and regular methods:

abstract class Animal {
    String name;
    
    // Regular method
    public void eat() {
        System.out.println(name + " is eating");
    }
    
    // Abstract method - must be implemented by subclasses
    public abstract void makeSound();
}

class Dog extends Animal {
    public Dog(String name) {
        this.name = name;
    }
    
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

Interface vs Abstract Class

Feature Interface Abstract Class
Inheritance Multiple allowed Single only
Constructor No Yes
Methods All abstract (pre-Java 8) Can have regular methods
Variables Constants only Can have instance variables
Access modifiers Public by default Any

When to Use Each

Use interfaces when:

  • Unrelated classes need to share behavior
  • You want multiple inheritance
  • You just need method signatures

Use abstract classes when:

  • Classes share a common ancestor
  • You want to provide some default behavior
  • You need instance variables

9. Exception Handling

What Are Exceptions?

Exceptions are errors that occur during program execution. Handling them prevents your program from crashing.

Try-Catch Block

try {
    // Code that might cause an error
    int result = 10 / 0;  // This will throw an exception
} catch (ArithmeticException e) {
    // Code to handle the error
    System.out.println("Cannot divide by zero!");
    System.out.println("Error: " + e.getMessage());
}

Multiple Catch Blocks

Handle different types of exceptions:

try {
    String str = null;
    System.out.println(str.length());  // NullPointerException
    
    int[] arr = new int[5];
    System.out.println(arr[10]);       // ArrayIndexOutOfBoundsException
    
    int num = Integer.parseInt("abc"); // NumberFormatException
} catch (NullPointerException e) {
    System.out.println("Null reference!");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index error!");
} catch (Exception e) {
    System.out.println("Something went wrong: " + e.getMessage());
}

The Finally Block

Code that always executes, whether or not an exception occurs:

try {
    System.out.println("Trying...");
} catch (Exception e) {
    System.out.println("Error!");
} finally {
    System.out.println("This always runs!");
}

Common use: closing resources like files or database connections.

Throwing Exceptions

Create and throw your own exceptions:

public static void divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Cannot divide by zero!");
    }
    System.out.println(a / b);
}

Common Java Exceptions

Exception Cause
NullPointerException Using null object
ArrayIndexOutOfBoundsException Invalid array index
ArithmeticException Math error (division by zero)
ClassCastException Invalid casting
NumberFormatException Invalid number string
IOException Input/Output error

10. Collections Framework

What Are Collections?

Collections are data structures that store groups of objects. They provide better functionality than arrays.

List Interface

Ordered collection that allows duplicates:

import java.util.*;

// ArrayList - most common
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice");  // Duplicate allowed

System.out.println(names.get(0));    // Get by index
System.out.println(names.size());    // Number of elements
names.remove("Alice");               // Remove by value
names.remove(0);                     // Remove by index

Set Interface

Collection that does not allow duplicates:

Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1);  // Won't be added (duplicate)

System.out.println(numbers.size());  // 2

TreeSet - Sorted order:

Set<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// Output in alphabetical order: Alice, Bob, Charlie

Map Interface

Stores key-value pairs:

Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);

System.out.println(ages.get("Alice"));  // 25
System.out.println(ages.containsKey("Bob"));  // true
ages.remove("Bob");

Iterating Collections

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// For-each loop
for (String name : names) {
    System.out.println(name);
}

// Using iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

Common Collection Methods

list.add(item)           // Add element
list.remove(item)        // Remove element
list.size()              // Get size
list.contains(item)      // Check if contains
list.isEmpty()           // Check if empty
list.clear()            // Remove all

map.put(key, value)     // Add/update
map.get(key)            // Get by key
map.containsKey(key)    // Check key
map.remove(key)         // Remove

11. Generics

What Are Generics?

Generics allow you to create classes, methods, and interfaces that work with any data type while maintaining type safety.

Generic Class

class Box<T> {
    private T content;
    
    public void set(T content) {
        this.content = content;
    }
    
    public T get() {
        return content;
    }
}

// Usage
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String str = stringBox.get();  // No casting needed

Box<Integer> intBox = new Box<>();
intBox.set(42);
int num = intBox.get();  // Already an Integer

Generic Method

public static <T> void printArray(T[] array) {
    for (T element : array) {
        System.out.println(element);
    }
}

// Usage
String[] names = {"Alice", "Bob"};
Integer[] numbers = {1, 2, 3};

printArray(names);    // Works with Strings
printArray(numbers);  // Works with Integers

Bounded Type Parameters

Restrict the types that can be used:

// Only allow Number types (Integer, Double, etc.)
public static <T extends Number> double sum(T a, T b) {
    return a.doubleValue() + b.doubleValue();
}

// Comparable interface
public static <T extends Comparable<T>> T maximum(T a, T b) {
    return (a.compareTo(b) > 0) ? a : b;
}

12. Lambda Expressions and Streams

What Are Lambda Expressions?

Lambdas are concise way to represent functions. They let you pass behavior as parameters.

Lambda Syntax

// Full form
(parameter) -> { statements }

// Short form for single parameter
parameter -> expression

// No parameters
() -> expression

Examples

// Runnable (no params, no return)
Runnable r = () -> System.out.println("Hello");

// Consumer (one param, no return)
Consumer<String> printer = s -> System.out.println(s);

// Function (one param, returns value)
Function<String, Integer> length = s -> s.length();

// Predicate (one param, returns boolean)
Predicate<Integer> isEven = n -> n % 2 == 0;

Common Functional Interfaces

Interface Method Use
Predicate<T> test(T) Returns boolean
Function<T,R> apply(T) Transforms T to R
Consumer<T> accept(T) Consumes T
Supplier<T> get() Provides T
UnaryOperator<T> apply(T) T to T

Streams

Streams process collections in a functional style:

import java.util.stream.*;

// Create stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = numbers.stream();

// Filter - keep matching elements
List<Integer> evens = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
// Result: [2, 4]

// Map - transform each element
List<Integer> doubled = numbers.stream()
    .map(n -> n * 2)
    .collect(Collectors.toList());
// Result: [2, 4, 6, 8, 10]

// Reduce - combine to single value
int sum = numbers.stream()
    .reduce(0, (a, b) -> a + b);
// Result: 15

// Count
long count = numbers.stream().count();

// Find first
Optional<Integer> first = numbers.stream().findFirst();

Method References

Shorthand for simple lambdas:

// These are equivalent:
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);

list.stream().map(s -> s.toUpperCase());
list.stream().map(String::toUpperCase);

13. Common Methods Quick Reference

String Methods

String str = "Hello, World!";

str.length()              // 13
str.charAt(0)            // 'H'
str.substring(0, 5)      // "Hello"
str.indexOf("o")         // 4
str.replace("o", "x")    // "Hellx, Wxrld!"
str.toUpperCase()        // "HELLO, WORLD!"
str.toLowerCase()        // "hello, world!"
str.trim()               // Removes whitespace
str.split(",")          // ["Hello", " World!"]
str.equals("hello")     // false (case-sensitive)
str.equalsIgnoreCase("hello")  // true
str.contains("World")   // true
str.startsWith("Hello") // true
str.endsWith("!")       // true
str.isEmpty()           // false

Math Methods

Math.abs(-5)           // 5 (absolute value)
Math.max(3, 7)        // 7
Math.min(3, 7)        // 3
Math.sqrt(16)         // 4.0
Math.pow(2, 3)        // 8.0
Math.floor(3.7)       // 3.0
Math.ceil(3.2)        // 4.0
Math.round(3.7)       // 4
Math.random()         // 0.0 to 1.0
Math.PI               // 3.14159...
Math.E                // 2.71828...

Array Methods (Arrays class)

int[] arr = {3, 1, 4, 1, 5, 9};

Arrays.sort(arr)                    // Sort in place
Arrays.toString(arr)                // "[1, 3, 4, 5, 9]"
Arrays.fill(arr, 0)                 // Fill with 0
Arrays.copyOf(arr, 10)              // Copy with new length
Arrays.equals(arr1, arr2)           // Compare arrays
Arrays.binarySearch(arr, 5)         // Search (must be sorted)
Arrays.stream(arr)                  // Convert to stream

14. Syntax Rules Summary

Class Structure Order

  1. Package declaration
  2. Import statements
  3. Class declaration
  4. Static variables
  5. Instance variables
  6. Constructors
  7. Methods

Naming Conventions

Type Convention Example
Class PascalCase MyClass, BankAccount
Variable camelCase firstName, userAge
Constant UPPER_SNAKE MAX_SIZE, PI
Method camelCase calculateTotal()
Package lowercase com.example.myapp

Reserved Keywords (Cannot Use as Names)

abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while

Important Syntax Rules

  • Every statement ends with semicolon
  • Curly braces define code blocks
  • Arrays use square brackets
  • Class names start with capital letter
  • File name must match public class name
  • Java is case-sensitive

15. Common Errors and Fixes

NullPointerException

Problem: Using a null reference

String str = null;
str.length();  // NullPointerException!

// Fix: Check for null
if (str != null) {
    str.length();
}

ArrayIndexOutOfBoundsException

Problem: Accessing invalid index

int[] arr = {1, 2, 3};
arr[3];  // Index 3 doesn't exist!

// Fix: Always check bounds
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

ClassCastException

Problem: Invalid type casting

Object obj = "Hello";
Integer num = (Integer) obj;  // ClassCastException!

// Fix: Use instanceof first
if (obj instanceof Integer) {
    Integer num = (Integer) obj;
}

Comparing Strings

Problem: Using == instead of equals()

String a = new String("hello");
String b = new String("hello");
a == b     // false (different objects)
a.equals(b)  // true (same content)

// Fix: Always use .equals() for strings
if (a.equals(b)) { }

Integer Division

Problem: Getting unexpected decimal result

int a = 5;
int b = 2;
System.out.println(a / b);  // 2, not 2.5!

// Fix: Use double
System.out.println((double) a / b);  // 2.5

Missing break in Switch

Problem: Fall-through behavior

int num = 1;
switch (num) {
    case 1:
        System.out.println("One");
    case 2:
        System.out.println("Two");
    default:
        System.out.println("Other");
}
// Output: One, Two, Other (no breaks!)

// Fix: Add break statements
switch (num) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
    default:
        System.out.println("Other");
}

Quick Study Checklist

  • Primitive types and their sizes
  • Variable declaration and initialization
  • Type conversion (implicit and explicit)
  • All operators and precedence
  • If-else and switch statements
  • For loops and while loops
  • Method structure and overloading
  • Array creation and manipulation
  • Class structure and access modifiers
  • Encapsulation with getters/setters
  • Inheritance with extends
  • Method overriding
  • Polymorphism
  • Interface vs abstract class
  • Try-catch exception handling
  • List, Set, Map implementations
  • Generic classes and methods
  • Lambda expressions
  • Stream operations

Exam Tips

  1. Practice writing code by hand
  2. Know the difference between similar concepts (interface vs abstract class)
  3. Remember that arrays are 0-indexed
  4. Know which methods modify collections vs which return new ones
  5. Understand the difference between == and equals()
  6. Remember operator precedence
  7. Practice tracing through loops
  8. Know common exception types and when they occur

Good luck with your studies!

Clone this wiki locally