⚡ Java Online Compiler

Output
// यहाँ output दिखेगा...
Ready

☕ Java Complete Tutorial

Puri Java Hindi mein — Beginners se Advanced tak | Oracle Java SE

CH-01

Java क्या है?

परिचय (Introduction)

Java एक high-level, object-oriented programming language है जिसे Sun Microsystems ने 1995 में बनाया था। बाद में Oracle ने इसे खरीद लिया। Java का मुख्य slogan है: "Write Once, Run Anywhere" (WORA)।

आसान भाषा में: Java ऐसी language है जिसमें आप एक बार code लिखो और वो किसी भी computer पर — Windows हो, Mac हो, Linux हो — सब पर चल जाता है।

Java की मुख्य विशेषताएं (Features)

1. Platform Independent

Java code किसी भी OS पर बिना बदले चलता है। यह JVM (Java Virtual Machine) की वजह से होता है।

2. Object-Oriented

Java में सब कुछ Object है। Class और Object के through programming होती है।

3. Simple

C++ जैसी languages से Java सरल है — memory management खुद होती है, pointers नहीं हैं।

4. Secure

Java में built-in security features हैं — no direct memory access, bytecode verification, sandbox environment।

5. Robust (मजबूत)

Java में automatic Garbage Collection है जो unused memory को साफ करती है। Exception Handling से program crash कम होता है।

6. Multithreaded

Java एक साथ कई tasks (threads) run कर सकती है।

7. Distributed

Java network programming के लिए बेहतरीन है — internet applications आसानी से बनते हैं।

8. High Performance

JIT (Just-In-Time) Compiler bytecode को machine code में convert करता है जिससे speed बढ़ती है।

ℹ️ Java का उपयोग: Android Apps, Web Applications (Spring Boot), Enterprise Software, Desktop Apps, Big Data (Hadoop), Embedded Systems में होता है।

Java के Versions (Oracle Java SE)

VersionYearMajor Feature
Java 1.01996पहला version
Java 52004Generics, Autoboxing, Enum
Java 82014Lambda, Stream API (Most popular)
Java 112018LTS, String methods
Java 172021LTS, Sealed Classes
Java 212023LTS, Virtual Threads
CH-02

Java कैसे काम करती है?

Compile & Run Process

Java program चलने के लिए 3 steps होते हैं:

// Step 1: आप .java file लिखते हैं
Hello.java  →  (javac compiler चलाओ)

// Step 2: javac compiler .class file बनाता है (bytecode)
Hello.class  →  (JVM पर दो)

// Step 3: JVM bytecode को machine code में चलाता है
java Hello  →  Output आता है!

Bytecode क्या है?

Bytecode ना तो machine language है, ना पूरी तरह human-readable। यह JVM के लिए intermediate code है। इसी की वजह से Java platform independent है — हर OS का अपना JVM होता है।

JVM, JRE, JDK — क्या फर्क है?

TermFull Formकामकिसे चाहिए
JVMJava Virtual MachineBytecode को execute करता हैसबको
JREJava Runtime EnvironmentJVM + Libraries (program चलाने के लिए)Users को
JDKJava Development KitJRE + javac compiler + tools (develop करने के लिए)Developers को

JVM के अंदर क्या होता है?

JVM के मुख्य parts:

// Command line process:
$ javac Hello.java   // Compilation — Hello.class बनेगी
$ java Hello         // Execution — JVM Hello.class को run करेगा
💡 याद रखो: जब आप java Hello लिखते हैं तो .class मत लिखो, सिर्फ class का नाम लिखो।
CH-03

Setup & पहला Program

JDK Install कैसे करें?

  1. Oracle की website oracle.com/java/technologies/downloads पर जाओ
  2. अपने OS (Windows/Mac/Linux) के लिए JDK download करो
  3. Install करो
  4. Environment Variable में JAVA_HOME और PATH set करो
// Verify installation
$ java --version
java 21.0.1 ...

$ javac --version
javac 21.0.1

पहला Program: Hello World

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

main() Method को समझें

Java program हमेशा main() method से शुरू होता है। यह JVM का entry point है।

CH-04

Java Structure Deep Understanding

पूरी structure को line by line समझें

// File का नाम: MyProgram.java (class के नाम जैसा होना जरूरी है)

public class MyProgram {          // class keyword — blueprint

    public static void main(String[] args) {  // entry point
        System.out.println("Namaste!");
    }

}

public क्यों?

public एक access modifier है। इसका मतलब है — यह class/method सबके लिए accessible है। JVM को main() को बाहर से call करना होता है, इसलिए public जरूरी है।

class क्या है?

Class एक blueprint/template है। जैसे घर का नक्शा (blueprint) होता है — एक ही नक्शे से कई घर (objects) बन सकते हैं।

static क्यों?

static का मतलब है — यह method class का हिस्सा है, किसी object का नहीं। JVM बिना object बनाए main() को directly call करता है, इसलिए static जरूरी है।

void क्यों?

void मतलब — यह method कुछ भी return नहीं करता। main() JVM को कुछ वापस नहीं देता।

File Name Rules

⚠️ अगर file का नाम और public class का नाम अलग हुआ तो javac error देगा: "class X is public, should be declared in a file named X.java"
CH-05

Variables & Data Types

Variable क्या है?

Variable एक named memory location है जहाँ data store होता है।

int age = 25;       // int = type, age = name, 25 = value
String name = "Rahul";
double salary = 50000.50;

Primitive Data Types (8 types)

TypeSizeRangeExample
byte1 byte-128 to 127byte b = 100;
short2 bytes-32,768 to 32,767short s = 5000;
int4 bytes-2³¹ to 2³¹-1int x = 99999;
long8 bytesVery largelong l = 99L;
float4 bytes6-7 decimal digitsfloat f = 3.14f;
double8 bytes15 decimal digitsdouble d = 3.14159;
char2 bytes0 to 65,535 (Unicode)char c = 'A';
boolean1 bittrue / falseboolean ok = true;

Non-Primitive Types

ये JVM के Heap memory में store होते हैं और null हो सकते हैं।

Type Casting

// Widening (automatic — छोटे से बड़े में)
int a = 10;
double d = a;  // auto — 10.0

// Narrowing (manual — बड़े से छोटे में)
double x = 9.7;
int y = (int) x;  // 9 — decimal हट जाता है

var (Java 10+)

var name = "Rohan";   // compiler खुद type समझता है (String)
var age = 21;          // int
CH-06

Operators

Arithmetic Operators

int a = 10, b = 3;
System.out.println(a + b);   // 13  — जोड़
System.out.println(a - b);   // 7   — घटाव
System.out.println(a * b);   // 30  — गुणा
System.out.println(a / b);   // 3   — भाग (int/int = int)
System.out.println(a % b);   // 1   — शेषफल (modulo)

Relational / Comparison Operators

// Result हमेशा boolean (true/false) होता है
a == b   // बराबर है?
a != b   // बराबर नहीं?
a > b    // बड़ा है?
a < b    // छोटा है?
a >= b   // बड़ा या बराबर?
a <= b   // छोटा या बराबर?

Logical Operators

boolean x = true, y = false;
x && y   // AND — दोनों true हों तो true (false)
x || y   // OR  — कोई एक true हो तो true (true)
!x       // NOT — उल्टा (false)

Assignment Operators

int n = 10;
n += 5;   // n = n + 5 = 15
n -= 3;   // n = n - 3 = 12
n *= 2;   // n = n * 2 = 24
n /= 4;   // n = n / 4 = 6
n %= 4;   // n = n % 4 = 2

Increment / Decrement

int i = 5;
i++;   // post-increment: पहले use, फिर बढ़ाओ
++i;   // pre-increment:  पहले बढ़ाओ, फिर use
i--;   // post-decrement
--i;   // pre-decrement

Ternary Operator

int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
// condition ? true_value : false_value

Bitwise Operators

int a = 5;   // 0101
int b = 3;   // 0011
a & b    // 0001 = 1  (AND)
a | b    // 0111 = 7  (OR)
a ^ b    // 0110 = 6  (XOR)
~a       // -6         (NOT)
a << 1   // 1010 = 10 (left shift)
a >> 1   // 0010 = 2  (right shift)
CH-07

Input & Output

Output (Print)

System.out.println("Hello");   // newline के साथ print
System.out.print("Hello");     // बिना newline
System.out.printf("Name: %s, Age: %d%n", "Rahul", 25);
// %s = String, %d = int, %f = float, %n = newline

Input (Scanner)

import java.util.Scanner;   // Scanner class import करो

public class InputExample {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Apna naam likhein: ");
        String name = sc.nextLine();   // पूरी line लेता है

        System.out.print("Apni age likhein: ");
        int age = sc.nextInt();        // integer लेता है

        System.out.println("Namaste, " + name + "! Age: " + age);

        sc.close();   // Scanner बंद करो (good practice)
    }
}

Scanner के सभी methods

Methodक्या लेता है
nextInt()Integer number
nextDouble()Decimal number
nextFloat()Float number
nextLong()Long number
next()एक word (space तक)
nextLine()पूरी line
nextBoolean()true/false
⚠️ Common Bug: nextInt() के बाद nextLine() use करने पर empty line मिलती है। Fix: nextInt() के बाद एक extra sc.nextLine() लिखो।
CH-08

Conditional Statements

if-else

int marks = 75;

if (marks >= 90) {
    System.out.println("A Grade");
} else if (marks >= 75) {
    System.out.println("B Grade");
} else if (marks >= 60) {
    System.out.println("C Grade");
} else {
    System.out.println("Fail");
}

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 day");
}

Switch Expression (Java 14+)

String result = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Unknown";
};
ℹ️ break भूलने पर "fall-through" होता है — अगले case भी execute होते हैं। Switch में String (Java 7+), int, char, enum use हो सकते हैं।
CH-09

Loops

for Loop

// for (init; condition; update)
for (int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

// Reverse loop
for (int i = 5; i >= 1; i--) {
    System.out.print(i + " ");
}
// Output: 5 4 3 2 1

while Loop

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
// Condition पहले check होती है — अगर false तो loop नहीं चलेगा

do-while Loop

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);
// Condition बाद में check — कम से कम एक बार जरूर चलेगा

for-each Loop (Enhanced for)

int[] nums = {10, 20, 30, 40};
for (int n : nums) {
    System.out.println(n);
}

break & continue

for (int i = 1; i <= 10; i++) {
    if (i == 5) continue;   // 5 skip करो
    if (i == 8) break;      // 8 पर loop बंद
    System.out.print(i + " ");
}
// Output: 1 2 3 4 6 7

Nested Loops — Multiplication Table

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print(i * j + "\t");
    }
    System.out.println();
}
CH-10

Functions (Methods)

Method क्या है?

Method एक reusable block of code है। एक बार लिखो, बार-बार use करो।

// Syntax: modifier returnType methodName(parameters) { body }

public static int add(int a, int b) {
    return a + b;
}

public static void greet(String name) {
    System.out.println("Hello, " + name);
}

public static void main(String[] args) {
    int sum = add(5, 3);       // 8
    greet("Priya");             // Hello, Priya
}

Method Overloading

एक ही नाम के multiple methods — अलग-अलग parameters के साथ।

static int multiply(int a, int b) { return a * b; }
static double multiply(double a, double b) { return a * b; }
static int multiply(int a, int b, int c) { return a * b * c; }

Recursion (पुनरावृत्ति)

// Factorial: 5! = 5×4×3×2×1 = 120
static int factorial(int n) {
    if (n == 0 || n == 1) return 1;   // Base case
    return n * factorial(n - 1);        // Recursive call
}

// Fibonacci
static int fib(int n) {
    if (n <= 1) return n;
    return fib(n-1) + fib(n-2);
}
⚠️ Recursion में Base case जरूरी है। नहीं तो StackOverflowError आएगा।
CH-11

Arrays

1D Array

// Declaration
int[] arr = new int[5];         // 5 elements, default 0
int[] nums = {10, 20, 30, 40}; // direct initialization

// Access
System.out.println(nums[0]);   // 10 (index 0 से शुरू)
nums[1] = 99;                   // modify

// Length
System.out.println(nums.length); // 4

// Loop से print
for (int n : nums) {
    System.out.print(n + " ");
}

2D Array (Matrix)

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

System.out.println(matrix[1][2]);  // 6 (row 1, col 2)

// Print matrix
for (int[] row : matrix) {
    for (int val : row) {
        System.out.printf("%3d", val);
    }
    System.out.println();
}

Arrays class (java.util.Arrays)

import java.util.Arrays;

int[] arr = {5, 2, 8, 1, 9};

Arrays.sort(arr);               // {1, 2, 5, 8, 9}
System.out.println(Arrays.toString(arr));  // [1, 2, 5, 8, 9]

int idx = Arrays.binarySearch(arr, 5);  // index of 5
int[] copy = Arrays.copyOf(arr, 3);      // {1, 2, 5}
Arrays.fill(arr, 0);               // सब 0 से भरो
CH-12

Strings

String क्या है?

String एक immutable (न बदलने वाला) sequence of characters है। String pool में store होती है।

String s1 = "Hello";         // String literal — pool में
String s2 = new String("Hello"); // Heap में

String के सभी Methods

String s = "Hello Java";

s.length()              // 10
s.charAt(0)             // 'H'
s.indexOf("Java")       // 6
s.substring(6)          // "Java"
s.substring(0, 5)       // "Hello"
s.toUpperCase()         // "HELLO JAVA"
s.toLowerCase()         // "hello java"
s.trim()                // spaces हटाता है (start/end)
s.replace("Java", "World") // "Hello World"
s.contains("Java")      // true
s.startsWith("Hello")   // true
s.endsWith("Java")      // true
s.split(" ")             // ["Hello", "Java"]
s.isEmpty()             // false
s.isBlank()             // false (Java 11+)
s.equals("Hello Java")  // true (case-sensitive)
s.equalsIgnoreCase("hello java") // true
s.compareTo("Hi")       // alphabetical comparison
String.valueOf(42)       // "42" (int to String)
Integer.parseInt("42")  // 42 (String to int)

String vs StringBuilder vs StringBuffer

StringStringBuilderStringBuffer
Mutable?❌ नहीं✅ हाँ✅ हाँ
Thread Safe?✅❌✅
SpeedSlow (concatenation में)FastMedium
Use WhenFixed textLoop में string बनानाMulti-threading
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");      // "Hello Java"
sb.insert(5, ",");        // "Hello, Java"
sb.delete(5, 6);         // "Hello Java"
sb.reverse();             // "avaJ olleH"
sb.toString();            // String में convert
CH-13

Class & Object

Class क्या है?

Class एक blueprint है — जैसे car का design। इससे actual cars (objects) बनती हैं।

Object क्या है?

Object class का instance है — जैसे blueprint से बनी actual car।

class Student {
    // Fields (attributes)
    String name;
    int age;
    double marks;

    // Constructor
    Student(String name, int age, double marks) {
        this.name = name;      // this = current object
        this.age = age;
        this.marks = marks;
    }

    // Method
    void display() {
        System.out.println(name + " | Age: " + age + " | Marks: " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        // Object बनाओ
        Student s1 = new Student("Ravi", 20, 88.5);
        Student s2 = new Student("Priya", 19, 92.0);

        s1.display();   // Ravi | Age: 20 | Marks: 88.5
        s2.display();   // Priya | Age: 19 | Marks: 92.0
    }
}

Constructor के प्रकार

class Car {
    String brand;
    int speed;

    // Default Constructor (no parameters)
    Car() {
        brand = "Unknown";
        speed = 0;
    }

    // Parameterized Constructor
    Car(String brand, int speed) {
        this.brand = brand;
        this.speed = speed;
    }

    // Copy Constructor
    Car(Car other) {
        this.brand = other.brand;
        this.speed = other.speed;
    }
}

this keyword

CH-14

OOP Concepts

1. Encapsulation (कैप्सूल जैसा)

Data और methods को एक class में बंद करना। Fields को private बनाओ, access के लिए getter/setter methods।

class BankAccount {
    private double balance;  // बाहर से direct access नहीं

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    public void withdraw(double amount) {
        if (amount <= balance) balance -= amount;
        else System.out.println("Insufficient balance!");
    }
}

2. Inheritance (विरासत)

Parent class के properties और methods को Child class inherit करना।

class Animal {               // Parent
    String name;
    void eat() { System.out.println(name + " is eating"); }
}

class Dog extends Animal {   // Child
    void bark() { System.out.println("Woof!"); }
}

class GoldenRetriever extends Dog {  // Multi-level
    void fetch() { System.out.println("Fetching!"); }
}

// super keyword — parent class access
class Cat extends Animal {
    Cat(String name) {
        super.name = name;   // parent का field
    }
    void eat() {
        super.eat();          // parent का method
        System.out.println("Cat eats fish");
    }
}

3. Polymorphism (अनेक रूप)

एक ही नाम का अलग-अलग behavior।

// Compile-time (Method Overloading)
class Calculator {
    int add(int a, int b) { return a+b; }
    double add(double a, double b) { return a+b; }
}

// Runtime (Method Overriding)
class Shape {
    void draw() { System.out.println("Drawing Shape"); }
}

class Circle extends Shape {
    @Override
    void draw() { System.out.println("Drawing Circle"); }
}

// Dynamic dispatch
Shape s = new Circle();
s.draw();   // "Drawing Circle" — runtime पर decide

4. Abstraction

Implementation छुपाओ, सिर्फ essential features दिखाओ।

// Abstract Class
abstract class Vehicle {
    abstract void start();     // abstract method — body नहीं
    void stop() { System.out.println("Stopping..."); }
}

class Bike extends Vehicle {
    @Override
    void start() { System.out.println("Kick start!"); }
}

5. Interface

Interface एक pure abstract contract है — सिर्फ method signatures।

interface Flyable {
    void fly();
    default void land() { System.out.println("Landing..."); }
}

interface Swimmable {
    void swim();
}

// Multiple interfaces implement कर सकते हैं (Java में multiple inheritance)
class Duck implements Flyable, Swimmable {
    public void fly()  { System.out.println("Duck flying!"); }
    public void swim() { System.out.println("Duck swimming!"); }
}
Abstract ClassInterface
VariablesAny typepublic static final only
MethodsAbstract + concreteAbstract + default + static
InheritanceSingleMultiple
Constructor✅ हाँ❌ नहीं
CH-15

java.util Package — Complete Guide

java.util Java का सबसे important package है। इसमें Collections, Date/Time, Scanner, Random आदि आते हैं।

ArrayList

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add(1, "Cherry");    // index 1 पर insert
list.get(0);               // "Apple"
list.remove("Banana");    // remove by value
list.size();               // size
list.contains("Apple");  // true
list.set(0, "Avocado");   // update
Collections.sort(list);   // sort

LinkedList

import java.util.LinkedList;

LinkedList<Integer> ll = new LinkedList<>();
ll.addFirst(1);  ll.addLast(3);  ll.add(1, 2);
ll.removeFirst();  ll.removeLast();
// Stack की तरह: push(), pop(), peek()
// Queue की तरह: offer(), poll(), peek()

HashMap

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Ravi", 90);
map.put("Priya", 95);
map.get("Ravi");           // 90
map.containsKey("Priya"); // true
map.remove("Ravi");
map.size();
// Iterate
for (Map.Entry<String, Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

HashSet, TreeSet, TreeMap

import java.util.*;

HashSet<String> set = new HashSet<>();
set.add("A"); set.add("B"); set.add("A");  // duplicate नहीं
System.out.println(set.size());   // 2

TreeSet<Integer> ts = new TreeSet<>();
ts.add(5); ts.add(2); ts.add(8);
System.out.println(ts);  // [2, 5, 8] — sorted

TreeMap<String, Integer> tm = new TreeMap<>();
// sorted by key

Stack & Queue

import java.util.*;

Stack<Integer> stack = new Stack<>();
stack.push(1); stack.push(2);
stack.pop();    // 2 (LIFO)
stack.peek();   // top देखो बिना remove किए

Queue<String> q = new LinkedList<>();
q.offer("A"); q.offer("B");
q.poll();    // "A" (FIFO)
q.peek();    // front देखो

Collections class (Utility)

import java.util.*;

List<Integer> list = new ArrayList<>(Arrays.asList(5,2,8,1));

Collections.sort(list);           // [1, 2, 5, 8]
Collections.reverse(list);        // [8, 5, 2, 1]
Collections.shuffle(list);        // random order
Collections.min(list);            // minimum
Collections.max(list);            // maximum
Collections.frequency(list, 5);  // 5 कितनी बार है
Collections.fill(list, 0);       // सब 0

Random Class

import java.util.Random;

Random rand = new Random();
rand.nextInt(100);       // 0 to 99
rand.nextDouble();        // 0.0 to 1.0
rand.nextBoolean();       // true/false
rand.nextFloat();         // float
Math.random();             // 0.0 to 1.0

Date & Calendar (Legacy)

import java.util.Date;
import java.util.Calendar;

Date d = new Date();
System.out.println(d);   // current date-time

Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR);    // year
cal.get(Calendar.MONTH);   // month (0-11)
cal.get(Calendar.DATE);    // day

java.time (Modern — Java 8+)

import java.time.*;

LocalDate today = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dt = LocalDateTime.now();

LocalDate birth = LocalDate.of(2000, 5, 15);
Period age = Period.between(birth, today);
System.out.println("Age: " + age.getYears() + " years");

Optional (Java 8+)

import java.util.Optional;

Optional<String> opt = Optional.ofNullable(getName());
opt.isPresent();        // null नहीं है?
opt.get();               // value लो
opt.orElse("Default");  // null हो तो default
CH-16

java.io Package — File I/O

java.io package में file reading/writing, streams, serialization आता है।

File Class

import java.io.File;

File f = new File("test.txt");
f.createNewFile();   // file बनाओ
f.exists();           // exist करती है?
f.getName();          // "test.txt"
f.getPath();          // path
f.length();           // size in bytes
f.delete();           // delete
f.mkdir();            // directory बनाओ
f.listFiles();        // directory में files

FileWriter & FileReader

import java.io.*;

// Write
FileWriter fw = new FileWriter("data.txt");
fw.write("Hello File!\n");
fw.close();

// Read
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();

BufferedWriter (Fast Writing)

BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
bw.write("Line 1"); bw.newLine();
bw.write("Line 2"); bw.newLine();
bw.flush(); bw.close();

Serialization (Object to file)

import java.io.*;

class Person implements Serializable {  // Marker interface
    String name; int age;
}

// Serialize (save to file)
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"));
oos.writeObject(new Person());
oos.close();

// Deserialize (load from file)
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"));
Person p = (Person) ois.readObject();
ois.close();

try-with-resources (Java 7+)

// Auto-close — close() खुद होता है
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
CH-17

java.lang Package

java.lang Java का सबसे fundamental package है। यह automatically import होता है।

Math Class

Math.abs(-5)          // 5
Math.max(3, 7)        // 7
Math.min(3, 7)        // 3
Math.pow(2, 10)       // 1024.0
Math.sqrt(25)         // 5.0
Math.floor(3.9)       // 3.0
Math.ceil(3.1)        // 4.0
Math.round(3.5)       // 4
Math.log(Math.E)      // 1.0
Math.PI               // 3.14159...
Math.E                // 2.71828...

Wrapper Classes

Primitive types के object versions — Collections में use होते हैं।

PrimitiveWrapperMethods
intIntegerparseInt(), valueOf(), MAX_VALUE
doubleDoubleparseDouble(), isNaN()
charCharacterisLetter(), isDigit(), toUpperCase()
booleanBooleanparseBoolean()
// Autoboxing (int → Integer)
Integer n = 42;

// Unboxing (Integer → int)
int x = n;

Integer.MAX_VALUE    // 2147483647
Integer.MIN_VALUE    // -2147483648
Integer.toBinaryString(10)  // "1010"
Integer.toHexString(255)    // "ff"

Character.isLetter('A')     // true
Character.isDigit('5')      // true
Character.toLowerCase('Z') // 'z'

Object Class — सबकी Parent

Java में हर class Object class से inherit करती है।

class MyClass {
    @Override
    public String toString() {
        return "MyClass object";
    }

    @Override
    public boolean equals(Object o) {
        return this == o;
    }

    @Override
    public int hashCode() {
        return System.identityHashCode(this);
    }
}
// Object methods: toString(), equals(), hashCode(),
// getClass(), clone(), finalize(), wait(), notify()

System Class

System.out.println();          // standard output
System.err.println("Error!");  // error stream
System.exit(0);               // program बंद (0=success)
System.currentTimeMillis();   // ms timestamp
System.nanoTime();            // nanoseconds
System.arraycopy(src,0,dest,0,5); // array copy
System.gc();                   // garbage collector suggest
System.getenv("PATH");        // environment variable
CH-18

Exception Handling

Exception क्या है?

Runtime में होने वाली errors जो program crash कर देती हैं। Exception handling से हम इन्हें gracefully handle करते हैं।

try {
    int result = 10 / 0;   // ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
    System.out.println("General error");
} finally {
    System.out.println("Always runs!");  // हमेशा चलेगा
}

Common Exceptions

Exceptionकब आता है
ArithmeticException0 से divide करने पर
NullPointerExceptionnull object पर method call
ArrayIndexOutOfBoundsExceptionArray की range से बाहर
NumberFormatExceptionString को invalid number parse
ClassCastExceptionInvalid type cast
StackOverflowErrorInfinite recursion
OutOfMemoryErrorHeap full
FileNotFoundExceptionFile नहीं मिली

Custom Exception

class AgeException extends RuntimeException {
    AgeException(String msg) { super(msg); }
}

void setAge(int age) {
    if (age < 0) throw new AgeException("Age cannot be negative!");
    this.age = age;
}

throws keyword

void readFile(String path) throws IOException {
    FileReader fr = new FileReader(path);
    // Checked exception को propagate करना
}
CH-19

Collections Framework + Generics + Lambda

Generics (Type Safety)

// Generic Method
static <T> void print(T item) {
    System.out.println(item);
}

// Generic Class
class Pair<A, B> {
    A first; B second;
    Pair(A a, B b) { first = a; second = b; }
}

Pair<String, Integer> p = new Pair<>("Age", 25);

Lambda Expression (Java 8+)

import java.util.*;

List<String> names = Arrays.asList("Ravi", "Priya", "Amit");

// Lambda sort
names.sort((a, b) -> a.compareTo(b));

// forEach with lambda
names.forEach(name -> System.out.println(name));
// Method reference (short form)
names.forEach(System.out::println);

Stream API (Java 8+)

import java.util.stream.*;

List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8);

// Filter even, square, collect
List<Integer> result = nums.stream()
    .filter(n -> n % 2 == 0)  // [2,4,6,8]
    .map(n -> n * n)            // [4,16,36,64]
    .collect(Collectors.toList());

// Sum
int sum = nums.stream().mapToInt(Integer::intValue).sum();

// Average
double avg = nums.stream().mapToInt(Integer::intValue).average().getAsDouble();

// Count
long count = nums.stream().filter(n -> n > 5).count();

Comparable & Comparator

class Student implements Comparable<Student> {
    String name; int marks;
    @Override
    public int compareTo(Student other) {
        return this.marks - other.marks;  // marks से sort
    }
}

// Comparator — externally sort
Comparator<Student> byName = (Student a, Student b) -> a.name.compareTo(b.name);
list.sort(byName);
CH-20

.class Files & JVM — Deep Dive

.class File क्या होती है?

जब javac MyProgram.java चलाते हैं, तो MyProgram.class बनती है। यह bytecode है — binary format में।

.class File Structure

// .class file का format (Java Class File Format):
magic number:     0xCAFEBABE  ← हर .class file ऐसे शुरू होती है!
minor_version:    0
major_version:    65          ← Java 21 = 65, Java 8 = 52
constant_pool:    ...         ← strings, numbers, references
access_flags:     0x0021      ← public, super
this_class:       #3
super_class:      #4
interfaces:       ...
fields:           ...
methods:          ...
attributes:       ...

JVM Memory Areas (विस्तार से)

Areaक्या store होता हैPer?
Method AreaClass structure, static variables, method codeJVM
HeapObjects, instance variables, arraysJVM (GC यहाँ काम करता है)
StackMethod calls, local variables, framesThread
PC RegisterCurrent instruction pointerThread
Native StackNative (C/C++) method callsThread

Class Loading Process

// 3 Steps:
1. Loading    → .class file disk/network से load करना
2. Linking    →
   a. Verification  (bytecode valid है?)
   b. Preparation   (static variables initialize)
   c. Resolution    (symbolic references resolve)
3. Initialization → static initializers, static blocks run

Garbage Collection

// Heap के generations:
Young Generation:
  - Eden Space     (नए objects यहाँ)
  - Survivor S0/S1 (minor GC के बाद)

Old Generation:
  - Long-lived objects यहाँ move होते हैं

Metaspace:
  - Class metadata (Java 8 से PermGen हटा, Metaspace आया)

// GC Algorithms:
Serial GC      → Single-threaded, small apps
Parallel GC    → Multi-threaded, throughput
G1 GC          → Default (Java 9+), balanced
ZGC            → Ultra-low latency (Java 15+)

javap — Bytecode Decompiler

// .class file देखना:
$ javap Hello.class        // high-level view
$ javap -c Hello.class     // bytecode instructions
$ javap -verbose Hello.class // complete details

// Output example:
public class Hello {
  public Hello();
  public static void main(java.lang.String[]);
}

Important Java Tools (JDK में)

Toolकाम
javac.java को .class में compile करता है
javaProgram execute करता है
javapBytecode decompile करता है
jar.jar archive बनाता है
javadocDocumentation generate करता है
jdbJava Debugger
jpsRunning JVM processes
jstackThread dump
jmapHeap dump
jconsoleGUI monitoring tool
💡 Pro Tip: Java के नए features सीखते रहो — Java 8 (Lambda/Streams), Java 17 (Records, Sealed Classes), Java 21 (Virtual Threads) आज industry में बहुत use होते हैं।