Notes on Key players of Classes and Objects

Notes on Constructors, Constructor Overloading, Chaining, Garbage Collection, static Keyword, String Class, and Wrapper Class


1. Constructors in Java

What is a Constructor?

  • A constructor in Java is a special method that is called when an object is instantiated.
  • The primary purpose of a constructor is to initialize the newly created object.
  • A constructor has the same name as the class and does not have a return type, not even void.

Types of Constructors:

  • Default Constructor: A no-argument constructor automatically provided by Java if no constructors are defined in the class.
  • Parameterized Constructor: A constructor that accepts arguments to initialize an object with specific values.

Example:

class MyClass {
    int num;
    String name;

    // Default constructor
    MyClass() {
        num = 0;
        name = "Default";
    }

    // Parameterized constructor
    MyClass(int n, String nm) {
        num = n;
        name = nm;
    }
}

public class Test {
    public static void main(String[] args) {
        MyClass obj1 = new MyClass(); // Calls default constructor
        MyClass obj2 = new MyClass(100, "John"); // Calls parameterized constructor

        System.out.println(obj1.num + " " + obj1.name); // Output: 0 Default
        System.out.println(obj2.num + " " + obj2.name); // Output: 100 John
    }
}

2. Constructor Overloading

What is Constructor Overloading?

  • Constructor overloading is the technique of defining multiple constructors with different parameter lists within the same class.
  • It allows the creation of objects in different ways depending on the arguments provided.

Example:

class Box {
    double width, height, depth;

    // Default constructor
    Box() {
        width = height = depth = 0;
    }

    // Constructor with one parameter
    Box(double len) {
        width = height = depth = len;
    }

    // Constructor with three parameters
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    double volume() {
        return width * height * depth;
    }
}

public class Test {
    public static void main(String[] args) {
        Box box1 = new Box(); // Calls default constructor
        Box box2 = new Box(10); // Calls constructor with one parameter
        Box box3 = new Box(10, 20, 30); // Calls constructor with three parameters

        System.out.println("Volume of box1: " + box1.volume()); // Output: 0.0
        System.out.println("Volume of box2: " + box2.volume()); // Output: 1000.0
        System.out.println("Volume of box3: " + box3.volume()); // Output: 6000.0
    }
}

3. Constructor Chaining

What is Constructor Chaining?

  • Constructor chaining is the process of calling one constructor from another constructor within the same class or a parent class.
  • It is achieved using the this() or super() keywords.

Example within the Same Class:

class MyClass {
    int num;
    String name;

    // Constructor with one parameter
    MyClass(int n) {
        this(n, "Unknown"); // Calls constructor with two parameters
    }

    // Constructor with two parameters
    MyClass(int n, String nm) {
        num = n;
        name = nm;
    }

    void display() {
        System.out.println(num + " " + name);
    }
}

public class Test {
    public static void main(String[] args) {
        MyClass obj = new MyClass(10);
        obj.display(); // Output: 10 Unknown
    }
}

Example with Inheritance:

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // Calls Parent class constructor
        System.out.println("Child constructor");
    }
}

public class Test {
    public static void main(String[] args) {
        Child obj = new Child();
        // Output:
        // Parent constructor
        // Child constructor
    }
}

4. Java Garbage Collection

What is Garbage Collection?

  • Java provides automatic memory management through garbage collection.
  • Garbage collection automatically deletes objects that are no longer in use to free up memory.

How Does It Work?

  • The garbage collector identifies objects that are no longer reachable by any references in the program and reclaims their memory.
  • This process helps prevent memory leaks and optimizes memory usage.

Garbage Collection Example:

class MyClass {
    // Instance variables
}

public class Test {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj = null; // Eligible for garbage collection
        System.gc(); // Suggests garbage collection (not guaranteed)
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Object is garbage collected.");
    }
}
  • Note: The finalize() method is deprecated in Java 9 and above. It's advisable to avoid relying on it for cleanup tasks.

5. static Keyword in Java

What is static?

  • The static keyword in Java is used for memory management.
  • It can be applied to variables, methods, blocks, and nested classes.

Static Variables:

  • Static variables are shared among all instances of a class.
  • They are initialized only once at the start of the program.

Static Methods:

  • Static methods can be called without creating an instance of the class.
  • They can access static data members and change their values.

Example:

class MyClass {
    static int count = 0; // Static variable

    MyClass() {
        count++;
    }

    static void displayCount() { // Static method
        System.out.println("Count: " + count);
    }
}

public class Test {
    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();
        MyClass.displayCount(); // Output: Count: 2
    }
}

6. String Class in Java

What is the String Class?

  • The String class represents a sequence of characters.
  • Strings are immutable in Java, meaning once a string is created, it cannot be changed.

Common String Methods:

  • length(): Returns the length of the string.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex, int endIndex): Returns a substring from beginIndex to endIndex.
  • concat(String str): Concatenates the specified string to the end of the current string.
  • replace(char oldChar, char newChar): Replaces occurrences of oldChar with newChar.

Example:

public class Test {
    public static void main(String[] args) {
        String str = "Hello, World!";
        System.out.println("Length: " + str.length()); // Output: 13
        System.out.println("Char at index 1: " + str.charAt(1)); // Output: e
        System.out.println("Substring: " + str.substring(0, 5)); // Output: Hello
        System.out.println("Concatenated String: " + str.concat(" Java")); // Output: Hello, World! Java
        System.out.println("Replaced String: " + str.replace('l', 'p')); // Output: Heppo, Worpd!
    }
}

7. Wrapper Class in Java

What is a Wrapper Class?

  • Wrapper classes provide a way to use primitive data types (int, char, etc.) as objects.
  • Each primitive type has a corresponding wrapper class: Integer for int, Character for char, Double for double, etc.

Why Use Wrapper Classes?

  • Wrapper classes allow primitives to be used in collections that require objects, like ArrayList.
  • They provide utility methods for conversions and manipulations.

Common Wrapper Methods:

  • parseXxx(String s): Converts a string to the corresponding primitive type (parseInt, parseDouble, etc.).
  • valueOf(String s): Converts a string to the corresponding wrapper class (Integer.valueOf, Double.valueOf, etc.).
  • toString(): Converts the wrapper object to a string.

Example:

public class Test {
    public static void main(String[] args) {
        int num = 10;
        Integer wrappedNum = Integer.valueOf(num); // Boxing
        int unwrappedNum = wrappedNum.intValue(); // Unboxing

        String str = "123";
        int parsedNum = Integer.parseInt(str); // Convert String to int
        System.out.println("Parsed Number: " + parsedNum); // Output: 123
    }
}