1. Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It follows the principle "Write Once, Run Anywhere" (WORA).
Why Learn Java?
- Platform Independent - Runs on any device with JVM
- Object-Oriented - Clean OOP implementation
- High Demand - Enterprise, Android, web applications
- Robust - Strong memory management, exception handling
- Secure - Built-in security features
Java vs Other Languages
| Feature | Java | Python | C++ |
|---|---|---|---|
| Typing | Static | Dynamic | Static |
| Compilation | Bytecode (JVM) | Interpreted | Native |
| Memory | Garbage Collected | Garbage Collected | Manual |
| Speed | Fast | Slower | Fastest |
How Java Works
// Java Source Code (.java) // ↓ Compile // Bytecode (.class) // ↓ JVM // Machine Code // ↓ Execute // Output
2. Environment Setup
Install JDK
Download JDK:
Visit oracle.com/java or use OpenJDK
Popular versions: JDK 17 (LTS), JDK 21 (LTS)
First Program
// Save as HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Compile and Run:
javac HelloWorld.java // Compile java HelloWorld // Run
📌 File Naming: The filename must match the class name (HelloWorld.java).
3. Basic Syntax
public class MyClass { // Main method - entry point public static void main(String[] args) { // Statement System.out.println("Hello!"); // Multiple statements on one line int x = 5; int y = 10; } }
Key Rules
- Every statement ends with semicolon
; - Code blocks use curly braces
{} - Class names start with uppercase
- Method names start with lowercase
- Java is case-sensitive
4. Variables and Data Types
Primitive Data Types
| Type | Size | Range | Example |
|---|---|---|---|
byte | 1 byte | -128 to 127 | byte b = 100; |
short | 2 bytes | -32K to 32K | short s = 1000; |
int | 4 bytes | -2B to 2B | int x = 42; |
long | 8 bytes | Very large | long l = 100L; |
float | 4 bytes | 6 decimal | float f = 3.14f; |
double | 8 bytes | 15 decimal | double d = 3.14159; |
char | 2 bytes | 0 to 65K | char c = 'A'; |
boolean | 1 bit | true/false | boolean b = true; |
Variable Declaration
// Explicit type int age = 25; double salary = 50000.50; String name = "Alice"; // var (Java 10+) var x = 42; // int var text = "hello"; // String // Constants final double PI = 3.14159;
Type Casting
// Widening (automatic) int x = 100; double d = x; // int → double // Narrowing (manual) double pi = 3.99; int n = (int) pi; // 3 (truncates)
5. Input/Output
Output
System.out.print("Hello"); // No newline System.out.println("Hello"); // With newline System.out.printf("Name: %s, Age: %d\n", name, age);
Input with Scanner
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter name: "); String name = sc.nextLine(); System.out.print("Enter age: "); int age = sc.nextInt(); System.out.printf("Name: %s, Age: %d\n", name, age); sc.close(); } }
6. Operators
Arithmetic
int a = 10, b = 3; a + b // 13 a - b // 7 a * b // 30 a / b // 3 (integer division) a % b // 1 (modulus)
Comparison & Logical
// Comparison a == b // equal to a != b // not equal a > b // greater than a < b // less than a >= b // greater or equal a <= b // less or equal // Logical a && b // AND a || b // OR !a // NOT // Ternary int max = (a > b) ? a : b;
Increment/Decrement
int x = 5; x++; // x = 6 (post-increment) ++x; // x = 7 (pre-increment) x--; // x = 6 (post-decrement) --x; // x = 5 (pre-decrement)
7. Conditional Statements
int age = 25; if (age >= 18) { System.out.println("Adult"); } else if (age >= 13) { System.out.println("Teen"); } else { System.out.println("Child"); } // Switch statement int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Other"); } // Enhanced switch (Java 14+) String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Other"; };
8. Loops
// for loop for (int i = 0; i < 5; i++) { System.out.println(i); } // Enhanced for (for-each) int[] nums = {1, 2, 3, 4, 5}; for (int n : nums) { System.out.println(n); } // while loop int count = 0; while (count < 5) { System.out.println(count); count++; } // do-while loop do { System.out.println(count); count--; } while (count > 0); // break and continue for (int i = 0; i < 10; i++) { if (i == 5) break; // Exit loop if (i % 2 == 0) continue; // Skip iteration System.out.println(i); }
9. Methods
public class Calculator { // Method with return value public static int add(int a, int b) { return a + b; } // Method without return public static void greet(String name) { System.out.println("Hello, " + name); } // Method with default behavior (overloading) public static int add(int a, int b, int c) { return a + b + c; } // Varargs public static int sum(int... numbers) { int total = 0; for (int n : numbers) total += n; return total; } public static void main(String[] args) { System.out.println(add(5, 3)); // 8 System.out.println(add(1, 2, 3)); // 6 System.out.println(sum(1, 2, 3, 4)); // 10 } }
10. Arrays
// Declaration int[] nums = new int[5]; int[] nums2 = {1, 2, 3, 4, 5}; // Access System.out.println(nums2[0]); // 1 nums2[1] = 10; // Length System.out.println(nums2.length); // 5 // Loop through array for (int n : nums2) { System.out.println(n); } // Multi-dimensional array int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int[] row : matrix) { for (int val : row) { System.out.print(val + " "); } System.out.println(); }
11. Strings
String s = "Hello World"; // Methods s.length() // 11 s.toUpperCase() // HELLO WORLD s.toLowerCase() // hello world s.charAt(0) // H s.substring(0, 5) // Hello s.indexOf("World") // 6 s.contains("World") // true s.equals("Hello") // false s.trim() // Remove whitespace s.replace("World", "Java") // Hello Java s.split(" ") // ["Hello", "World"] // String comparison String a = "hello"; String b = "hello"; a.equals(b) // true (content) a == b // false (reference) // String concatenation String result = "Hello" + " " + "World"; // StringBuilder (mutable, faster) StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(" World"); String final = sb.toString();
12. OOP Concepts
public class Student { // Instance variables (encapsulation) private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getter public String getName() { return name; } // Setter public void setName(String name) { this.name = name; } // toString method public String toString() { return "Student{name='" + name + "', age=" + age + "}"; } public static void main(String[] args) { Student s = new Student("Alice", 20); System.out.println(s.toString()); } }
13. Inheritance
// Parent class class Animal { String name; public void eat() { System.out.println(name + " is eating"); } } // Child class class Dog extends Animal { public void bark() { System.out.println(name + " is barking"); } } // Using inheritance Dog dog = new Dog(); dog.name = "Rex"; dog.eat(); // From Animal dog.bark(); // From Dog // super keyword class Puppy extends Dog { public void play() { super.eat(); // Call parent method System.out.println(name + " is playing"); } }
14. Polymorphism
class Shape { public void draw() { System.out.println("Drawing shape"); } } class Circle extends Shape { public void draw() { System.out.println("Drawing circle"); } } class Square extends Shape { public void draw() { System.out.println("Drawing square"); } } // Polymorphism in action Shape s1 = new Circle(); Shape s2 = new Square(); s1.draw(); // Drawing circle s2.draw(); // Drawing square
Method Overloading
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } }
15. Abstraction
Abstract Class
abstract class Animal { String name; abstract void makeSound(); // No body void sleep() { // Has body System.out.println(name + " is sleeping"); } } class Dog extends Animal { void makeSound() { System.out.println("Woof!"); } }
Interfaces
interface Drawable { void draw(); // implicitly public abstract default void fill() { // default method System.out.println("Filling shape"); } } interface Resizable { void resize(double factor); } // Implementing multiple interfaces class Circle implements Drawable, Resizable { public void draw() { System.out.println("Drawing circle"); } public void resize(double factor) { System.out.println("Resizing by " + factor); } }
16. Exception Handling
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } catch (Exception e) { System.out.println("General error"); } finally { System.out.println("Always runs"); } // Custom exception class AgeException extends Exception { public AgeException(String message) { super(message); } } public static void setAge(int age) throws AgeException { if (age < 0) throw new AgeException("Age cannot be negative"); }
17. Collections Framework
ArrayList
import java.util.ArrayList; ArrayList<String> list = new ArrayList<>(); list.add("Alice"); list.add("Bob"); list.get(0); // Alice list.set(1, "Charlie"); list.remove(0); list.size(); // 1 list.contains("Bob"); // false for (String name : list) { System.out.println(name); }
HashMap
import java.util.HashMap; HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30); map.get("Alice"); // 25 map.containsKey("Bob"); // true map.remove("Bob"); // Iterate for (String key : map.keySet()) { System.out.println(key + ": " + map.get(key)); }
LinkedList
import java.util.LinkedList; LinkedList<String> queue = new LinkedList<>(); queue.addFirst("First"); queue.addLast("Last"); queue.getFirst(); queue.getLast(); queue.removeFirst(); queue.removeLast();
18. File I/O
import java.io.*; import java.nio.file.*; // Write to file try (BufferedWriter writer = new BufferedWriter( new FileWriter("file.txt"))) { writer.write("Hello, World!\n"); writer.write("Second line\n"); } // Read from file try (BufferedReader reader = new BufferedReader( new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } // Java NIO (modern way) Files.writeString(Path.of("file.txt"), "Hello!"); String content = Files.readString(Path.of("file.txt"));
19. Lambda Expressions
// Lambda syntax // (parameters) -> expression // (parameters) -> { statements; } // Functional interface @FunctionalInterface interface MathOperation { int operate(int a, int b); } MathOperation add = (a, b) -> a + b; MathOperation sub = (a, b) -> a - b; System.out.println(add.operate(5, 3)); // 8 System.out.println(sub.operate(5, 3)); // 2 // With Collections ArrayList<String> names = new ArrayList<>(); names.add("Charlie"); names.add("Alice"); names.add("Bob"); names.sort((a, b) -> a.compareTo(b)); names.forEach(name -> System.out.println(name));
Stream API
import java.util.stream.*; List<Integer> nums = List.of(1, 2, 3, 4, 5); // Filter even numbers List<Integer> evens = nums.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); // Map to squares List<Integer> squares = nums.stream() .map(n -> n * n) .collect(Collectors.toList()); // Sum int sum = nums.stream() .reduce(0, Integer::sum);
20. Practice Problems
Beginner
1. FizzBuzz Easy
View Solution
public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { if (i % 15 == 0) System.out.println("FizzBuzz"); else if (i % 3 == 0) System.out.println("Fizz"); else if (i % 5 == 0) System.out.println("Buzz"); else System.out.println(i); } } }
2. Palindrome Check Easy
View Solution
public static boolean isPalindrome(String s) { String reversed = new StringBuilder(s) .reverse().toString(); return s.equals(reversed); }
Intermediate
3. Bubble Sort Medium
View Solution
public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
4. Binary Search Medium
View Solution
public static int binarySearch(int[] arr, int target) { int low = 0, high = arr.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }
Advanced
5. Linked List Hard
View Solution
class Node { int data; Node next; Node(int data) { this.data = data; } } class LinkedList { Node head; void add(int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; } Node reverse(Node head) { Node prev = null, curr = head; while (curr != null) { Node next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } }
💡 Next Steps:
- Learn Spring Boot for web development
- Explore Android development
- Practice on LeetCode and HackerRank
- Build projects: REST API, CRUD app