Java Handbook
Table of Contents
- Introduction
- Control Statements
- Data Structures
- Object-Oriented Programming
- Advanced Data Structures
- Advanced OOP Concepts
- Advanced Java Concepts
Introduction
Basic Syntax and Variables
// Variable declaration
int age = 27;
double realAge = 27.1;
String name = "banana";
// Formatted printing
System.out.printf("my name is %s and age is %.2f\n", name, realAge);
// %s - string, %d - int, %f - float/double, %c - char, %b - boolean
Input Handling
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.println("what's your age?");
int age = scanner.nextInt();
// Clear input buffer
scanner.nextLine();
System.out.println("what's your name?");
String name = scanner.nextLine();
scanner.close();
Arithmetic Operations
int x = 10;
int y = 20;
x = x + y; // Addition
x += y; // Compound assignment
x++; // Increment
x--; // Decrement
System.out.println(x * y); // Multiplication
System.out.println(x - y); // Subtraction
System.out.println(y % x); // Modulus
Control Statements
Conditional Statements
// If-else statements
int age = 18;
if (age >= 18) {
System.out.println("you can watch conjuring");
} else if (age > 16) {
System.out.println("you can watch iron man");
} else {
System.out.println("you can watch frozen");
}
// Ternary operator
int score = 90;
char grade = (score >= 90) ? 'A' : 'B';
// Switch statement
switch(score) {
case 90 -> System.out.println("90, wah");
case 80 -> System.out.println("80 ugh");
case 900 -> {
System.out.println("are you out of your mind");
}
default -> System.out.println("average, damn.");
}
Loops
// While loop
int score = 5;
while(score > 1) {
System.out.println(score--);
}
// For loop
for(int i = 0; i < 10; i += 2) {
System.out.println(i);
}
// Enhanced for loop (arrays/collections)
String[] fruits = {"apple", "banana", "orange"};
for(String fruit : fruits) {
System.out.println(fruit);
}
// Loop control
break; // Exit loop
continue; // Skip current iteration
Logical Operators
// Used in conditional statements
&& // AND
|| // OR
! // NOT
Data Structures
Arrays
// Array declaration and initialization
String[] bananas = new String[3];
String[] fruits = {"apple", "banana", "mango"};
// Array operations
bananas[0] = "keli";
Arrays.sort(bananas); // Sort array
int length = bananas.length; // Get length
// Iterating through arrays
for (String banana : bananas) {
System.out.println(banana);
}
// 2D Arrays
int[][] matrix = new int[3][3];
int[][] grid = {{1,2,3}, {4,5,6}, {7,8,9}};
Strings and StringBuilder
String name = "banana";
// String methods
name.isEmpty(); // Check if empty
name.length(); // Get length
name.charAt(0); // Character at index
name.indexOf("a"); // First occurrence
name.lastIndexOf("a"); // Last occurrence
name.toUpperCase(); // Convert to uppercase
name.toLowerCase(); // Convert to lowercase
name.trim(); // Remove whitespace
name.replace("a", "o"); // Replace characters
name.contains("a"); // Check containment
name.equals("banana"); // Check equality
name.substring(0, 2); // Get substring
// StringBuilder for mutable strings
StringBuilder sb = new StringBuilder();
sb.append("hi");
sb.insert(1, "X");
sb.deleteCharAt(0);
sb.setCharAt(0, 'Y');
sb.reverse();
String result = sb.toString();
Object-Oriented Programming
Classes and Objects
// Class definition
public class Car {
// Attributes (fields)
private String name;
private int year;
// Constructor
public Car(String name, int year) {
this.name = name;
this.year = year;
}
// Methods
public void drive() {
System.out.println("Driving " + name);
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
// Object creation
Car myCar = new Car("Toyota", 2020);
myCar.drive();
Methods
// Method definition
public void sayApple() {
System.out.println("Apple.");
}
// Method with parameters and return value
public int add(int a, int b) {
return a + b;
}
// Method overloading
public void sayApple() {}
public void sayApple(String message) {}
Static Members
public class MathUtils {
// Static variable
public static int objectCount = 0;
// Static method
public static int max(int a, int b) {
return a > b ? a : b;
}
}
// Access static members without object
int maximum = MathUtils.max(5, 10);
Advanced Data Structures
Collections Framework
ArrayList
import java.util.ArrayList;
import java.util.Collections;
ArrayList<String> fruits = new ArrayList<>();
// Basic operations
fruits.add("banana");
fruits.add("apple");
fruits.add(1, "orange"); // Insert at index
fruits.get(0); // Get element
fruits.set(0, "mango"); // Update element
fruits.remove(1); // Remove by index
fruits.remove("apple"); // Remove by value
fruits.contains("banana"); // Check existence
fruits.size(); // Get size
// Sorting
Collections.sort(fruits);
// Iteration
for(String fruit : fruits) {
System.out.println(fruit);
}
HashMap
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
// Basic operations
map.put("abc", 2);
map.put("cda", 3);
map.get("abc"); // Get value
map.containsKey("abc"); // Check key
map.containsValue(2); // Check value
map.remove("abc"); // Remove entry
// Iteration
for(String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
for(Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
HashSet
import java.util.HashSet;
import java.util.Set;
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.remove(1);
boolean exists = set.contains(2);
int size = set.size();
for(int num : set) {
System.out.println(num);
}
Stack and Queue
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Deque;
import java.util.ArrayDeque;
// Stack
Stack<Integer> stack = new Stack<>();
stack.push(10);
int top = stack.peek();
int popped = stack.pop();
// Queue
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.add(2);
int first = queue.peek();
int removed = queue.poll();
// Deque (Double Ended Queue)
Deque<Integer> deque = new ArrayDeque<>();
deque.offerFirst(1);
deque.offerLast(2);
int front = deque.pollFirst();
int last = deque.pollLast();
PriorityQueue (Heap)
import java.util.PriorityQueue;
// Min-heap (default)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.add(5);
minHeap.offer(2);
int min = minHeap.poll();
// Max-heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
// Custom comparator
PriorityQueue<int[]> customHeap = new PriorityQueue<>(
(a, b) -> a[0] - b[0] // Compare first element
);
Advanced OOP Concepts
Inheritance
// Parent class
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println("Animal sound");
}
}
// Child class
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}
@Override
public void speak() {
System.out.println("Woof!");
}
}
Polymorphism
// Using parent class reference for child objects
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Whiskers");
Animal[] animals = {myDog, myCat};
for(Animal animal : animals) {
animal.speak(); // Calls respective overridden methods
}
Abstraction
// Abstract class
public abstract class Shape {
protected String color;
// Abstract method (must be implemented by subclasses)
public abstract double area();
// Concrete method
public String getColor() {
return color;
}
}
// Concrete subclass
public class Circle extends Shape {
private double radius;
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Interfaces
// Interface definition
public interface Prey {
void flee();
}
public interface Predator {
void hunt();
}
// Class implementing multiple interfaces
public class Fish implements Prey, Predator {
@Override
public void flee() {
System.out.println("Fish flees");
}
@Override
public void hunt() {
System.out.println("Fish hunts");
}
}
Encapsulation
public class BankAccount {
private double balance;
private String accountNumber;
// Public getters and setters
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
Advanced Java Concepts
Exception Handling
import java.util.InputMismatchException;
try {
// Code that might throw exceptions
System.out.println(1/0);
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero: " + e.getMessage());
} catch (InputMismatchException e) {
System.out.println("Invalid input: " + e.toString());
} catch (Exception e) {
System.out.println("Something went wrong: " + e.getMessage());
} finally {
// Always executes
System.out.println("Cleanup code here");
}
// Try-with-resources (auto-closing)
try (Scanner scanner = new Scanner(System.in)) {
// Use scanner
} catch (Exception e) {
// Handle exception
}
Generics
// Generic class
public class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
// Multiple type parameters
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
// Usage
Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
Box<Integer> intBox = new Box<>();
intBox.setItem(42);
Enums
public enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4),
THURSDAY(5), FRIDAY(6), SATURDAY(7);
private int dayNumber;
Day(int dayNumber) {
this.dayNumber = dayNumber;
}
public int getDayNumber() {
return dayNumber;
}
}
// Usage
Day today = Day.MONDAY;
System.out.println(today.getDayNumber()); // Output: 2
// Switch with enums
switch(today) {
case MONDAY -> System.out.println("Start of work week");
case FRIDAY -> System.out.println("Almost weekend!");
default -> System.out.println("Regular day");
}
Wrapper Classes
// Autoboxing (Java 5+)
Integer a = 21; // Autoboxing
int x = a; // Unboxing
// Useful methods
String numStr = "123";
int num = Integer.parseInt(numStr); // String to int
String str = Integer.toString(123); // int to String
// Character methods
Character.isLetter('a'); // true
Character.isUpperCase('A'); // true
Character.isDigit('5'); // true
Anonymous Classes
// Regular class
Dog dog = new Dog();
// Anonymous class with custom behavior
Dog specialDog = new Dog() {
@Override
void speak() {
System.out.println("Special bark!");
}
};
Math Utilities
Math.PI; // 3.141592653589793
Math.pow(2, 4); // 16.0
Math.abs(-10); // 10
Math.ceil(4.3); // 5.0
Math.floor(4.7); // 4.0
Math.max(5, 10); // 10
Math.min(5, 10); // 5
Math.sqrt(16); // 4.0
Math.random(); // Random double between 0.0 and 1.0
Random Number Generation
import java.util.Random;
Random random = new Random();
int randomInt = random.nextInt(10); // 0-9
double randomDouble = random.nextDouble(); // 0.0-1.0
boolean randomBool = random.nextBoolean(); // true/false
Common Algorithms and Patterns
Binary Search
int[] sortedArray = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(sortedArray, 5); // Returns 2
Sorting
int[] numbers = {3, 1, 4, 1, 5, 9};
Arrays.sort(numbers); // Sorts in-place
// Custom sorting with comparator
Arrays.sort(numbers, (a, b) -> b - a); // Descending order
DFS and BFS Patterns
// Binary Tree Node
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
// DFS (Recursive)
void dfs(TreeNode root) {
if (root == null) return;
// Pre-order processing
dfs(root.left);
// In-order processing
dfs(root.right);
// Post-order processing
}
// BFS (Iterative with Queue)
void bfs(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
// Process current node
if (current.left != null) queue.offer(current.left);
if (current.right != null) queue.offer(current.right);
}
}
Dynamic Programming Example
// Fibonacci with DP
public int fibonacci(int n) {
if (n <= 1) return n;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}