←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Memory Allocation, Garbage Collection, Java Keywords, Access Specifiers & JDK Tools

Study material and explanations for Unit 2

Memory Allocation, Garbage Collection, Java Keywords, Access Specifiers & JDK Tools

1. Memory Allocation in Java (Stack vs Heap)

Whenever a Java program runs, the JVM divides main memory (RAM) primarily into two regions for storing variables and objects: Stack Memory and Heap Memory.

Figure 2.3: How Stack and Heap Memory Work Together in Java
Stack Memory (Fast, LIFO)
  • Stores method call frames & local primitive variables (e.g., int x = 10;)
  • Stores object reference variables (e.g., s1 holding address 0x4A2)
  • Automatically freed as soon as the method finishes execution
Heap Memory (Large, Dynamic)
  • Stores ALL Objects created with new (e.g., new Student() at 0x4A2)
  • Stores instance variables and Arrays
  • Cleaned up automatically by the Garbage Collector (GC)

2. Garbage Collection (GC) in Java

In C/C++, programmers must manually free dynamically allocated memory using free() or delete. Forgetting to do so causes Memory Leaks (RAM fills up and crashes the program).

In Java, Garbage Collection (GC) is an automatic memory management process. A background daemon thread called the Garbage Collector continuously monitors the Heap memory, identifies objects that are no longer referenced (unreachable) by any part of the program, and automatically reclaims their memory.

How Does an Object Become Eligible for Garbage Collection?

An object on the Heap becomes “garbage” (eligible for GC) in 3 ways:

// 1. Nullifying the reference variable
Student s1 = new Student();
s1 = null; // The original Student object now has no reference!

// 2. Re-assigning the reference variable to another object
Student s2 = new Student();
Student s3 = new Student();
s2 = s3; // The first object pointed to by s2 is now eligible for GC!

// 3. Anonymous Object (created without any reference variable)
new Student().display(); // Eligible for GC immediately after display() finishes!
  1. System.gc() or Runtime.getRuntime().gc(): Used by programmers to request the JVM to run the Garbage Collector. (Note: It is a polite request, not a command—the JVM decides the best time to run GC).
  2. finalize() Method: A protected method of the Object class that the Garbage Collector calls just before destroying an object so it can release non-memory resources (like open files or database connections).

3. Essential Java Keywords: this, static, and final

A. The this Keyword

this is a reference variable inside an instance method or constructor that always refers to the currently calling object.

  • Main Uses of this:
    1. Resolving Shadowing (Name Conflict): Distinguishes between instance variables and local parameters when both have the exact same name (this.rollNo = rollNo;).
    2. Constructor Chaining (this()): Calling one constructor from another constructor within the same class.
    3. Passing the current object as an argument to another method.
class Account {
    int accNo;
    double balance;

    Account(int accNo, double balance) {
        this.accNo = accNo;       // 'this.accNo' is instance var; 'accNo' is parameter
        this.balance = balance;
    }
}

B. The static Keyword

The static keyword is used for memory management. A static member belongs to the Class itself rather than to any individual object instance.

  1. Static Variable (Class Variable): Only one single copy is created in the Method Area and shared among all objects of that class (e.g., static String college = "DAVV";).
  2. Static Method: Can be called directly using the Class Name (Math.sqrt(25)) without creating an object. (Restriction: A static method can only directly access other static data/methods and cannot use this or super).
  3. Static Block (static { ... }): Executes automatically once when the class is first loaded into memory by the ClassLoader (even before main()!).

C. The final Keyword

The final keyword means “cannot be changed or modified”. It can be applied in 3 places:

  1. final Variable: Creates a Constant whose value cannot be modified once assigned (final double GST = 18.0;).
  2. final Method: Cannot be overridden by any child subclass.
  3. final Class: Cannot be inherited (extended) by any class (e.g., the built-in String and Math classes are final).

4. Access Specifiers (Access Modifiers) in Java

Access specifiers control the visibility and accessibility of classes, variables, constructors, and methods across packages. Java has 4 access levels:

Access Specifier Within Same Class Within Same Package Subclass in Outside Package Everywhere (Outside Package)
private ✅ Yes ❌ No ❌ No ❌ No
default (No keyword) ✅ Yes ✅ Yes ❌ No ❌ No
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes ✅ Yes
  1. private: Most restrictive; accessible only within the same class (used for Encapsulation / data hiding).
  2. default (Package-Private): Applied when no keyword is written; accessible only to classes inside the same package.
  3. protected: Accessible within the same package plus inside child subclasses located in other packages.
  4. public: Least restrictive; accessible from anywhere in the program.

5. Using the JDK Tools

The Java Development Kit (jdk/bin) provides command-line tools for compiling, running, documenting, inspecting, and debugging Java programs. This is an explicit topic in Unit 2 of the DAVV syllabus!

JDK Tool Command Example Purpose & Description
1. javac javac Student.java Java Compiler: Translates Java source code (.java) into platform-independent Bytecode (.class).
2. java java Student Java Launcher / Interpreter: Starts the JVM, loads the .class file, and executes main().
3. javadoc javadoc Student.java API Documentation Generator: Reads /** ... */ documentation comments from source files and generates clean HTML documentation pages.
4. javap javap java.lang.String Java Class File Disassembler: Inspects any compiled .class file and displays its fields, constructors, methods, and bytecode instructions (using javap -c).
5. jar jar cvf app.jar *.class Java Archive Tool: Packages multiple .class files, images, and metadata into a single compressed .jar file (like a ZIP file) for easy distribution.
6. jdb jdb Student Java Debugger: Command-line debugging tool used to set breakpoints, step through code line-by-line, and inspect variable values to fix bugs.

💡 Exam Preparation Tips for DAVV BCA

  • If asked a 5-mark question on final or static, always divide your answer into 3 sub-headings: (1) Variable, (2) Method, and (3) Class/Block with a 3-line code snippet for each.
  • Memorize the 4×4 Access Specifier Table (private, default, protected, public)—drawing this table guarantees full marks!