Back to Premium Vault
Premium Vault / Java ProgrammingFree Programming Course

CODESTUDIO / GO BEYOND SYNTAX

Java ProgrammingFundamentals, OOP, Collections & JVM Internals

A comprehensive Java course covering syntax, OOP, collections, exceptions, generics, concurrency, JVM internals, JDBC, testing and best practices.

6 learning modules18 review questions30 practice drillsSelf-paced learning
Java Programming / learning workspace

Your technical depth starts here.

MODULE 1 / 6

Module 1 — Java Fundamentals and Basics

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:

bash
javac Hello.java
java Hello

These 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):

java
public class Hello {
// main method
public static void main(String[] args) {
// Output: Hello, world!
System.out.println("Hello, world!");
}
}

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

java
**Example**
int num = 5;
String s = "quickref.me";
final int MAX = 100;
final List<String> list = new ArrayList<>(); // list reference final but contents modifiable

Stack 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:

java
if (x < 0) { ... } else if (x == 0) { ... } else { ... }geeksforgeeks
switch: supports ints, enums, Strings (since Java 7); since Java 14 enhanced switch expressions exist (briefly mention). Use break to avoid fallthrough. Example:
switch (month) {
case 1 -> System.out.println("January");
case 2 -> System.out.println("February");
default -> 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:

java
for (...) {
for (...) {
if (cond) break outer;
}

}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:

java
String s1 = "value"; // literal, may be interned
String s2 = new String("value"); // new object
String 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:

java
StringBuilder sb = new StringBuilder();
sb.append("QuickRef");
sb.insert(0, "My ");
sb.delete(5, 9);
sb.append("!");
String 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:

java
String a = "hello";
a.concat("world");
System.out.println(a); // prints "hello"
String b = a.concat("world");
System.out.println(b); // "helloworld"geeksforgeeks

Performance 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:

java
int[] a1;
int[] a2 = {1,2,3};
int[] a3 = new int[]{1,2,3};
int[] a4 = new int; // defaults to 0abit

Access and length: a2 == 1, arrays have .length (not method). Access out of bounds throws ArrayIndexOutOfBoundsException.geeksforgeeks Multidimensional arrays:

java
int[][] matrix = { {1,2,3}, {4,5} }; // jagged arrays supported
int x = matrix; // 4vtu.ac

Common 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:

java
void reverse(int[] arr) {
int i=0,j=arr.length-1;
while (i<j) {
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
i++; j--;
}

}geeksforgeeks

1.11 Basic I/O and user input

Console output:

java
System.out.println("text"); // newline
System.out.print("text"); // no newline
System.out.printf("Hello %s: %d%n", name, age); // formatted output

Console input with Scanner:

java
Scanner in = new Scanner(System.in);
String line = in.nextLine();
int n = in.nextInt();

// Caution: nextInt leaves newline; call in.nextLine() to consume remainder before nextLine() reading.geeksforgeeks BufferedReader example (older, faster for line reading):

java
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();

File reading (contemporary NIO):

java
Path p = Paths.get("file.txt");
List<String> lines = Files.readAllLines(p, StandardCharsets.UTF_8);

Example program:

java
import java.util.Scanner;
public class Greet {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
String name = in.nextLine();
System.out.print("Enter age: ");
int age = in.nextInt();
System.out.printf("Hello %s, age %d%n", name, age);
in.close();
}

}vtu.ac

1.12 Consolidated Cheat‑sheet (your provided content, organized)

Hello world and compile/run:

bash
javac Hello.java
java Hello

Output: Hello, world!vtu.ac Variables examples:

java
int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "quickref.me";geeksforgeeks

Primitive 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:

java
String s = 3 + "str" + 3; // "3str3"
String s = 3 + 3 + "str"; // "6str"geeksforgeeks

Loops 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.