Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Java Documentation

Write once, run anywhere — the language of enterprise backends, Android and countless placement interviews.

Java is a statically typed, object-oriented language that runs on the Java Virtual Machine (JVM) — "write once, run anywhere". It powers enterprise backends (Spring Boot), Android apps, big-data tools and is one of the most asked languages in placement interviews.

1. Introduction & Installation

Java source (.java) is compiled by javac into bytecode (.class), which the JVM runs.

  • Install a JDK (not just a JRE) — e.g. Eclipse Temurin 17 or 21 (LTS versions).
  • Set JAVA_HOME and add its bin folder to PATH (the installer can do it).
  • IDEs: IntelliJ IDEA Community, VS Code (Extension Pack for Java), Eclipse.
java -version
javac Main.java     # compile → Main.class
java Main           # run
java Main.java      # Java 11+: compile and run a single file directly
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Codify!");
    }
}

Output:

Hello, Codify!

⚠️ Common error: class Main is public, should be declared in a file named Main.java — the public class name must match the file name exactly (case-sensitive). On Codify, name your class Main.

2. Basic Syntax

  • Everything lives inside a class; execution starts at public static void main(String[] args).
  • Statements end with ;, blocks use { }, and names are case-sensitive.
  • Conventions: ClassName, methodName, variableName, CONSTANT_NAME.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        int age = sc.nextInt();
        System.out.println("Hi " + name + ", next year you'll be " + (age + 1));
        System.out.printf("%s is %d years old%n", name, age);
    }
}

Output (input Asha then 20):

Hi Asha, next year you'll be 21
Asha is 20 years old

💡 Tip: for large inputs, BufferedReader + StringTokenizer is much faster than Scanner.

3. Variables & Data Types

Primitive types hold values directly; everything else is a reference type (objects).

Type Size Example
byte, short 1, 2 bytes byte b = 10;
int 4 bytes int n = 42;
long 8 bytes long big = 9_000_000_000L;
float, double 4, 8 bytes double pi = 3.14;
char 2 bytes (UTF-16) char c = 'A';
boolean — true / false
String object "Codify"
public class Main {
    public static void main(String[] args) {
        int count = 25;
        long population = 1_400_000_000L;
        double price = 99.5;
        char grade = 'B';
        boolean active = true;
        String lang = "Java";
        var list = new java.util.ArrayList<Integer>();   // var: local type inference (Java 10+)
        final int MAX = 100;                             // constant

        System.out.println(count + " " + population + " " + price + " " + grade + " " + active + " " + lang);
        System.out.println(Integer.MAX_VALUE + " " + (Integer.MAX_VALUE + 1));   // overflow wraps
        System.out.println((int) 9.99 + " " + (double) 7 / 2 + " " + Integer.parseInt("123") + " " + list.size() + " " + MAX);
    }
}

Output:

25 1400000000 99.5 B true Java
2147483647 -2147483648
9 3.5 123 0 100

⚠️ Common error: possible lossy conversion from double to int — Java won't narrow automatically. Cast explicitly: int x = (int) d;.

4. Operators

Arithmetic + - * / %, increment ++ --, relational == != < > <= >=, logical && || ! (short-circuit), bitwise & | ^ ~ << >> >>>, assignment = += -= ..., ternary ?: and instanceof.

public class Main {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a / b + " " + a % b + " " + (double) a / b);
        System.out.println((a > 10 && b < 10) + " " + (a == 17 || b == 0));
        System.out.println((a & 1) + " " + (a << 1) + " " + (-16 >> 2) + " " + (-16 >>> 28));
        String s1 = new String("hi"), s2 = "hi";
        System.out.println((s1 == s2) + " " + s1.equals(s2));
    }
}

Output:

3 2 3.4
true true
1 34 -4 15
false true

⚠️ Common error: comparing strings with == checks if they are the same object. Always use .equals() to compare text.

5. Conditional Statements

public class Main {
    public static void main(String[] args) {
        int marks = 82;
        String grade;
        if (marks >= 90) grade = "A";
        else if (marks >= 75) grade = "B";
        else grade = "C";
        System.out.println("Grade " + grade);

        String day = "SAT";
        switch (day) {                       // classic switch
            case "SAT":
            case "SUN":
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Weekday");
        }

        int len = switch (day) {             // switch expression (Java 14+)
            case "MON", "FRI", "SUN" -> 6;
            case "TUE" -> 7;
            default -> 8;
        };
        System.out.println(len);
    }
}

Output:

Grade B
Weekend
8

⚠️ Common error: forgetting break in a classic switch falls through to the next case. The arrow form -> never falls through.

6. Loops

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) System.out.print(i + " ");
        System.out.println();

        int[] nums = {4, 8, 15, 16, 23, 42};
        int sum = 0;
        for (int x : nums) sum += x;                // enhanced for
        System.out.println("sum = " + sum);

        int n = 1;
        while (n < 100) n *= 3;
        System.out.println("first power of 3 >= 100: " + n);

        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i * j == 4) break outer;        // labelled break
                System.out.print(i * j + " ");
            }
        }
        System.out.println();
    }
}

Output:

1 2 3 4 5 
sum = 108
first power of 3 >= 100: 243
1 2 3 2 

⚠️ Common error: ArrayIndexOutOfBoundsException from i <= arr.length — valid indices are 0 to arr.length - 1.

7. Functions

In Java, functions are methods inside a class. static methods belong to the class; others need an object. Java is always pass-by-value (for objects, the reference is copied).

import java.util.Arrays;

public class Main {
    static int add(int a, int b) { return a + b; }
    static double add(double a, double b) { return a + b; }      // overloading
    static int sum(int... nums) {                                  // varargs
        int s = 0;
        for (int x : nums) s += x;
        return s;
    }
    static void fill(int[] arr, int v) { Arrays.fill(arr, v); }   // array contents can be changed
    static long fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

    public static void main(String[] args) {
        int[] a = new int[3];
        fill(a, 7);
        System.out.println(add(2, 3) + " " + add(1.5, 2.25) + " " + sum(1, 2, 3, 4));
        System.out.println(Arrays.toString(a) + " " + fib(20));
    }
}

Output:

5 3.75 10
[7, 7, 7] 6765

⚠️ Common error: non-static method cannot be referenced from a static context — call it on an object (new Main().run()) or make it static.

8. Arrays & Data Structures

Arrays have a fixed size. The Collections Framework (java.util) provides dynamic structures.

Interface Common class Use
List ArrayList, LinkedList ordered, index access
Set HashSet, TreeSet unique items (TreeSet is sorted)
Map HashMap, TreeMap key → value
Queue / Deque ArrayDeque, PriorityQueue queue, stack, heap
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 3, 9, 1};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr) + " " + Arrays.binarySearch(arr, 9));

        int[][] grid = new int[2][3];
        grid[1][2] = 8;
        System.out.println(Arrays.deepToString(grid));

        List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Neha"));
        names.add("Kabir");
        Collections.sort(names);
        System.out.println(names + " " + names.get(0) + " " + names.contains("Neha"));

        Map<String, Integer> freq = new HashMap<>();
        for (String w : "to be or not to be".split(" ")) freq.merge(w, 1, Integer::sum);
        System.out.println(new TreeMap<>(freq));

        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1); stack.push(2);
        Queue<Integer> queue = new ArrayDeque<>();
        queue.offer(1); queue.offer(2);
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(List.of(7, 2, 9));
        System.out.println(stack.peek() + " " + queue.peek() + " " + minHeap.poll());

        Set<Integer> unique = new TreeSet<>(List.of(4, 1, 4, 3));
        System.out.println(unique);
    }
}

Output:

[1, 3, 5, 9] 3
[[0, 0, 0], [0, 0, 8]]
[Asha, Kabir, Neha, Ravi] Asha true
{be=2, not=1, or=1, to=2}
2 1 2
[1, 3, 4]

Use StringBuilder to build strings in a loop (Strings are immutable).

⚠️ Common error: ConcurrentModificationException — removing from a list while iterating with for-each. Use an Iterator and it.remove(), or removeIf.

9. Object-Oriented Programming

import java.util.List;

abstract class Account {                                   // abstraction
    private final String owner;                            // encapsulation
    protected double balance;

    Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }
    String getOwner() { return owner; }
    void deposit(double amt) {
        if (amt <= 0) throw new IllegalArgumentException("Amount must be positive");
        balance += amt;
    }
    abstract double monthlyInterest();                     // subclasses must implement

    @Override
    public String toString() { return owner + ": " + balance; }
}

interface Rewardable { int points(); }

class Savings extends Account implements Rewardable {     // inheritance + interface
    Savings(String owner, double balance) { super(owner, balance); }
    @Override double monthlyInterest() { return balance * 0.04 / 12; }
    @Override public int points() { return (int) (balance / 100); }
}

class Current extends Account {
    Current(String owner, double balance) { super(owner, balance); }
    @Override double monthlyInterest() { return 0; }
}

public class Main {
    public static void main(String[] args) {
        List<Account> accounts = List.of(new Savings("Asha", 12000), new Current("Ravi", 5000));
        for (Account a : accounts) {                       // polymorphism
            System.out.printf("%s -> interest %.2f%n", a, a.monthlyInterest());
        }
        Savings s = (Savings) accounts.get(0);
        s.deposit(3000);
        System.out.println(s.getOwner() + " points: " + s.points());
    }
}

Output:

Asha: 12000.0 -> interest 40.00
Ravi: 5000.0 -> interest 0.00
Asha points: 150

Also learn: static members, final (constants, no override, no subclass), access modifiers (private, default, protected, public), equals/hashCode, records (record Point(int x, int y) {}) and enums.

⚠️ Common error: overriding equals without overriding hashCode — objects then behave wrongly as keys in HashMap/HashSet.

10. Advanced Concepts

Exceptions — checked exceptions (like IOException) must be caught or declared with throws:

public class Main {
    static int parse(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            System.out.println("Bad number: " + s);
            return 0;
        } finally {
            System.out.println("checked " + s);
        }
    }
    public static void main(String[] args) {
        System.out.println(parse("42") + parse("4x2"));
    }
}
checked 42
Bad number: 4x2
checked 4x2
42

Generics, lambdas and the Streams API:

import java.util.*;
import java.util.stream.*;

public class Main {
    static <T extends Comparable<T>> T maxOf(List<T> list) {
        T best = list.get(0);
        for (T x : list) if (x.compareTo(best) > 0) best = x;
        return best;
    }
    public static void main(String[] args) {
        List<Integer> nums = List.of(5, 12, 7, 20, 3, 8);
        List<Integer> evensSquared = nums.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .sorted()
                .collect(Collectors.toList());
        int total = nums.stream().mapToInt(Integer::intValue).sum();
        Map<Boolean, Long> bigSmall = nums.stream().collect(Collectors.partitioningBy(n -> n > 7, Collectors.counting()));
        System.out.println(evensSquared + " " + total + " " + bigSmall + " " + maxOf(List.of("kiwi", "apple", "mango")));
    }
}
[64, 144, 400] 55 {false=3, true=3} mango

Multithreading:

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Future<Integer> a = pool.submit(() -> 21 * 2);
        Future<Integer> b = pool.submit(() -> 10 + 5);
        System.out.println(a.get() + b.get());
        pool.shutdown();
    }
}
57

JDBC connects to databases (DriverManager.getConnection(url, user, pass), then PreparedStatement). The JVM loads classes, verifies bytecode, runs it with a JIT compiler and manages memory with the garbage collector (heap = objects, stack = method frames and local variables).

⚠️ Common error: NullPointerException — calling a method on a null reference. Check for null or use Optional.

11. Examples with Output

Example 1 — Reverse each word with StringBuilder

public class Main {
    public static void main(String[] args) {
        String s = "Java at Codify";
        StringBuilder out = new StringBuilder();
        for (String w : s.split(" ")) out.append(new StringBuilder(w).reverse()).append(' ');
        System.out.println(out.toString().trim());
    }
}
avaJ ta yfidoC

Example 2 — Valid parentheses with a stack

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    static boolean valid(String s) {
        Deque<Character> st = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') st.push(c);
            else {
                if (st.isEmpty()) return false;
                char o = st.pop();
                if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{')) return false;
            }
        }
        return st.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println(valid("{[()]}") + " " + valid("([)]") + " " + valid("(("));
    }
}
true false false

Example 3 — Group words by length with streams

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("go", "java", "c", "rust", "python", "js");
        Map<Integer, List<String>> byLen = words.stream()
                .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
        System.out.println(byLen);
    }
}
{1=[c], 2=[go, js], 4=[java, rust], 6=[python]}

12. Practice Problems

Solve these on Codify (choose Java; the class must be named Main):

  1. Sum of Two Numbers — long and fast input (Easy)
  2. Reverse a String — StringBuilder.reverse() (Easy)
  3. Check Palindrome — two pointers (Easy)
  4. Two Sum — HashMap (Easy)
  5. Binary Search — careful with mid = lo + (hi - lo) / 2 (Easy)
  6. Valid Parentheses — ArrayDeque as a stack (Medium)
  7. Maximum Subarray Sum — Kadane (Medium)
  8. Longest Common Subsequence — DP (Medium)

Continue with the Codify DSA Sheet and the Java interview questions.

13. Interview Questions

1. Why is Java platform independent? Code compiles to bytecode that runs on any JVM; the JVM is platform-specific, the bytecode isn't.

2. JDK vs JRE vs JVM? JVM runs bytecode; JRE = JVM + standard libraries (to run programs); JDK = JRE + compiler and tools (to develop).

3. Why are Strings immutable? For security, thread safety and the string pool (literals can be shared), and so their hash codes can be cached.

4. == vs equals()? == compares references (same object) for objects; equals() compares content when overridden (as in String).

5. Abstract class vs interface? Abstract classes can have state, constructors and any methods; a class extends only one. Interfaces define a contract (with default/static methods since Java 8) and a class can implement many.

6. HashMap internal working? An array of buckets; the key's hashCode() picks the bucket and equals() resolves collisions. Since Java 8 long buckets become balanced trees. Average O(1).

7. Checked vs unchecked exceptions? Checked (e.g. IOException) must be caught or declared; unchecked (RuntimeException subclasses like NullPointerException) don't.

8. What is garbage collection? The JVM automatically frees objects that are no longer reachable. You can't force it (System.gc() is only a hint).

9. final, finally, finalize? final — constant/no override/no subclass; finally — block that always runs after try/catch; finalize — deprecated cleanup hook called by the GC.

10. ArrayList vs LinkedList? ArrayList — fast random access, slow inserts in the middle. LinkedList — fast insert/remove at known positions, slow index access.

14. Cheat Sheet & References

Program and I/O

public class Main { public static void main(String[] args) { } }
System.out.println("text"); System.out.printf("%d %.2f%n", n, d);
Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

Strings

s.length(); s.charAt(i); s.substring(a, b); s.indexOf("x");
s.equals(t); s.equalsIgnoreCase(t); s.compareTo(t);
s.split(" "); String.join(",", list); s.trim(); s.toUpperCase();
StringBuilder sb = new StringBuilder(); sb.append(x); sb.reverse(); sb.toString();
Integer.parseInt(s); String.valueOf(n); s.toCharArray();

Arrays

int[] a = new int[n]; int[] b = {1, 2, 3};
Arrays.sort(a); Arrays.fill(a, -1); Arrays.toString(a);
int[][] g = new int[n][m];
Arrays.sort(objs, (x, y) -> x[0] - y[0]);

Collections

List<Integer> list = new ArrayList<>(); list.add(x); list.get(i); list.remove(i);
Map<String, Integer> m = new HashMap<>(); m.put(k, v); m.getOrDefault(k, 0); m.merge(k, 1, Integer::sum);
Set<Integer> set = new HashSet<>(); set.add(x); set.contains(x);
Deque<Integer> st = new ArrayDeque<>(); st.push(x); st.pop(); st.peek();
Queue<Integer> q = new ArrayDeque<>(); q.offer(x); q.poll();
PriorityQueue<Integer> maxH = new PriorityQueue<>(Collections.reverseOrder());
Collections.sort(list); Collections.reverse(list); Collections.max(list);

OOP

class Dog extends Animal implements Pet { @Override void speak() { } }
abstract class Animal { abstract void speak(); }
interface Pet { default void play() { } }
record Point(int x, int y) { }
enum Level { LOW, HIGH }

Streams and lambdas

list.stream().filter(x -> x > 0).map(x -> x * 2).collect(Collectors.toList());
list.stream().mapToInt(Integer::intValue).sum();
list.forEach(System.out::println);
Collectors.groupingBy(String::length);

Exceptions

try { risky(); } catch (IOException | RuntimeException e) { e.printStackTrace(); } finally { close(); }
throw new IllegalArgumentException("bad input");
try (BufferedReader r = Files.newBufferedReader(path)) { }

Official documentation