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;
MyClass() {
num = 0;
name = "Default";
}
MyClass(int n, String nm) {
num = n;
name = nm;
}
}
public class Test {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(100, "John");
System.out.println(obj1.num + " " + obj1.name);
System.out.println(obj2.num + " " + obj2.name);
}
}
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;
Box() {
width = height = depth = 0;
}
Box(double len) {
width = height = depth = len;
}
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();
Box box2 = new Box(10);
Box box3 = new Box(10, 20, 30);
System.out.println("Volume of box1: " + box1.volume());
System.out.println("Volume of box2: " + box2.volume());
System.out.println("Volume of box3: " + box3.volume());
}
}
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;
MyClass(int n) {
this(n, "Unknown");
}
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();
}
}
Example with Inheritance:
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
super();
System.out.println("Child constructor");
}
}
public class Test {
public static void main(String[] args) {
Child obj = new Child();
}
}
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 {
}
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj = null;
System.gc();
}
@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;
MyClass() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public class Test {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass.displayCount();
}
}
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());
System.out.println("Char at index 1: " + str.charAt(1));
System.out.println("Substring: " + str.substring(0, 5));
System.out.println("Concatenated String: " + str.concat(" Java"));
System.out.println("Replaced String: " + str.replace('l', 'p'));
}
}
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);
int unwrappedNum = wrappedNum.intValue();
String str = "123";
int parsedNum = Integer.parseInt(str);
System.out.println("Parsed Number: " + parsedNum);
}
}