Java Notes
Java Notes
In Java, constructors are special methods that are used to initialize newly created
objects. When a new instance of a class is created, the constructor is called automatically to
initialize the object’s state (i.e., the values of its fields/attributes). Understanding constructors
is fundamental to object-oriented programming in Java, as they allow you to set up objects
with initial values, ensuring that they are in a valid state right from the moment they are
created.
1. Definition and Purpose of a Constructor
A constructor is a block of code that gets executed when an object of a class is
instantiated (i.e., created). The main purpose of a constructor is to initialize the newly created
object. It sets up the initial state of the object by assigning values to its instance variables or
performing other setup actions.
Constructors are called automatically when you create an object using the new
keyword.
A class can have multiple constructors (this is called constructor overloading), each
with a different parameter list, allowing for different ways of initializing objects.
2. Characteristics of a Constructor
Name: The constructor must have the same name as the class in which it is defined.
For example, in a class Car, the constructor must be named Car.
No Return Type: Unlike regular methods, constructors do not have a return type, not
even void. They cannot return any value.
Called Automatically: The constructor is invoked automatically when you create an
object of a class using the new keyword.
Cannot Be Inherited: Constructors are not inherited by subclasses, but they can be
invoked from a subclass constructor using super().
Can Be Overloaded: You can define multiple constructors with different parameter
lists (this is known as constructor overloading). Java will choose the appropriate
constructor based on the number and types of arguments passed during object
creation.
3. Types of Constructors in Java
Java supports two main types of constructors:
1. Default Constructor (No-Argument Constructor)
A default constructor is a constructor that does not take any arguments.
If no constructor is defined in the class, Java automatically provides a default
constructor. The default constructor initializes the object with default values (e.g.,
null for objects, 0 for numbers, false for booleans).
When you explicitly define a constructor with parameters, the default constructor is
no longer automatically provided.
Example of a Default Constructor:
class Person {
String name;
int age;
// Default constructor
public Person() {
name = "John Doe"; // Default name
age = 30; // Default age
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name; // Initialize name with the provided value
this.age = age; // Initialize age with the provided value
}
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Here, the output will be "Wednesday" because day equals 3.
2. Looping Statements
Looping statements allow you to execute a block of code multiple times, based on a
condition.
a. for loop
The for loop is used when you know beforehand how many times you need to execute
a statement or a block of code.
Syntax:
for (initialization; condition; increment/decrement) {
// Block of code to be executed
}
initialization: Initializes the loop counter.
condition: Specifies the condition for the loop to continue executing.
increment/decrement: Modifies the loop counter after each iteration.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}
This loop will print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
b. while loop
The while loop is used when you want to execute a block of code as long as a
specified condition is true.
Syntax:
while (condition) {
// Block of code to be executed
}
Example:
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration " + i);
i++;
}
}
}
This loop will also print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
c. do-while loop
The do-while loop is similar to the while loop, except that it guarantees that the block
of code will execute at least once, regardless of whether the condition is true.
Syntax:
do {
// Block of code to be executed
} while (condition);
Example:
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration " + i);
i++;
} while (i <= 5);
}
}
This loop will also print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
However, unlike the while loop, the do-while loop guarantees the code inside the
block is executed at least once.
3. Jump Statements
Jump statements allow you to control the flow of execution within loops or switch
statements by jumping to another part of the code.
a. break statement
The break statement is used to terminate the current loop or switch statement, and
transfer control to the next statement after the loop or switch block.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}
}
}
The output will be:
1
2
3
4
b. continue statement
The continue statement is used to skip the current iteration of a loop and move to the
next iteration.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the iteration when i equals 3
}
System.out.println(i);
}
}
}
The output will be:
1
2
4
5
c. return statement
The return statement is used to exit from the current method and optionally return a
value (if the method has a return type other than void).
Example:
public class Main {
public static void main(String[] args) {
System.out.println("Before return statement");
return; // Exits the main method
// The following code will not be executed
System.out.println("After return statement");
}
}
The output will be:
Before return statement
Not necessary, can happen within the Requires inheritance (subclass inherits
Inheritance
same class. from superclass).
Method Overloading allows you to define multiple methods with the same name but
with different parameters. It is resolved at compile-time and provides a way to use the
same method name for different types or numbers of arguments.
Method Overriding, on the other hand, is used to provide a specific implementation
of a method that is already defined in a superclass. It is resolved at runtime and is
essential for achieving polymorphic behavior in Java.
Both techniques are important tools for writing clean, maintainable, and flexible code,
allowing methods to behave differently based on the context (inputs or objects).