Skip to content
IT-504 (C) · Java Programming/Quick Revision Short Notes

Java Programming (IT-504 (C)) - Unit 1 Short Notes

I. Introduction to Java

Features of Java:

  • Simple: Syntax similar to C/C++, but eliminates pointers and operator overloading.

  • Secure: No explicit pointers, bytecode verification, sandbox execution.

  • Portable: Bytecode runs on any JVM (Write Once, Run Anywhere).

  • Object-Oriented: Everything is an object (except primitives); supports encapsulation, inheritance, polymorphism, abstraction.

  • Robust: Strong memory management, exception handling, type checking.

  • Multithreaded: Built-in support for concurrent programming.

  • Distributed: Supports RMI and socket programming.

  • Dynamic: Classes loaded at runtime, reflection API.

Java Virtual Machine (JVM) & Bytecode:

  • Java source code (.java) → Compiler → Bytecode (.class).

  • JVM interprets bytecode into machine-specific instructions.

  • JVM provides platform independence, security, and automatic garbage collection.

Platform Independence:

  • Bytecode is platform-neutral; JVM is platform-specific.

  • \boxed{\text{Write Once, Run Anywhere (WORA)}}

Java as OOP Language:

  • Encapsulation: Bundling data and methods, access control via modifiers.

  • Inheritance: extends keyword for code reuse.

  • Polymorphism: Method overloading (compile-time) and overriding (runtime).

  • Abstraction: Abstract classes and interfaces hide implementation.

[!TIP]

Common Pitfall: Java is not purely object-oriented due to primitive types (e.g., int, char). Use wrapper classes (Integer, Character) for pure OOP.


II. Data Types, Variables, and Operators

Primitive Data Types:

Type Size (bits) Range Default Value
byte 8 -128 to 127 0
short 16 -32,768 to 32,767 0
int 32 -2³¹ to 2³¹-1 0
long 64 -2⁶³ to 2⁶³-1 0L
float 32 ~7 decimal digits 0.0f
double 64 ~15 decimal digits 0.0d
char 16 Unicode 0 to 65,535 ''
boolean 1 true/false false

Reference Data Types:

  • Classes, interfaces, arrays. Store references (memory addresses).

  • Default value: null.

Variable Types:

  • Local: Inside method/block, no default value, must initialize.

  • Instance: Non-static fields, per-object, default values.

  • Static: Class-level, shared among objects, default values.

Operators:

  • Arithmetic: +, -, *, /, %, ++, --.

  • Relational: ==, !=, >, <, >=, <=.

  • Logical: &&, ||, !.

  • Bitwise: &, |, ^, ~, <<, >>, >>>.

  • Assignment: =, +=, -=, etc.

  • Ternary: condition ? expr1 : expr2.

[!TIP]

Common Pitfall: == compares references for objects; use .equals() for value comparison.


III. Control Statements

Selection Statements:

  • if, if-else, nested if.

  • switch: Works with byte, short, int, char, String (Java 7+), enum. case values must be constants.

Iteration Statements:

  • for(init; condition; update) { }

  • while(condition) { }

  • do { } while(condition); // Executes at least once.

  • Enhanced for: for(type var : array/collection) { } // For arrays/collections only.

Jump Statements:

  • break: Exits loop or switch.

  • continue: Skips current iteration, proceeds to next.

  • return: Exits method, returns value (if any).

[!TIP]

Common Pitfall: continue in do-while jumps to condition check, not loop start. Labeled break/continue for nested loops.


IV. Arrays and Strings

Arrays:

  • Declaration: int[] arr; or int arr[];

  • Initialization:

    • int[] arr = new int[5]; // Default 0s.

    • int[] arr = {1,2,3};

    • int[] arr = new int[]{1,2,3};

  • Multi-dimensional: int[][] matrix = new int[3][4]; // Jagged arrays possible.

String Class:

  • Immutable: Cannot change content; operations create new objects.

  • Common Methods:

    • length(), charAt(index), substring(begin, end), equals(), equalsIgnoreCase(), indexOf(), toUpperCase(), toLowerCase(), trim(), split(regex).
  • String Literals: Stored in String Pool; identical literals share same reference.

StringBuffer vs StringBuilder:

Feature StringBuffer StringBuilder
Mutability Mutable Mutable
Thread-Safety Synchronized (thread-safe) Not synchronized (faster)
Performance Slower Faster
Use Case Multi-threaded environments Single-threaded environments

[!TIP]

Common Pitfall: String concatenation in loops (+) creates many temporary objects; use StringBuilder for efficiency.


V. Classes and Objects

Defining a Class:


class ClassName {

    // fields (instance/static)

    // methods

    // constructors

}

Creating Objects:

  • ClassName obj = new ClassName(); // new allocates memory, calls constructor.

Instance vs Static Members:

  • Instance: Per-object, accessed via object reference.

  • Static: Class-level, accessed via ClassName.member or object. One copy per class.

this Keyword:

  • Refers to current object.

  • Used to disambiguate instance variables from parameters, call constructors (this()), pass current object as argument.

Constructors:

  • Default Constructor: No-args, provided by compiler if no other constructor exists. Initializes primitives to default, objects to null.

  • Parameterized Constructor: Takes arguments, used to initialize fields.

  • Copy Constructor: Not built-in; user-defined: Class(Class other) { this.field = other.field; }.

Method Overloading:

  • Same method name, different parameter lists (type, number, order).

  • Compile-time polymorphism.

  • Return type can differ, but not sufficient for overloading.

[!TIP]

Common Pitfall: Constructor name must match class name exactly; no return type (not even void).


VI. Inheritance and Polymorphism

Inheritance (extends):

  • Subclass inherits superclass members (except private).

  • Single inheritance for classes; multiple via interfaces.

super Keyword:

  • Refers to parent class.

  • super() calls parent constructor (must be first statement).

  • super.method() calls parent method.

  • super.field accesses parent field.

Method Overriding:

  • Subclass redefines superclass method with same signature.

  • Used for runtime polymorphism.

  • @Override annotation (optional but recommended).

  • Access modifier cannot be more restrictive.

  • final methods cannot be overridden.

Dynamic Method Dispatch (Runtime Polymorphism):

  • Superclass reference can refer to subclass object.

  • Overridden method call resolved at runtime based on actual object type.


Animal a = new Dog();

a.sound(); // Calls Dog.sound() if overridden.

Abstract Classes and Methods:

  • Abstract class: Cannot instantiate; may contain abstract methods (no body) and concrete methods.

  • Abstract method: Must be implemented by concrete subclasses.

  • Class must be abstract if it has any abstract method.

Interfaces:

  • Definition: interface InterfaceName { abstract methods (implicitly public abstract), static/final fields, default/static methods (Java 8+). }

  • Implementation: class MyClass implements Interface1, Interface2 { } // Multiple inheritance.

  • All methods are public abstract by default (pre-Java 8).

  • Variables are public static final by default.

final Keyword:

  • final class: Cannot be subclassed (e.g., String, Integer).

  • final method: Cannot be overridden.

  • final variable: Constant; cannot reassign (but object state can change if mutable).

Multiple Inheritance in Java:

  • Not allowed for classes (diamond problem).

  • Achieved via interfaces: class can implement multiple interfaces; interfaces can extend multiple interfaces.

[!TIP]

Common Pitfall: Overriding method must have same signature (including return type, which can be covariant). static methods are hidden, not overridden.


VII. Packages and Access Protection

Creating Packages:

  • package com.example.myapp; // First statement in .java file.

  • Directory structure must match package hierarchy.

  • Compile: javac -d . MyClass.java // Creates com/example/myapp/MyClass.class.

Importing Packages:

  • import com.example.myapp.MyClass; // Single type.

  • import com.example.myapp.*; // All types (except subpackages).

  • Static import: import static java.lang.Math.PI; // Access static members without class name.

Access Modifiers:

Modifier Class Package Subclass (outside) Everywhere
public ✓ ✓ ✓ ✓
protected ✓ ✓ ✓ ✗
default (no modifier) ✓ ✓ ✗ ✗
private ✓ ✗ ✗ ✗

Levels of Access Protection:

  • Within class: All members accessible.

  • Within package: public, protected, default accessible.

  • Outside package (subclass): public, protected accessible (via inheritance).

  • Outside package (non-subclass): Only public accessible.

Access for Classes/Interfaces:

  • Top-level classes/interfaces: Only public or default.

  • Nested classes: All modifiers allowed.

[!TIP]

Common Pitfall: protected allows access in subclasses even if in different package, but only through inheritance (not via reference of parent class from different package).


VIII. Exception Handling

Exception Types:

  • Checked Exceptions: Subclasses of Exception (excluding RuntimeException). Must be handled or declared (e.g., IOException, SQLException).

  • Unchecked Exceptions: Subclasses of RuntimeException or Error. Not required to handle (e.g., NullPointerException, ArithmeticException).

try-catch-finally:


try {

    // Code that may throw exception

} catch (ExceptionType1 e1) {

    // Handler

} catch (ExceptionType2 e2) {

    // Handler

} finally {

    // Always executes (even if return in try/catch), for cleanup

}
  • Multiple catch blocks; more specific first.

  • try with resources (Java 7+): try (FileReader fr = new FileReader("file.txt")) { } // Auto-close.

throw vs throws:

  • throw: Used to raise an exception explicitly. throw new IllegalArgumentException();

  • throws: Used in method signature to declare exceptions that method might throw. void read() throws IOException { }

Custom Exceptions:

  • Extend Exception (for checked) or RuntimeException (for unchecked).

  • Provide constructors (no-arg, with message, with cause).

Assertions (assert):

  • assert condition; or assert condition : message;

  • Enabled at runtime with -ea (or -enableassertions). Disabled by default.

  • Used for debugging, not for production error handling.

[!TIP]

Common Pitfall: finally block executes even if return in try/catch, but not if System.exit() called. Catch blocks should be specific; avoid empty catch blocks.


IX. Multithreading

Thread Creation:

  1. Extend Thread class:

    
    class MyThread extends Thread {
    
        public void run() { /* task */ }
    
    }
    
    MyThread t = new MyThread();
    
    t.start(); // Calls run() in new thread
    
    
  2. Implement Runnable interface (preferred for multiple inheritance):

    
    class MyRunnable implements Runnable {
    
        public void run() { /* task */ }
    
    }
    
    Thread t = new Thread(new MyRunnable());
    
    t.start();
    
    

Thread Lifecycle:

DiagramCANVAS: Thread lifecycle diagram: New (Thread object created) -> Runnable (start() called, ready to run) -> Running (run() executing) -> Blocked (wait/sleep/join, waiting for resource) -> Terminated (run() completes or error). Transitions: start() from New to Runnable; scheduler from Runnable to Running; sleep/wait/join to Blocked; notify/notifyAll from Blocked to Runnable; termination from Running/Blocked.

Thread Methods:

  • start(): Starts thread, calls run().

  • run(): Entry point for thread logic.

  • sleep(ms): Pauses thread (static method).

  • join(): Waits for thread to die.

  • isAlive(): Checks if thread is alive (New or Terminated → false).

  • setPriority(int): 1 (MIN) to 10 (MAX).

  • setDaemon(boolean): Daemon threads (background) die when main thread ends.

Thread Synchronization:

  • Purpose: Prevent race conditions when multiple threads access shared resources.

  • Synchronized methods: public synchronized void method() { } // Locks on this (instance) or Class object (static).

  • Synchronized blocks:

    
    synchronized(lockObject) {
    
        // critical section
    
    }
    
    
  • ReentrantLock (java.util.concurrent.locks): More flexible than synchronized; explicit lock/unlock.

Inter-thread Communication:

  • Must be called from synchronized context.

  • wait(): Releases lock, enters waiting state.

  • notify(): Wakes one waiting thread.

  • notifyAll(): Wakes all waiting threads.

  • Used for producer-consumer problems.

[!TIP]

Common Pitfall: Never call run() directly to start a thread; use start(). sleep() is static; Thread.sleep() affects current thread. wait(), notify(), notifyAll() are in Object class, not Thread.


X. I/O Streams

Stream Concept:

  • Sequence of data. Byte streams handle binary data; character streams handle text (with encoding).

Byte Streams:

  • Abstract classes: InputStream, OutputStream.

  • File I/O: FileInputStream, FileOutputStream.

  • Buffered: BufferedInputStream, BufferedOutputStream (efficiency via buffer).

  • Standard: System.in (InputStream), System.out (PrintStream), System.err.

Character Streams:

  • Abstract classes: Reader, Writer.

  • File I/O: FileReader, FileWriter (uses default encoding).

  • Buffered: BufferedReader (has readLine()), BufferedWriter.

  • Conversion: InputStreamReader (bytes to chars), OutputStreamWriter (chars to bytes).

Difference: Byte vs Character Streams:

Byte Streams Character Streams
Handle raw binary data Handle text (Unicode)
InputStream/OutputStream Reader/Writer
No encoding/decoding Encoding/decoding involved
E.g., images, audio E.g., text files

Capturing Input from User:

  • Scanner (java.util): Scanner sc = new Scanner(System.in); int n = sc.nextInt();

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

  • Scanner is easier; BufferedReader is faster for large input.

[!TIP]

Common Pitfall: Always close streams (use try-with-resources). FileReader/FileWriter use platform default encoding; specify encoding with InputStreamReader/OutputStreamWriter for portability.


XI. GUI Programming (AWT and Swing)

AWT Facilities:

  • Components: UI elements (Button, TextField, Label, Checkbox, Choice, List).

  • Containers: Hold components (Frame, Panel, Applet, Dialog).

  • Layout Managers: Arrange components:

    • FlowLayout (left to right, wraps).

    • BorderLayout (North, South, East, West, Center).

    • GridLayout (grid of equal-sized cells).

    • GridBagLayout (flexible grid).

    • CardLayout (stacked cards).

Swing Components:

  • Lightweight, pluggable look-and-feel.

  • Prefixed with J: JFrame, JPanel, JButton, JTextField, JLabel, JCheckBox, JComboBox, JList, JTable, etc.

  • JApplet (deprecated), JDialog.

Event Handling Model:

  • Event Source: Component that generates event (e.g., JButton).

  • Event Object: Encapsulates event info (e.g., ActionEvent).

  • Event Listener: Interface with callback methods (e.g., ActionListener with actionPerformed(ActionEvent e)).

  • Event Adapter: Abstract class with empty implementations (e.g., WindowAdapter, MouseAdapter) for convenience.

Example: Sum of Two Numbers (Swing):


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SumGUI extends JFrame implements ActionListener {

    JTextField t1, t2, res;

    JButton add;

    public SumGUI() {

        t1 = new JTextField(10); t2 = new JTextField(10); res = new JTextField(10);

        add = new JButton("Add");

        add.addActionListener(this);

        setLayout(new FlowLayout());

        add(t1); add(t2); add(add); add(res);

        setSize(300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

        int a = Integer.parseInt(t1.getText());

        int b = Integer.parseInt(t2.getText());

        res.setText(String.valueOf(a+b));

    }

    public static void main(String[] args) { new SumGUI(); }

}

[!TIP]

Common Pitfall: Swing components must be created/updated on Event Dispatch Thread (EDT) using SwingUtilities.invokeLater(). AWT is heavyweight; Swing is lightweight (but mixing can cause issues).


XII. Applets

Applet vs Application:

  • Applet: Runs in browser/AppletViewer, no main(), security restrictions, lifecycle methods.

  • Application: Standalone, has main(), full system access.

Applet Life Cycle:

  1. init(): Called once when applet first loads. Initialize resources.

  2. start(): Called after init(), and whenever applet becomes visible (e.g., browser tab switched to). Start animations/threads.

  3. stop(): Called when applet becomes invisible (e.g., browser tab switched away). Pause threads.

  4. destroy(): Called when browser closes/applet removed. Cleanup resources.

Applet Tags (HTML):


<applet code="MyApplet.class" width=300 height=200>

    <param name="text" value="Hello">

</applet>

  • code: Class file.

  • width, height: Dimensions.

  • <param>: Pass parameters via getParameter("name").

Example Applet:


import java.applet.Applet;

import java.awt.Graphics;

public class MyApplet extends Applet {

    public void paint(Graphics g) {

        g.drawString("Hello Applet", 50, 50);

    }

}

[!TIP]

Common Pitfall: Applets are deprecated (Java 9+); use Java Web Start or other technologies. Lifecycle: init() → start() → stop() → destroy(); start()/stop() may be called multiple times.


XIII. Database Connectivity (JDBC)

JDBC Architecture:

  • JDBC API: java.sql and javax.sql packages.

  • JDBC Drivers: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol), Type 4 (pure Java, thin driver).

  • DriverManager: Manages drivers, establishes connections.

Steps to Connect:

  1. Load driver: Class.forName("com.mysql.cj.jdbc.Driver"); // Registers driver.

  2. Establish connection:

    
    Connection conn = DriverManager.getConnection(
    
        "jdbc:mysql://localhost:3306/dbname", "user", "password");
    
    
  3. Create statement:

    • Statement stmt = conn.createStatement(); // For static SQL.

    • PreparedStatement pstmt = conn.prepareStatement("INSERT INTO table VALUES (?, ?)"); // For dynamic SQL with parameters.

  4. Execute query:

    • ResultSet rs = stmt.executeQuery("SELECT * FROM table"); // For SELECT.

    • int rows = stmt.executeUpdate("INSERT ..."); // For INSERT/UPDATE/DELETE.

  5. Process results:

    
    while (rs.next()) {
    
        int id = rs.getInt("id");
    
        String name = rs.getString("name");
    
    }
    
    
  6. Close connections: rs.close(); stmt.close(); conn.close(); // In reverse order. Use try-with-resources.

JDBC-ODBC Bridge:

  • Type 1 driver; translates JDBC calls to ODBC.

  • Requires ODBC driver installed.

  • Deprecated in Java 8; removed in Java 11.

Basic JDBC Program Structure:


import java.sql.*;

public class JDBCExample {

    public static void main(String[] args) {

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "user", "pass");

            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

            while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2));

            rs.close(); stmt.close(); conn.close();

        } catch (Exception e) { e.printStackTrace(); }

    }

}

[!TIP]

Common Pitfall: Always close ResultSet, Statement, Connection in finally block or try-with-resources to avoid leaks. Use PreparedStatement to prevent SQL injection.


XIV. Networking

Networking Basics:

  • IP Address: Unique identifier for device on network.

  • Port: 16-bit number (0-65535) identifying process/service.

  • Protocol: Rules for communication (TCP = reliable, connection-oriented; UDP = fast, connectionless).

Socket Programming:

  • Server:

    
    ServerSocket server = new ServerSocket(port);
    
    Socket client = server.accept(); // Blocks until client connects
    
    // Get I/O streams: InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream();
    
    
  • Client:

    
    Socket socket = new Socket(host, port);
    
    // Get I/O streams
    
    

Client-Server Example (Echo):
Server:


import java.net.*;

import java.io.*;

public class EchoServer {

    public static void main(String[] args) throws Exception {

        ServerSocket ss = new ServerSocket(1234);

        Socket s = ss.accept();

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        PrintWriter out = new PrintWriter(s.getOutputStream(), true);

        String line;

        while ((line = in.readLine()) != null) {

            out.println("Echo: " + line);

        }

        s.close(); ss.close();

    }

}

Client:


import java.net.*;

import java.io.*;

public class EchoClient {

    public static void main(String[] args) throws Exception {

        Socket s = new Socket("localhost", 1234);

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        PrintWriter out = new PrintWriter(s.getOutputStream(), true);

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        String line;

        while ((line = console.readLine()) != null) {

            out.println(line);

            System.out.println(in.readLine());

        }

        s.close();

    }

}

[!TIP]

Common Pitfall: Server must start before client. Use try-with-resources for sockets/streams. Handle IOException.


XV. Java Beans

Java Beans Components:

  • Properties: Private fields with public getter/setter methods (e.g., getX(), setX()).

  • Methods: No-arg constructor, getter/setter, any business methods.

  • Events: Support event listeners (e.g., addActionListener(ActionListener l)).

Introspection:

  • Process of discovering bean properties, methods, events at runtime.

  • Uses reflection API.

BeanInfo Interface:

  • java.beans.BeanInfo provides explicit bean information.

  • Override methods: getPropertyDescriptors(), getMethodDescriptors(), getEventSetDescriptors().

  • Obtain via Introspector.getBeanInfo(BeanClass.class).

  • Allows hiding properties/methods, customizing display names.

Bean Properties Types:

  • Simple: Single value, getX(), setX().

  • Indexed: Array access, getX(int index), setX(int index, value).

  • Bound: Supports PropertyChangeListener; fire PropertyChangeEvent on change.

  • Constrained: Supports VetoableChangeListener; listeners can veto change.

Bean Events:

  • Event listener registration methods (e.g., addActionListener).

  • Corresponding removal methods (e.g., removeActionListener).

  • Event listener interfaces (e.g., ActionListener).

[!TIP]

Common Pitfall: Beans must have a public no-arg constructor. Properties must follow naming conventions (get/set for boolean can be is).


XVI. JNDI (Java Naming and Directory Interface)

JNDI Overview:

  • API for accessing naming and directory services (e.g., LDAP, DNS, RMI registry).

  • Provides uniform interface to diverse systems.

Context Interface Methods:

  • bind(String name, Object obj): Binds name to object.

  • rebind(String name, Object obj): Rebinds name (overwrites existing).

  • lookup(String name): Returns object bound to name.

  • unbind(String name): Removes binding.

  • rename(String oldName, String newName): Renames binding.

  • createSubcontext(String name): Creates subcontext.

  • getAttributes(String name): Returns attributes for named object.

  • modifyAttributes(String name, Attributes attrs): Modifies attributes.

JNDI Example (Naming Service):


import javax.naming.*;

import java.util.Hashtable;

public class JNDIExample {

    public static void main(String[] args) throws NamingException {

        Hashtable<String, String> env = new Hashtable<>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");

        env.put(Context.PROVIDER_URL, "file:/C:/JNDI");

        Context ctx = new InitialContext(env);

        // Bind

        ctx.bind("myObj", "Hello JNDI");

        // Lookup

        String value = (String) ctx.lookup("myObj");

        System.out.println(value); // Hello JNDI

        // Rebind

        ctx.rebind("myObj", "Updated");

        // Unbind

        ctx.unbind("myObj");

        ctx.close();

    }

}

Note: Provider-specific factories and URLs required.

[!TIP]

Common Pitfall: JNDI requires provider libraries (e.g., fscontext.jar for file system). lookup() returns Object; cast appropriately.


XVII. Garbage Collection

Purpose & Mechanism:

  • Automatic memory management; reclaims memory from unreachable objects.

  • Eligibility: Object becomes eligible when no references point to it (e.g., obj = null;, reference goes out of scope, isolated cycles).

  • Process: JVM runs GC periodically or when memory low.

  • Phases: Mark (identify reachable objects), Sweep (reclaim unreachable), Compact (optional, defragment heap).

System.gc() and Runtime.gc():

  • Suggest JVM to run GC.

  • Not guaranteed; JVM may ignore.

  • Runtime.getRuntime().gc() equivalent.

finalize() Method:

  • Called by GC on object before回收 (only once).

  • Declared in Object class; override for cleanup (e.g., closing resources).

  • Unreliable: May never be called, or called multiple times if object resurrected.

  • Deprecated (since Java 9); use try-with-resources or Cleaner (Java 9+).

Types of Garbage Collectors (Brief):

  • Serial GC: Single thread, for small apps. -XX:+UseSerialGC

  • Parallel GC (Throughput): Multi-threaded, maximizes throughput. -XX:+UseParallelGC

  • CMS (Concurrent Mark Sweep): Concurrent with app threads, low pause times (deprecated).

  • G1 (Garbage-First): Divides heap into regions, predictable pauses. Default since Java 9. -XX:+UseG1GC

  • ZGC / Shenandoah: Low-latency, scalable (Java 11+).

[!TIP]

Common Pitfall: Do not rely on finalize() for critical cleanup; it may not run. Avoid creating unnecessary objects to reduce GC pressure. Use profiling tools to monitor GC.


Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in