Java ProgrammingFundamentals, OOP, Collections & JVM Internals
A comprehensive Java course covering syntax, OOP, collections, exceptions, generics, concurrency, JVM internals, JDBC, testing and best practices.
Your Learning Progress
Module 1 — Java Fundamentals and Basics
Goal: Build a rock‑solid foundation in Java syntax, types, memory basics, control flow, strings, arrays, I/O, and common utilities so you can write, compile, run, and reason about Java programs confidently.geeksforgeeks
1.1 Introduction to Java
What is Java: Java is a high‑level, class‑based, object‑oriented programming language designed to be platform independent and robust; Java programs compile to bytecode that runs on the JVM (Java Virtual Machine).geeksforgeeks Key editions: Java SE (Standard Edition) for core language/libraries, Jakarta/Java EE for enterprise, Java ME for embedded devices.vtu.ac JVM / JRE / JDK explained: JDK (Java Development Kit): tools to develop (javac, jar) and runtime.vtu.ac JRE (Java Runtime Environment): JVM plus standard libraries needed to run Java apps.vtu.ac JVM (Java Virtual Machine): executes bytecode, provides memory management and garbage collection.vtu.ac Why Java: portability (write‑once‑run‑anywhere), large ecosystem, strong standard library, and automatic memory management.geeksforgeeks
1.2 Setup and Tools
Install JDK (OpenJDK or Oracle JDK), set JAVA_HOME to installation path, and add bin to PATH. Verify with javac -version and java -version.vtu.ac IDE options: IntelliJ IDEA (recommended), Eclipse, VS Code with Java extensions.vtu.ac Command‑line essentials: javac (compile .java to .class), java (run class), jar (package). Example:
1javac Hello.java2java HelloThese commands compile and run your program; javac produces Hello.class which the JVM runs.vtu.ac
1.3 First Program: Hello World (structure and explanation)
Code (copy‑paste):
1public class Hello {2// main method3public static void main(String[] args) {4// Output: Hello, world!5System.out.println("Hello, world!");6}7}Explanation: class declaration (Hello), main signature public static void main(String[] args) is entry point; System.out.println prints to console. Compile with javac Hello.java, run with java Hello.geeksforgeeks Packages: put package declaration at top (package com.example;), directory structure must match package.vtu.ac
1.4 Java syntax and conventions
Identifiers: letters, digits, underscore, dollar sign; cannot start with digit.geeksforgeeks Access modifiers: public, protected, default (package), private — control visibility.geeksforgeeks main signature: public static void main(String[] args) — public for JVM access, static so it's callable without instance, String[] args holds command‑line args.vtu.ac Comments: // single line, /* / multi‑line, /** / Javadoc. Naming: classes PascalCase, methods/variables camelCase, constants ALL_CAPS.geeksforgeeks
1.5 Primitive types and literals
Primitives (sizes and basic notes): byte: 1 byte, -128 to 127.geeksforgeeks short: 2 bytes, -2^15 to 2^15-1.geeksforgeeks int: 4 bytes, -2^31 to 2^31-1.geeksforgeeks long: 8 bytes, -2^63 to 2^63-1 (use L suffix for literals).geeksforgeeks float: 4 bytes, single precision (use f suffix).geeksforgeeks double: 8 bytes, double precision (default for decimals).geeksforgeeks char: 2 bytes (UTF‑16 code unit).geeksforgeeks boolean: true/false (size not precisely defined).geeksforgeeks Literal forms: Integer: decimal (42), hex (0x2A), binary (0b101010).geeksforgeeks Long: 42L. Float: 3.14f. Double: 3.14. Char: 'A'. String: "text". Boolean: true/false.geeksforgeeks Wrapper classes and auto‑boxing: Integer, Long, Double, Float, Character, Boolean — use when nullability or generics required.geeksforgeeks
1.6 Variables, memory, and scopes
Variable kinds: Local variables: declared inside methods, stored on stack (lifetime limited to method execution).vtu.ac Instance fields: per‑object, stored on heap with object.vtu.ac Static/class fields: one per class, stored in class area/metaspace.vtu.ac Primitive vs reference: primitives hold value directly; references hold pointer to object on heap.vtu.ac final: marks variable immutable after assignment; final reference cannot be reseated but object contents can change (unless object itself is immutable).geeksforgeeks
1**Example**2int num = 5;3String s = "quickref.me";4final int MAX = 100;5final List<String> list = new ArrayList<>(); // list reference final but contents modifiableStack vs heap: stack holds frames and primitive locals/references; heap stores objects and arrays.vtu.ac
1.7 Operators and expressions
Arithmetic: + - * / %; integer division truncates toward zero. Example: 5/2 == 2.geeksforgeeks Increment/decrement: prefix (++i) vs postfix (i++); prefix modifies then yields value; postfix yields then modifies.geeksforgeeks Relational: ==, !=, >, >=, <, <=. For object equality use equals() unless comparing references intentionally.geeksforgeeks Logical: && (short‑circuit), || (short‑circuit), & and | (bitwise, also non‑short‑circuit), ! (not). geeksforgeeks Bitwise: &, |, ^, ~, <<, >>, >>> (unsigned right shift). geeksforgeeks Assignment and compound assignment: =, +=, -=, *=, /=, %= (compound conversions may apply).geeksforgeeks Ternary operator: condition ? expr1 : expr2.geeksforgeeks Precedence: parentheses highest, then unary, multiplicative, additive, shifts, relational, equality, bitwise, logical, ternary, assignment. Use parentheses to clarify.geeksforgeeks Example step‑through: int a = 2; int b = a++ + ++a; // evaluate: a++ yields 2 (a becomes 3), ++a makes a 4 and yields 4, so b = 2 + 4 = 6, final a = 4.geeksforgeeks
1.8 Control flow statements
if / else if / else:
1if (x < 0) { ... } else if (x == 0) { ... } else { ... }geeksforgeeks2switch: supports ints, enums, Strings (since Java 7); since Java 14 enhanced switch expressions exist (briefly mention). Use break to avoid fallthrough. Example:3switch (month) {4case 1 -> System.out.println("January");5case 2 -> System.out.println("February");6default -> System.out.println("Other");}vtu.ac for loops: for (int i = 0; i < n; i++) { ... } enhanced for: for (String s : arr) { ... } — safer for iteration.geeksforgeeks while and do‑while: while (cond) { ... }, do { ... } while (cond); break and continue: break exits loop; continue skips to next iteration; labeled break supports nested loops: outer:
1for (...) {2for (...) {3if (cond) break outer;4}}geeksforgeeks Example: counting loop and early exit.
1.9 Strings and StringBuilder (detailed)
Strings are immutable; operations produce new String instances; string literals may be interned in the string pool.geeksforgeeks Creating Strings:
1String s1 = "value"; // literal, may be interned2String s2 = new String("value"); // new object3String s3 = String.valueOf(123); // "123"Common methods: length(), charAt(i), substring(beginIndex[, endIndex]), indexOf(str), lastIndexOf, contains, startsWith, endsWith, equals, equalsIgnoreCase, toLowerCase, toUpperCase, trim, split, replace, toCharArray, isEmpty.geeksforgeeks Concatenation: + operator creates new Strings; repeated concatenation in loops is inefficient. Use StringBuilder or StringBuffer for mutable sequences:
1StringBuilder sb = new StringBuilder();2sb.append("QuickRef");3sb.insert(0, "My ");4sb.delete(5, 9);5sb.append("!");6String result = sb.toString();// Example shows building and modifying with indices.geeksforgeeks Comparison: s1 == s2 checks reference equality; s1.equals(s2) checks content. For ordering use compareTo.geeksforgeeks Example demonstrating immutability:
1String a = "hello";2a.concat("world");3System.out.println(a); // prints "hello"4String b = a.concat("world");5System.out.println(b); // "helloworld"geeksforgeeksPerformance tip: for repeated concatenation (e.g., building CSV rows or logs) use StringBuilder and preallocate capacity when possible.geeksforgeeks
1.10 Arrays (single and multi‑dimensional)
Declaration forms:
1int[] a1;2int[] a2 = {1,2,3};3int[] a3 = new int[]{1,2,3};4int[] a4 = new int; // defaults to 0abitAccess and length: a2 == 1, arrays have .length (not method). Access out of bounds throws ArrayIndexOutOfBoundsException.geeksforgeeks Multidimensional arrays:
1int[][] matrix = { {1,2,3}, {4,5} }; // jagged arrays supported2int x = matrix; // 4vtu.acCommon utilities: Arrays.toString(arr), Arrays.deepToString(matrix), Arrays.sort(arr), Arrays.binarySearch(arr, key). Use System.arraycopy for efficient copying.geeksforgeeks Example: double loop to iterate matrix; reversing an array in place:
1void reverse(int[] arr) {2int i=0,j=arr.length-1;3while (i<j) {4int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;5i++; j--;6}}geeksforgeeks
1.11 Basic I/O and user input
Console output:
1System.out.println("text"); // newline2System.out.print("text"); // no newline3System.out.printf("Hello %s: %d%n", name, age); // formatted outputConsole input with Scanner:
1Scanner in = new Scanner(System.in);2String line = in.nextLine();3int n = in.nextInt();// Caution: nextInt leaves newline; call in.nextLine() to consume remainder before nextLine() reading.geeksforgeeks BufferedReader example (older, faster for line reading):
1BufferedReader br = new BufferedReader(new InputStreamReader(System.in));2String s = br.readLine();File reading (contemporary NIO):
1Path p = Paths.get("file.txt");2List<String> lines = Files.readAllLines(p, StandardCharsets.UTF_8);Example program:
1import java.util.Scanner;2public class Greet {3public static void main(String[] args) {4Scanner in = new Scanner(System.in);5System.out.print("Enter name: ");6String name = in.nextLine();7System.out.print("Enter age: ");8int age = in.nextInt();9System.out.printf("Hello %s, age %d%n", name, age);10in.close();11}}vtu.ac
1.12 Consolidated Cheat‑sheet (your provided content, organized)
Hello world and compile/run:
1javac Hello.java2java HelloOutput: Hello, world!vtu.ac Variables examples:
1int num = 5;2float floatNum = 5.99f;3char letter = 'D';4boolean bool = true;5String site = "quickref.me";geeksforgeeksPrimitive Data Types (size, default, range): (condensed) byte 1 byte, short 2 byte, int 4 byte, long 8 byte, float 4 byte, double 8 byte, char 2 byte, boolean N/A.geeksforgeeks Strings quick facts and operations: creation, concatenation rules, StringBuilder usage, immutability, comparison using equals(), common methods (length, charAt, substring, indexOf, toUpperCase, toLowerCase, trim). Example concatenations:
1String s = 3 + "str" + 3; // "3str3"2String s = 3 + 3 + "str"; // "6str"geeksforgeeksLoops example: for (char c: "QuickRef".toCharArray()) System.out.print(c + "-"); // Q-u-i-c-k-R-e-f-geeksforgeeks Arrays examples and initialization (single & multi‑dimensional); Arrays.deepToString(matrix).geeksforgeeks Swap using temp: int a=1,b=2; int temp=a; a=b; b=temp;geeksforgeeks Type casting: widening: int i=10; long l=i; narrowing: double d=10.02; long l=(long)d;geeksforgeeks Parse/format helpers: String.valueOf(10), Integer.parseInt("10"), Double.parseDouble("10")geeksforgeeks Conditionals and switch example (use break after case to avoid fallthrough). Ternary operator usage. User input snippet with Scanner.geeksforgeeks Java Collections quick table (condensed): ArrayList (List): ordered, allows duplicates, not synchronized.geeksforgeeks Vector: synchronized List.geeksforgeeks LinkedList: List and Deque.geeksforgeeks HashSet: no order, no duplicates.geeksforgeeks LinkedHashMap: preserves insertion order, map.geeksforgeeks HashMap: key→value map, one null key allowed.geeksforgeeks Common Math methods: Math.max, Math.min, Math.abs, Math.sqrt, Math.pow, Math.round, Math.sin, Math.cos, Math.tan, Math.log, Math.toDegrees, Math.toRadians.geeksforgeeks Try/catch/finally template: try { /* risky code / } catch(Exception e) { e.printStackTrace(); } finally { / always runs */ }geeksforgeeks Common snippets: StringBuilder operations (append, delete, insert), Arrays.sort, Collections utility usage, forEach lambda, HashMap get/put basics.geeksforgeeks
1.13 Exercises (with hints)
Easy Print first N Fibonacci numbers. Hint: iterative loop with two variables.geeksforgeeks Check if a number is prime. Hint: check divisibility up to sqrt(n).geeksforgeeks Medium Reverse words in a sentence preserving word order (e.g., "hello world" -> "olleh dlrow"). Hint: split by whitespace, reverse each string.geeksforgeeks CLI calculator supporting + - * / and integer operands using switch.geeksforgeeks Hard Implement a dynamic array (like ArrayList): internal int[] buffer, add, removeAt(index), get(index), resize to double capacity when full. Include tests.geeksforgeeks CLI contact manager storing contacts in CSV, with add/list/search/delete and save/load using Files API.vtu.ac
1.14 Debugging and common errors
Read stack traces from top to bottom; the first "Caused by" often shows root cause.vtu.ac Frequent errors: NullPointerException (dereferencing null), NumberFormatException (parsing invalid strings), ArrayIndexOutOfBoundsException, ClassCastException.vtu.ac Tips: use debugger to step through, set breakpoints, inspect variables, and reproduce minimal failing example.vtu.ac
1.15 Mini project (end of module)
Contact Manager (in‑memory then file persistence) Requirements: add contact (name, phone, email), list all contacts, search by name (case‑insensitive), delete by id, save/load from CSV.vtu.ac Suggested steps: Design Contact class (fields, constructor, toString). Build ContactManager with List<Contact> and methods add, list, search, delete, save, load. Build CLI (main) using Scanner to read commands and call ContactManager methods. Persist using Files.write/Files.readAllLines or simple serialization. This practice reinforces classes, lists, I/O, string parsing, and exception handling.
Practice Drill
Module 1 Quiz
Practice Drill Bank
Every practice drill from the course, organised by module. Rehearse these until they feel automatic.
Final Revision Checklist
Tick items as you master them — progress saves automatically.
Module 1 – Module 1 — Java Fundamentals and Basics
Module 2 – Module 2 — Object-Oriented Programming in Java
Module 3 – Module 3 — Collections Framework and Core APIs
Module 4 – Module 4 — Exceptions, Generics, File I/O, and Lambdas
Module 5 – Module 5 — Concurrency, Networking, and JVM Internals
Module 6 – Module 6 — Advanced Topics, Best Practices, and Project
Congratulations!
You've finished the CodeStudio Java Programming course. Revise, drill, and keep building.