सामग्री पर जाएँ

लेसन 195 · Practice and Review

Java चीट शीट (Cheat Sheet)

एक पन्ने की Java 25 चीट शीट: सिंटैक्स, टाइप, स्ट्रिंग, कंट्रोल फ़्लो, OOP, रिकॉर्ड, एक्सेप्शन, कलेक्शन, लैम्ब्डा, स्ट्रीम, तारीख़ें, फ़ाइलें और थ्रेड।

यह पन्ना पूरे Java कोर्स को एक स्क्रॉल होने वाले संदर्भ में समेटता है: वह सिंटैक्स, टाइप और API जिन्हें आप रोज़ इस्तेमाल करते हैं, छोटे स्निपेट में जिन्हें आप सेकंडों में स्कैन कर सकते हैं। इसे अभ्यास के सवालों पर काम करते समय, अपने प्रोग्राम लिखते समय, या इंटरव्यू की पिछली रात खुला रखें।

हर सेक्शन उस पाठ से जुड़ा है जो विषय को ठीक से समझाता है, उन तर्कों और जालों के साथ जिनके लिए चीट शीट में जगह नहीं होती। जो नियम लोगों को सबसे ज़्यादा चौंकाते हैं, उनके साथ लाइव एडिटर हैं, ताकि आप उन्हें चलाकर खुद व्यवहार देख सकें। यहाँ सब कुछ आधुनिक Java 25 है; हाल के वर्ज़नों में जोड़ी गई सुविधाओं के साथ उस वर्ज़न का नाम दिया है जिसमें वे आईं।

प्रोग्राम की संरचना

प्रोग्राम लिखने के दो तरीके

Java
// Compact source file (Java 25): no class needed
void main() {
    IO.println("Hello, Java!");
}
Java
// Classic form: what most existing code and frameworks use
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

कॉम्पैक्ट फ़ाइलें java.base को अपने आप इम्पोर्ट करती हैं (List, Map, Path, ...)। क्लासिक फ़ाइलों में java.lang के बाहर की किसी भी चीज़ के लिए इम्पोर्ट चाहिए। देखें शुरुआत करना, सिंटैक्स और main मेथड।

कंपाइल और रन

Terminal
java Main.java               # run a single source file directly (no javac step)
javac Main.java              # compile to Main.class (bytecode)
java Main                    # run the compiled class on the JVM
java -version                # which JDK is on the PATH
javac -d out src/app/*.java  # compile into an output folder

देखें Java कैसे काम करती है और बिल्ड टूल।

कमेंट और नामकरण

Java
// line comment
/* block comment */
/** Javadoc: @param, @return, @throws */
/// Markdown doc comment (Java 23+)

class OrderService {}             // classes, records, enums: PascalCase
int itemCount;                    // variables and methods: camelCase
static final int MAX_RETRIES = 3; // constants: UPPER_SNAKE_CASE
package com.example.shop;         // packages: lowercase, reversed domain

देखें कमेंट और Javadoc और कीवर्ड और आइडेंटिफ़ायर।

आउटपुट और इनपुट

प्रिंट करना

Java
System.out.println("line");      // print + newline
System.out.print("no newline");
IO.println("Java 25 shortcut");  // also IO.print(...)
System.err.println("error stream");
System.out.printf("%s is %d%n", "Ada", 36);   // formatted (IO has no printf)
String s = "%.2f".formatted(3.14159);           // "3.14"
String t = String.format("%05d", 42);           // "00042"
स्पेसिफ़ायर अर्थ उदाहरण → आउटपुट
%d इंटीजर %d, 42 → 42
%,d हज़ारों के समूह %,d, 1234567 → 1,234,567
%05d शून्य से भरी चौड़ाई 5 42 → 00042
%.2f 2 दशमलव (राउंड करता है) 3.14159 → 3.14
%8.2f चौड़ाई 8, दाएँ संरेखित 3.5 → 3.50
%s / %-10s स्ट्रिंग / 10 में बाएँ संरेखित "ab" → ab
%x / %X हेक्साडेसिमल 255 → ff / FF
%e वैज्ञानिक संकेतन 12345.0 → 1.234500e+04
%b %c %% %n बूलियन, char, शाब्दिक %, नई लाइन

देखें आउटपुट प्रिंट करना और स्ट्रिंग फ़ॉर्मैटिंग।

इनपुट पढ़ना

Java
Scanner in = new Scanner(System.in);
String line = in.nextLine();     // whole line
int n = in.nextInt();            // one token; leaves the newline behind!
while (in.hasNextInt()) { ... }  // read until input runs out

String name = IO.readln("Name: ");          // Java 25: prompt + read a line
int age = Integer.parseInt(IO.readln());

var reader = new BufferedReader(new InputStreamReader(System.in));
String first = reader.readLine();           // null at end of input

क्लासिक जाल: nextInt() के बाद nextLine() एक खाली स्ट्रिंग लौटाता है, क्योंकि nextInt() लाइन ब्रेक से पहले रुक जाता है। इसे चलाकर देखें, और फिर समाधान:

Java nextInt के बाद nextLine का जाल

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

आम तौर पर सबसे सरल समाधान: पूरी लाइनें पढ़ें और उन्हें Integer.parseInt(line.trim()) से पार्स करें। देखें यूज़र इनपुट पढ़ना।

वेरिएबल और टाइप

प्रिमिटिव टाइप

टाइप आकार रेंज / वैल्यू डिफ़ॉल्ट (फ़ील्ड) लिटरल
byte 8 बिट -128 से 127 0 (byte) 10
short 16 बिट -32,768 से 32,767 0 (short) 10
int 32 बिट लगभग ±2.1 अरब 0 42, 1_000_000, 0xFF, 0b1010, 017
long 64 बिट लगभग ±9.2 × 10¹⁸ 0L 42L
float 32 बिट लगभग 7 सार्थक अंक 0.0f 3.14f
double 64 बिट लगभग 15–16 सार्थक अंक 0.0 3.14, 1e-3
char 16 बिट एक UTF-16 कोड यूनिट '\u0000' 'A', '\n'
boolean – true, false false true

बाकी सब कुछ रेफ़रेंस टाइप है (String, ऐरे, ऑब्जेक्ट), जिनके फ़ील्ड का डिफ़ॉल्ट null है। लोकल वेरिएबल का कोई डिफ़ॉल्ट नहीं होता: इस्तेमाल से पहले उन्हें असाइन करना ज़रूरी है। देखें प्रिमिटिव डेटा टाइप और वेरिएबल।

डिक्लेरेशन, var और final

Java
int count = 0;
double price = 9.99, tax = 0.2;
var names = new ArrayList<String>();   // type inferred: ArrayList<String>
final int limit = 10;                  // can't be reassigned
static final double VAT = 0.21;        // a constant (inside a class)

var सिर्फ़ इनिशियलाइज़र वाले लोकल वेरिएबल के लिए काम करता है (फ़ील्ड, पैरामीटर या var x = null; के लिए नहीं)। देखें var और कॉन्स्टेंट और final।

कन्वर्ज़न

Java
long big = 42;                    // widening: automatic
int whole = (int) 3.99;           // narrowing: 3 (truncates toward zero)
byte wrapped = (byte) 200;        // -56 (keeps the low 8 bits)
int n = Integer.parseInt("123");  // NumberFormatException on "12a"
double d = Double.parseDouble("2.5");
String s = String.valueOf(42);    // or "" + 42, or Integer.toString(42)
int code = 'A';                   // 65
char next = (char) ('A' + 1);     // 'B'

देखें टाइप कास्टिंग और कन्वर्ज़न और रैपर क्लास।

ऑपरेटर

Java
7 / 2          // 3      int division truncates
-7 / 2         // -3     toward zero
7 % 3          // 1
-7 % 3         // -1     sign follows the left operand
Math.floorMod(-7, 3)   // 2
7 / 2.0        // 3.5    one double makes it double division
1 + 2 + "3"    // "33"   left to right: 3, then "33"
"1" + 2 + 3    // "123"

x += 5;  x -= 1;  x *= 2;  x /= 3;  x %= 4;
i++  // use, then add 1      ++i  // add 1, then use

a == b, a != b, a < b, a >= b
a && b, a || b, !a     // short-circuit: b may not be evaluated
a & b, a | b, a ^ b    // on booleans: always evaluate both
int max = a > b ? a : b;           // ternary
obj instanceof String str          // type test + pattern variable

5 & 3 /* 1 */, 5 | 3 /* 7 */, 5 ^ 3 /* 6 */, ~5 /* -6 */
1 << 4 /* 16 */, -16 >> 2 /* -4 */, -16 >>> 28 /* 15 */

प्राथमिकता ऊँची से नीची: पोस्टफ़िक्स x++ → यूनरी ++x -x ! ~ (cast) → * / % → + - → शिफ़्ट → < > <= >= instanceof → == != → & → ^ → | → && → || → ?: → असाइनमेंट। संदेह हो तो कोष्ठक (parentheses) लगाएँ। देखें अरिथमेटिक ऑपरेटर, तुलना और लॉजिकल ऑपरेटर, बिटवाइज़ और शिफ़्ट ऑपरेटर और ऑपरेटर प्राथमिकता।

संख्याओं की हैरानियाँ

Java एक ही रन में संख्याओं की हैरानियाँ

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

int और long का ओवरफ़्लो बिना चेतावनी के घूम जाता है; Math.addExact, multiplyExact और उनके साथी इसके बजाय एक्सेप्शन फेंकते हैं। पैसों के लिए BigDecimal इस्तेमाल करें। देखें संख्याओं के साथ काम, असाइनमेंट ऑपरेटर और BigInteger और BigDecimal।

Math क्लास

Java
Math.abs(-5)  Math.max(a, b)  Math.min(a, b)
Math.pow(2, 10)        // 1024.0 (a double)
Math.sqrt(16)  Math.cbrt(27)  Math.hypot(3, 4)   // 4.0 3.0 5.0
Math.round(2.4)        // 2 (a long for double arguments)
Math.floor(2.7)  Math.ceil(2.1)                  // 2.0 3.0
Math.floorDiv(-7, 2)   // -4
Math.clamp(150, 0, 100)                          // 100 (Java 21)
Math.random()          // 0.0 <= x < 1.0
RandomGenerator.getDefault().nextInt(1, 7)       // 1..6 (dice)

देखें Math क्लास और रैंडम नंबर।

स्ट्रिंग

रोज़मर्रा के String मेथड

Java
String s = "Hello, World";
s.length()                 // 12
s.charAt(0)                // 'H'
s.substring(7)             // "World"
s.substring(0, 5)          // "Hello" (end index excluded)
s.indexOf("o")             // 4      lastIndexOf("o") → 8, -1 if missing
s.contains("World")        // true
s.startsWith("He")  s.endsWith("!")
s.toUpperCase()  s.toLowerCase()
"  hi  ".strip()           // "hi"   (Unicode-aware; trim() is ASCII-only)
"".isEmpty()  "  ".isBlank()        // true true
s.replace('l', 'L')        // "HeLLo, WorLd"
"a1b22".replaceAll("\\d+", "#")      // "a#b#" (regex)
"a,b,,c,".split(",")       // [a, b, , c] (trailing empties dropped)
String.join("-", "a", "b") // "a-b"
"ab".repeat(3)             // "ababab"
"line1\nline2".lines()     // Stream<String>
s.toCharArray()            // char[]
s.chars()                  // IntStream of chars
s.equals(other)  s.equalsIgnoreCase(other)
s.compareTo("Help")        // negative: "Hello" sorts first

स्ट्रिंग इम्म्यूटेबल (immutable) हैं: हर मेथड एक नई स्ट्रिंग लौटाता है, इसलिए s = s.trim(); लिखें। देखें स्ट्रिंग, String मेथड और स्ट्रिंग की तुलना और कन्वर्ज़न।

== बनाम equals

Java स्ट्रिंग और रैपर की तुलना

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

== रेफ़रेंस की तुलना करता है; equals सामग्री की। स्ट्रिंग या बॉक्स्ड संख्याओं पर == से मिला कोई भी "true" किस्मत है (पूलिंग या कैशिंग), भरोसा करने लायक कुछ नहीं।

StringBuilder और टेक्स्ट ब्लॉक

Java
var sb = new StringBuilder();
sb.append("Hi").append(' ').append(42);   // "Hi 42"
sb.insert(0, ">> ");  sb.reverse();  sb.setLength(0);
String csv = String.join(",", list);      // or Collectors.joining(",")

String json = """
    {
      "name": "Ada",
      "age": 36
    }
    """;   // indentation relative to the closing """ is removed

लूप में स्ट्रिंग बनाते समय StringBuilder इस्तेमाल करें। देखें StringBuilder, StringBuffer, StringJoiner और StringTokenizer और टेक्स्ट ब्लॉक।

कंट्रोल फ़्लो

if और switch

Java
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else {
    grade = 'C';
}

String type = switch (day) {              // switch expression
    case SATURDAY, SUNDAY -> "weekend";
    case MONDAY -> {
        log("start");
        yield "weekday";                  // yield returns from a block
    }
    default -> "weekday";
};

switch (command) {                        // classic statement: needs break
    case "start":
        start();
        break;
    case "stop":
    case "halt":                          // fall-through groups labels
        stop();
        break;
    default:
        help();
}

Switch int जैसे टाइप, char, String, enum और (पैटर्न के साथ) किसी भी टाइप पर काम करता है। देखें if, else if और else और switch।

लूप

Java
for (int i = 0; i < 10; i++) { ... }
for (String name : names) { ... }          // arrays and any Iterable
while (condition) { ... }
do { ... } while (condition);              // body runs at least once

outer:
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        if (grid[r][c] == target) break outer;   // leaves both loops
        if (grid[r][c] < 0) continue;            // next c
    }
}

देखें while और do-while, for लूप और break, continue और लेबल।

ऐरे

Java
int[] nums = new int[5];                   // [0, 0, 0, 0, 0]
int[] primes = {2, 3, 5, 7};
String[] names = new String[3];            // [null, null, null]
nums.length                                // a field, not a method
int[][] grid = new int[3][4];              // 3 rows, 4 columns
int[][] jagged = {{1}, {2, 3}, {4, 5, 6}};

Arrays.toString(primes)                    // "[2, 3, 5, 7]"
Arrays.deepToString(grid)                  // nested arrays
Arrays.sort(nums);                         // ascending
Arrays.sort(words, Comparator.reverseOrder());   // objects only
Arrays.binarySearch(primes, 5)             // 2 (array must be sorted)
Arrays.fill(nums, -1);
int[] copy = Arrays.copyOf(nums, 10);      // pads with 0
int[] part = Arrays.copyOfRange(nums, 1, 3);
Arrays.equals(a, b)                        // contents; a.equals(b) is identity
List<String> view = Arrays.asList(names);  // fixed size: add() throws
int sum = Arrays.stream(primes).sum();     // 17

इंडेक्स 0 से length - 1 तक चलते हैं; इसके बाहर कुछ भी ArrayIndexOutOfBoundsException फेंकता है। देखें ऐरे, ऐरे पर लूप, मल्टीडाइमेंशनल ऐरे और Arrays क्लास।

मेथड

Java
static int add(int a, int b) {             // static: call as add(1, 2)
    return a + b;
}
static double add(double a, double b) { ... }  // overload: different parameters
static int sum(int... values) { ... }      // varargs: sum(), sum(1, 2, 3)
record MinMax(int min, int max) {}         // return several values
static MinMax range(int[] a) { ... }

long factorial(int n) {                    // recursion needs a base case
    return n <= 1 ? 1 : n * factorial(n - 1);
}

Java हमेशा पास-बाय-वैल्यू (pass-by-value) है: मेथड को प्रिमिटिव की कॉपी मिलती है, या रेफ़रेंस की कॉपी (इसलिए वह ऑब्जेक्ट बदल सकता है, पर यह नहीं कि कॉलर का वेरिएबल किस ऑब्जेक्ट की ओर इशारा करे)। देखें मेथड, पैरामीटर और रिटर्न वैल्यू, मेथड ओवरलोडिंग, रिकर्शन, Varargs और वेरिएबल स्कोप।

क्लास और ऑब्जेक्ट

एक पूरी क्लास

Java
public class Account {
    private static int created = 0;        // shared by all accounts
    private final String owner;            // set once
    private double balance;

    public Account(String owner) {
        this(owner, 0);                    // call another constructor
    }

    public Account(String owner, double balance) {
        if (balance < 0) throw new IllegalArgumentException("negative balance");
        this.owner = owner;                // this. disambiguates the field
        this.balance = balance;
        created++;
    }

    public double getBalance() { return balance; }
    public void deposit(double amount) { balance += amount; }
    public static int created() { return created; }

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

Account acc = new Account("Ada", 100);
acc.deposit(50);

देखें क्लास और ऑब्जेक्ट, कंस्ट्रक्टर, this कीवर्ड, एनकैप्सुलेशन और स्टैटिक मेंबर।

एक्सेस मॉडिफ़ायर

मॉडिफ़ायर वही क्लास वही पैकेज सबक्लास (दूसरा पैकेज) हर जगह
public हाँ हाँ हाँ हाँ
protected हाँ हाँ हाँ नहीं
(कोई नहीं) package-private हाँ हाँ नहीं नहीं
private हाँ नहीं नहीं नहीं

देखें एक्सेस मॉडिफ़ायर।

इनहेरिटेंस, एब्स्ट्रैक्ट क्लास और इंटरफ़ेस

Java
abstract class Shape {
    abstract double area();                       // no body: subclasses must implement
    String describe() { return "Area " + area(); }
}

class Circle extends Shape {                      // one superclass only
    private final double r;
    Circle(double r) { super(); this.r = r; }     // super(...) calls the parent constructor
    @Override double area() { return Math.PI * r * r; }
}

interface Drawable {
    void draw();                                  // implicitly public abstract
    default void drawTwice() { draw(); draw(); }  // default method
    static Drawable noop() { return () -> {}; }
}

class Square extends Shape implements Drawable, Comparable<Square> { ... }

Shape s = new Circle(2);                          // upcast: always allowed
if (s instanceof Circle c) { ... }                // safe downcast with a pattern

देखें इनहेरिटेंस, super, पॉलिमॉर्फ़िज़्म, एब्स्ट्रैक्ट क्लास, इंटरफ़ेस और कम्पोज़िशन।

रिकॉर्ड, enum और नेस्टेड क्लास

Java
record Point(int x, int y) {                      // final fields, accessors x() and y(),
    Point {                                       // equals/hashCode/toString for free
        if (x < 0) throw new IllegalArgumentException("x < 0");  // compact constructor
    }
    Point withX(int nx) { return new Point(nx, y); }
}

enum Planet {
    MERCURY(3.303e23), EARTH(5.976e24);
    private final double mass;
    Planet(double mass) { this.mass = mass; }
    double mass() { return mass; }
}
Planet.values()  Planet.valueOf("EARTH")  Planet.EARTH.ordinal()  // 1

class Outer {
    static class Nested {}        // no link to an Outer instance
    class Inner {}                // needs one: outer.new Inner()
}
Runnable r = new Runnable() {     // anonymous class
    public void run() { IO.println("run"); }
};

देखें रिकॉर्ड, Enum, नेस्टेड क्लास और इम्म्यूटेबल क्लास।

सील्ड टाइप और पैटर्न मैचिंग

Java Sealed इंटरफ़ेस, रिकॉर्ड और पैटर्न switch

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

क्योंकि Shape सील्ड (sealed) है, कंपाइलर हर सबटाइप जानता है, इसलिए जो switch उन सभी को कवर करता है उसे default नहीं चाहिए, और नया सबटाइप जोड़ने पर हर अधूरा switch कंपाइल एरर बन जाता है। देखें सील्ड क्लास और पैटर्न मैचिंग।

equals, hashCode और toString

Java
@Override
public boolean equals(Object o) {
    return o instanceof Isbn other && code.equals(other.code);
}
@Override
public int hashCode() { return Objects.hash(code); }   // equal objects → equal hashes
@Override
public String toString() { return "Isbn[" + code + "]"; }

Objects.equals(a, b)                     // null-safe
Objects.requireNonNull(name, "name")     // fail fast

equals और hashCode को साथ-साथ ओवरराइड करें, वरना हैश-आधारित कलेक्शन टूट जाते हैं। देखें Object क्लास और ऑब्जेक्ट की कॉपी बनाना।

एक्सेप्शन

Java
try {
    int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
    IO.println("Not a number: " + e.getMessage());
} catch (IllegalStateException | ArithmeticException e) {   // multi-catch
    throw new AppException("calculation failed", e);           // keep the cause
} finally {
    IO.println("always runs");
}

try (var reader = Files.newBufferedReader(path)) {   // closed automatically,
    return reader.readLine();                        // in reverse order
}

void load(Path p) throws IOException { ... }         // checked: declare or catch

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String message) { super(message); }
}
प्रकार किसे एक्सटेंड करता है क्या पकड़ना या घोषित करना ज़रूरी है? उदाहरण
Checked Exception हाँ IOException, SQLException, InterruptedException
Unchecked RuntimeException नहीं NullPointerException, IllegalArgumentException, IndexOutOfBoundsException
Error Error नहीं (पकड़ें नहीं) OutOfMemoryError, StackOverflowError

देखें एक्सेप्शन, एक्सेप्शन फेंकना, कस्टम एक्सेप्शन, try-with-resources, सर्वोत्तम अभ्यास और डीबगिंग।

कलेक्शन

कौन-सा चुनें?

ज़रूरत इस्तेमाल करें टिप्पणी
क्रमबद्ध लिस्ट, इंडेक्स से एक्सेस ArrayList डिफ़ॉल्ट लिस्ट
अनूठे आइटम, तेज़ खोज HashSet कोई क्रम नहीं
अनूठे आइटम, इन्सर्शन क्रम में LinkedHashSet
अनूठे आइटम, सॉर्टेड TreeSet first, floor, ceiling
की (key) → वैल्यू HashMap एक null की मान्य
की → वैल्यू, इन्सर्शन/एक्सेस क्रम LinkedHashMap LRU कैश
की → वैल्यू, सॉर्टेड की TreeMap headMap, floorKey
स्टैक या क्यू ArrayDeque Stack/LinkedList नहीं
हमेशा सबसे छोटा/बड़ा निकालना PriorityQueue बाइनरी हीप
थ्रेडों के बीच साझा ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
ऑपरेशन ArrayList LinkedList HashMap/HashSet TreeMap/TreeSet
इंडेक्स / की से get O(1) O(n) O(1) औसत O(log n)
अंत में add / put O(1) amortized O(1) O(1) औसत O(log n)
बीच में insert/remove O(n) खोजने में O(n), अनलिंक में O(1) – –
contains O(n) O(n) O(1) औसत O(log n)

देखें कलेक्शन फ़्रेमवर्क और सही कलेक्शन चुनना।

व्यवहार में लिस्ट, सेट और मैप

Java
List<String> list = new ArrayList<>();
list.add("b");  list.add(0, "a");  list.get(0);  list.set(0, "z");
list.remove("z");  list.remove(0);  list.size();  list.contains("b");
list.removeIf(s -> s.isBlank());
list.sort(Comparator.naturalOrder());
list.getFirst();  list.getLast();  list.reversed();     // Java 21

Set<Integer> set = new HashSet<>(List.of(3, 1, 2));
set.add(1);                     // false: already there
set.retainAll(other);           // intersection (addAll = union, removeAll = difference)

Map<String, Integer> map = new HashMap<>();
map.put("apples", 3);
map.get("pears")                       // null when missing
map.getOrDefault("pears", 0)           // 0
map.putIfAbsent("pears", 1);
map.merge(word, 1, Integer::sum);      // counting in one line
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);   // grouping
for (Map.Entry<String, Integer> e : map.entrySet()) { e.getKey(); e.getValue(); }
map.forEach((k, v) -> IO.println(k + "=" + v));

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);  stack.pop();  stack.peek();
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1);  queue.poll();  queue.peek();         // null when empty
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));

List.of(1, 2, 3)  Set.of("a")  Map.of("k", 1)        // immutable, no nulls
List.copyOf(list)                                     // immutable copy
Collections.unmodifiableList(list)                    // read-only view
Collections.frequency(list, "b")  Collections.max(list)  Collections.shuffle(list)

for-each से लूप करते समय कलेक्शन बदलने पर ConcurrentModificationException आता है; removeIf या Iterator का remove() इस्तेमाल करें। देखें ArrayList, HashMap, HashSet, TreeMap और TreeSet, क्यू और डेक, इटरेटर और इम्म्यूटेबल कलेक्शन।

सॉर्टिंग

Java
record Person(String name, int age) {}
people.sort(Comparator.comparing(Person::name));
people.sort(Comparator.comparingInt(Person::age).reversed());
people.sort(Comparator.comparing(Person::age).thenComparing(Person::name));
names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));

class Version implements Comparable<Version> {
    public int compareTo(Version o) { return Integer.compare(major, o.major); }
}

कॉम्पैरेटर में कभी return a - b; न लिखें: बड़ी वैल्यू के लिए यह ओवरफ़्लो होता है। Integer.compare इस्तेमाल करें। देखें Comparable और Comparator।

जेनेरिक और फ़ंक्शनल प्रोग्रामिंग

जेनेरिक (Generics)

Java
class Box<T> {
    private final T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
}
Box<String> box = new Box<>("hi");                     // diamond <>

static <T extends Comparable<T>> T max(List<T> items) { ... }   // bounded type
double sum(List<? extends Number> nums) { ... }        // read from a producer
void fill(List<? super Integer> out) { ... }           // write to a consumer

PECS: Producer extends, Consumer super। जेनेरिक रन टाइम पर मिटा दिए जाते हैं (erased): new T() नहीं, List<int> नहीं (List<Integer> इस्तेमाल करें), instanceof List<String> नहीं। देखें जेनेरिक, बाउंडेड टाइप और वाइल्डकार्ड और टाइप इरेज़र।

लैम्ब्डा, फ़ंक्शनल इंटरफ़ेस और मेथड रेफ़रेंस

इंटरफ़ेस मेथड आकार उदाहरण
Function<T, R> apply T → R s -> s.length()
BiFunction<T, U, R> apply (T, U) → R (a, b) -> a + b
Predicate<T> test T → boolean n -> n > 0
Consumer<T> accept T → void IO::println
Supplier<T> get () → T ArrayList::new
UnaryOperator<T> apply T → T String::trim
BinaryOperator<T> apply (T, T) → T Integer::sum
Runnable / Callable<V> run / call () → void / V थ्रेड के टास्क
Java
Function<Integer, Integer> twice = x -> x * 2;
Function<Integer, Integer> plusOne = x -> x + 1;
twice.andThen(plusOne).apply(5)     // 11
twice.compose(plusOne).apply(5)     // 12
Predicate<String> empty = String::isEmpty;
empty.negate().and(s -> s.length() < 5)

String::toUpperCase     // instance method of an arbitrary object: s -> s.toUpperCase()
System.out::println     // instance method of a particular object
Integer::parseInt       // static method
ArrayList::new          // constructor

लैम्ब्डा लोकल वेरिएबल तभी इस्तेमाल कर सकते हैं जब वे प्रभावी रूप से final (effectively final) हों। देखें लैम्ब्डा, फ़ंक्शनल इंटरफ़ेस, मेथड रेफ़रेंस और फ़ंक्शनल प्रोग्रामिंग।

स्ट्रीम

Java
List<String> result = names.stream()
    .filter(n -> n.length() > 3)          // intermediate: lazy
    .map(String::toUpperCase)
    .sorted()
    .distinct()
    .limit(10)
    .toList();                            // terminal: runs the pipeline (Java 16)

IntStream.range(0, 5)                     // 0..4  (rangeClosed(1, 5) → 1..5)
Stream.of("a", "b")  Arrays.stream(array)  list.stream()
stream.count()  .anyMatch(p)  .allMatch(p)  .noneMatch(p)
stream.findFirst()                        // Optional
stream.reduce(0, Integer::sum)
ints.mapToInt(Integer::intValue).sum()    // also average(), max(), summaryStatistics()
lists.stream().flatMap(List::stream)      // flatten
Java
Collectors.joining(", ", "[", "]")
Collectors.groupingBy(Person::city)                         // Map<City, List<Person>>
Collectors.groupingBy(Person::city, Collectors.counting())  // Map<City, Long>
Collectors.partitioningBy(p -> p.age() >= 18)               // Map<Boolean, List<...>>
Collectors.toMap(Person::name, Person::age, (a, b) -> a)    // merge on duplicate keys
Collectors.averagingInt(Person::age)
Java कलेक्टर के साथ स्ट्रीम पाइपलाइन

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

स्ट्रीम सिर्फ़ एक बार इस्तेमाल हो सकती है, और टर्मिनल ऑपरेशन चलने तक वह कुछ नहीं करती। देखें स्ट्रीम, स्ट्रीम के नतीजे इकट्ठा करना और एडवांस्ड स्ट्रीम।

Optional

Java
Optional<User> found = repo.findById(id);
found.map(User::email).orElse("none");
found.orElseGet(() -> loadDefault());     // lazy fallback
found.orElseThrow();                      // NoSuchElementException if empty
found.ifPresentOrElse(u -> greet(u), () -> IO.println("not found"));
Optional.ofNullable(maybeNull)            // Optional.of(null) throws

Optional को "शायद कोई नतीजा न हो" वाले रिटर्न टाइप के रूप में इस्तेमाल करें, फ़ील्ड या पैरामीटर के लिए नहीं। देखें Optional।

डेटा के साथ काम

तारीख़ें और समय (java.time)

Java
LocalDate today = LocalDate.now();
LocalDate due = LocalDate.of(2026, 3, 15).plusWeeks(2);
LocalDateTime meeting = LocalDateTime.of(2026, 5, 1, 9, 30);
ZonedDateTime tokyo = meeting.atZone(ZoneId.of("Asia/Tokyo"));
Instant now = Instant.now();                         // a point on the UTC timeline
Duration d = Duration.ofMinutes(90);                 // time-based: 1h30m
Period p = Period.between(birthday, today);          // date-based: years/months/days
long days = ChronoUnit.DAYS.between(start, end);
var fmt = DateTimeFormatter.ofPattern("dd.MM.yyyy");
fmt.format(today);  LocalDate.parse("01.02.2026", fmt);
today.with(TemporalAdjusters.lastDayOfMonth());
today.getDayOfWeek()                                 // e.g. MONDAY

सभी java.time टाइप इम्म्यूटेबल हैं: plusDays नई वैल्यू लौटाता है। पुराने Date और Calendar से बचें। देखें तारीख़ें और समय।

रेगेक्स, बड़ी संख्याएँ, UUID

Java
Pattern p = Pattern.compile("(?<year>\\d{4})-(\\d{2})");   // compile once, reuse
Matcher m = p.matcher("Due 2026-03");
if (m.find()) { m.group("year"); m.group(2); }              // "2026", "03"
"2026-03".matches("\\d{4}-\\d{2}")                          // whole string must match

new BigDecimal("0.10").add(new BigDecimal("0.20"))          // 0.30 exactly
amount.setScale(2, RoundingMode.HALF_EVEN)
a.compareTo(b) == 0                    // equals() also compares the scale: 2.0 ≠ 2.00
BigInteger.TWO.pow(100)

UUID.randomUUID()
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
Base64.getEncoder().encodeToString(bytes)

देखें रेगुलर एक्सप्रेशन, BigInteger और BigDecimal, UUID, हैशिंग और Base64 और इंटरनेशनलाइज़ेशन।

फ़ाइलें

Java
Path path = Path.of("data", "notes.txt");
Files.createDirectories(path.getParent());
Files.writeString(path, "first line\n");
Files.writeString(path, "more\n", StandardOpenOption.APPEND);
String text = Files.readString(path);
List<String> lines = Files.readAllLines(path);
try (Stream<String> stream = Files.lines(path)) { ... }   // large files: close it!
Files.exists(path)  Files.size(path)  Files.delete(path)
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
try (Stream<Path> all = Files.walk(Path.of("."))) { ... }

Files API डिफ़ॉल्ट रूप से UTF-8 इस्तेमाल करते हैं। देखें फ़ाइलें पढ़ना और लिखना, बाइट और कैरेक्टर स्ट्रीम, डायरेक्टरी के साथ काम, सीरियलाइज़ेशन, कैरेक्टर सेट और प्रॉपर्टी फ़ाइलें।

कन्करेंसी

Java
Thread t = new Thread(() -> work());
t.start();                    // run() would execute on the current thread
t.join();                     // wait for it to finish

synchronized (lock) { count++; }          // one thread at a time
private volatile boolean running = true;  // visibility only, not atomicity
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(key, 1, Integer::sum);       // atomic

try (ExecutorService pool = Executors.newFixedThreadPool(4)) {   // close() waits (Java 19+)
    Future<Integer> f = pool.submit(() -> compute());
    int value = f.get();
}

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {  // Java 21
    for (int i = 0; i < 10_000; i++) executor.submit(() -> blockingCall());
}

CompletableFuture.supplyAsync(() -> fetch())
    .thenApply(String::length)
    .exceptionally(ex -> -1)
    .join();

देखें थ्रेड, सिंक्रोनाइज़ेशन, लॉक, एटॉमिक वेरिएबल, Executors, CompletableFuture, कन्करेंट कलेक्शन और वर्चुअल थ्रेड।

वर्ज़न की मुख्य बातें

वर्ज़न मुख्य सुविधाएँ
8 (2014) लैम्ब्डा, स्ट्रीम, Optional, java.time, डिफ़ॉल्ट मेथड
9–11 मॉड्यूल, List.of, var (10), HttpClient, String.strip/isBlank/repeat (11, LTS)
14–17 switch एक्सप्रेशन (14), टेक्स्ट ब्लॉक (15), रिकॉर्ड (16), सील्ड क्लास (17, LTS)
21 (LTS) वर्चुअल थ्रेड, switch के लिए पैटर्न मैचिंग, रिकॉर्ड पैटर्न, सीक्वेंस्ड कलेक्शन
22–24 अनामित वेरिएबल _ (22), Markdown डॉक कमेंट (23), स्ट्रीम गैदरर (24)
25 (LTS) कॉम्पैक्ट सोर्स फ़ाइलें और इंस्टेंस main, IO क्लास, मॉड्यूल इम्पोर्ट, लचीली कंस्ट्रक्टर बॉडी, स्कोप्ड वैल्यू

देखें Java के वर्ज़न और इतिहास, सर्वोत्तम अभ्यास और, डेटाबेस, वेब ऐप और Spring के लिए, Advanced Java कोर्स।

अपनी समझ जाँचें

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. IO.println(1 + 2 + "3" + 4 + 5); क्या प्रिंट करता है?

    मूल्यांकन बाएँ से दाएँ होता है। 1 + 2 int 3 है; "3" जोड़ने पर स्ट्रिंग "33" मिलती है; उसके बाद हर + स्ट्रिंग कॉन्कैटिनेशन है, इसलिए नतीजा "3345" है।
  2. 2. कौन-सा कलेक्शन की (key) को सॉर्टेड क्रम में रखता है और "50 से छोटी सबसे बड़ी की" का जवाब दे सकता है?

    TreeMap एक NavigableMap है जो रेड-ब्लैक ट्री पर टिका है, इसलिए lowerKey(50) या floorKey(50) इसका जवाब O(log n) में देते हैं। HashMap का कोई क्रम नहीं होता, और LinkedHashMap सिर्फ़ इन्सर्शन या एक्सेस का क्रम याद रखता है।
  3. 3. int n = in.nextInt(); String s = in.nextLine(); इनपुट 5 और अगली लाइन पर Ada के साथ। s क्या है?

    nextInt() टोकन 5 पढ़ता है और लाइन ब्रेक से पहले रुक जाता है, इसलिए nextLine() उस लाइन का बचा हिस्सा लौटाता है, जो खाली है। एक अतिरिक्त nextLine() कॉल करें या पूरी लाइनें पढ़कर पार्स करें।
  4. 4. Comparator<Integer> c = (a, b) -> a - b; बुरा कॉम्पैरेटर क्यों है?

    उदाहरण के लिए, Integer.MIN_VALUE - 1 ओवरफ़्लो होकर एक बड़ी धनात्मक संख्या बन जाता है। Integer.compare(a, b) या Comparator.naturalOrder() हमेशा चिह्न सही देते हैं।

सारांश

  • Java 25 प्रोग्राम एक कॉम्पैक्ट void main() फ़ाइल हो सकता है या public static void main(String[] args) वाली क्लासिक public class Main; IO.println या System.out.println से प्रिंट करें, printf/formatted से फ़ॉर्मैट करें।
  • आठ प्रिमिटिव, इंटीजर डिवीज़न और ओवरफ़्लो, कंपाउंड असाइनमेंट में छिपा कास्ट, और यह जानें कि स्ट्रिंग और बॉक्स्ड संख्याओं पर == बग क्यों है।
  • Switch एक्सप्रेशन, रिकॉर्ड, enum, सील्ड टाइप और पैटर्न मैचिंग आधुनिक Java कोड को छोटा और सुरक्षित बनाते हैं; equals और hashCode को साथ-साथ ओवरराइड करें।
  • कलेक्शन ज़रूरत के हिसाब से चुनें: डिफ़ॉल्ट रूप से ArrayList, HashMap, HashSet; सॉर्टिंग के लिए Tree*, क्रम के लिए LinkedHash*, स्टैक और क्यू के लिए ArrayDeque।
  • लैम्ब्डा, मेथड रेफ़रेंस, स्ट्रीम और Optional ज़्यादातर डेटा प्रोसेसिंग संभाल लेते हैं; java.time, Files और java.util.concurrent तारीख़ों, फ़ाइलों और थ्रेडों को।

आगे: Java प्रोग्राम: 40 क्लासिक उदाहरण, जहाँ आप इन बुनियादी हिस्सों का अभ्यास छोटे, चलाए जा सकने वाले प्रोग्रामों पर करेंगे।

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।