Java Programming — Study Notes

Unit 02

Constructors, Garbage Collector, Keywords, Static & Interfaces

5 Questions 6 Marks Each
01
6 Marks Question

Constructors in Java

A constructor in Java is a special member function of a class whose main task is to initialize the object when it is created. It is automatically invoked at the time of object creation.

Definition

A constructor is a special method that has the same name as the class and is used to initialize instance data members of the class.

Characteristics of Constructor

Constructors have the following properties:

  • The constructor name must be the same as the class name.
  • Constructors do not have any return type, not even void.
  • Constructors are automatically called when an object is created.
  • If no constructor is provided, Java automatically provides a default constructor.

Types of Constructors

1. Default Constructor (No-Argument Constructor)

A constructor that does not take any parameters is called a default or no-argument constructor. It initializes objects with default values.

class Box {
    int length;

    Box() {          // default constructor
        length = 10;
    }
}

2. Parameterized Constructor

A constructor that accepts parameters is called a parameterized constructor. It allows initialization of objects with different values.

class Box {
    int length;

    Box(int l) {     // parameterized constructor
        length = l;
    }
}

3. Copy Constructor

A copy constructor is used to copy the data of one object into another object. In Java, this is usually implemented by passing an object as a parameter.

class Box {
    int length;

    Box(Box b) {     // copy constructor
        length = b.length;
    }
}

Constructor Overloading

When a class contains more than one constructor with different parameter lists, it is called constructor overloading. It supports compile-time polymorphism.

Conclusion Constructors are essential in Java for initializing objects automatically. They improve code readability and ensure objects start in a valid state. Java supports default, parameterized, and copy constructors, along with constructor overloading for flexibility.
02
6 Marks Question

Garbage Collector in Java

The Garbage Collector (GC) in Java is an automatic memory management mechanism that removes objects which are no longer in use, so that memory can be reused for other programs. It helps prevent memory leaks and improves program efficiency.

Definition

In Java, objects are created using the new keyword and occupy memory. The process of automatically destroying unused objects and freeing memory is called garbage collection.

Need of Garbage Collector

  • Objects occupy memory when created.
  • If unused objects are not removed, memory gets wasted.
  • Garbage collector automatically frees such memory.
  • Thus, Java programmers do not need to manually deallocate memory (unlike C/C++).

Working of Garbage Collector

The garbage collector works on the mark-sweep algorithm:

  • Objects that are still referenced are marked as active.
  • Objects with no reference are marked for removal.
  • Marked objects are removed from memory.

The garbage collector runs on a low-priority thread.

When Object Becomes Eligible for GC

An object becomes eligible for garbage collection when it has no reference, or it is explicitly assigned null. Such objects are automatically cleaned by the garbage collector.

Calling Garbage Collector

We can request the garbage collector using:

System.gc();

However, it does not guarantee when the garbage collector will actually run.

finalize() Method

  • The finalize() method is called just before garbage collection.
  • It is used to perform cleanup tasks like closing files.
  • Its execution time cannot be predicted.

General form:

protected void finalize() throws Throwable {
    // cleanup code
}
Advantages of Garbage Collector
  • Automatic memory management
  • Prevents memory leaks
  • Improves program reliability
  • Reduces programmer burden
Conclusion The Java garbage collector automatically removes unused objects from memory using the mark-sweep algorithm. It simplifies memory management and makes Java programs more robust and efficient.
03
6 Marks Question

Super and This Keyword in Java

In Java, this and super are special reference keywords used to refer to objects in inheritance and within classes. They help in accessing members of the current class and parent class respectively.

This Keyword

Definition

The this keyword always refers to the current object of the class. It is used inside non-static methods and constructors.

Uses of this Keyword

1. To refer current class instance variable

It is mainly used when local variable name and instance variable name are the same; this distinguishes them.

class Test {
    int x;

    Test(int x) {
        this.x = x;   // refers to instance variable
    }
}

2. To refer current class object

this acts as a reference to the object on which the method is called.

Important Points about this
  • Points to current object
  • Used only in non-static methods and constructors
  • Cannot be used inside static methods
  • Helps in resolving variable hiding

Super Keyword

Definition

The super keyword is used to refer to the immediate parent (super) class object. It is mainly used in inheritance.

Uses of super Keyword

1. To access super class variable

super.variableName;

Used when subclass and superclass have variables with the same name.

2. To call super class method

super.methodName();

Used when a subclass overrides a method and still wants to use the parent class version.

3. To call super class constructor

super(parameters);

Must be the first statement in subclass constructor. Used to initialize parent class part of object.

Difference Between this and super

thissuper
Refers to current class objectRefers to parent class object
Used within same classUsed in inheritance
Access current class membersAccess parent class members
Cannot be used in static contextAlso cannot be used in static context
Conclusion The this keyword refers to the current object and is mainly used to resolve variable conflicts within a class, while the super keyword refers to the parent class and is used to access parent class variables, methods, and constructors. Both are essential for writing clear and effective object-oriented Java programs.
04
6 Marks Question

Importance of Static Keyword in Java

The static keyword in Java is used to create class-level members that belong to the class rather than to any specific object. Static members are shared among all objects of the class and can be accessed without creating an object.

Definition

The static keyword is used to create a static member of a class, which can be a static variable, static method, or static block (initializer).

Importance / Advantages of Static Keyword

1. Memory Efficiency (Static Variable)

When a variable is declared static, only one copy of that variable is created for the entire class and shared by all objects. This saves memory.

class Test {
    static int count = 0;
}

2. Access Without Object

Static members can be accessed using the class name without creating an object.

ClassName.staticVariable;
ClassName.staticMethod();

This improves performance and convenience.

3. Utility Methods (Static Methods)

Static methods are useful for utility or common functions because they can access only static data, cannot use this or super, and can be called directly using the class name.

class MathUtil {
    static int square(int x) {
        return x * x;
    }
}

4. Class Initialization (Static Block)

Java does not support static constructors, so static blocks are used to initialize static variables. The static block executes once when the class is loaded into memory.

class Test {
    static {
        System.out.println("Static block executed");
    }
}

5. Shared Data Management

Static keyword is important when we want to maintain common data for all objects, such as company name, counter variable, or configuration values.

Conclusion The static keyword is important in Java because it enables memory sharing, allows access without object creation, supports utility methods, and helps initialize class-level data efficiently. It improves performance and resource management in Java programs.
05
6 Marks Question

Interface in Java

An interface in Java is a special reference type similar to a class that contains abstract methods and constants. It is used to achieve abstraction and multiple inheritance in Java.

Definition

An interface is like a class that contains data and methods but with a major difference: it tells a class what to do but not how to do it.

General Form of Interface

interface InterfaceName {
    // variables and abstract methods
}

Characteristics of Interface

Important characteristics are:

  • Interface methods do not contain a body.
  • A class that implements an interface must provide implementation of all its methods.
  • Interface variables are implicitly public, static, and final.
  • Interface access specifier can be default or public.
  • If a class does not implement all interface methods, it must be declared abstract.

Implementing an Interface

A class uses the implements keyword to implement an interface.

interface Shape {
    void draw();   // abstract method
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}
Advantages of Interface
  • Achieves full abstraction
  • Supports multiple inheritance
  • Promotes loose coupling
  • Improves code reusability
  • Provides standardization

Java uses interfaces to achieve multiple inheritance since it does not support multiple inheritance through classes.

Conclusion An interface in Java defines a contract that classes must follow. It provides abstraction, supports multiple inheritance, and helps in designing flexible and maintainable object-oriented programs.