Unit 1
Unit 1
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
TYPE CONVERSION AND CASTING IN JAVA
In Java, type conversion and casting are used to convert one data type to another. Java
supports both implicit (automatic) and explicit (manual) type conversion.
Let's break these concepts down:
1. Type Conversion in Java
Type conversion refers to changing a variable from one data type to another. There are two
kinds of type conversion in Java:
Implicit Type Conversion (Widening)
Explicit Type Conversion (Narrowing)
2. Implicit Type Conversion (Widening)
Widening conversion occurs when a smaller data type is automatically converted to a larger
data type. This type of conversion is done automatically by the Java compiler without any
data loss.
Example:
From int to long, float to double, char to int, etc.
The compiler performs widening because no data is lost during the conversion.
Example of Implicit Type Conversion:
int a = 100;
long b = a; // int is automatically converted to long
System.out.println(b); // Output: 100
In the above example, the int variable a is automatically converted into a long type without
explicit casting.
Rules for Implicit Type Conversion:
Smaller primitive data types (like byte, short, int, char) can be automatically
converted to larger primitive types (like long, float, double).
Integer types can be converted into floating-point types.
Char type can be converted to numeric types (e.g., int or long).
3. Explicit Type Conversion (Narrowing)
Narrowing conversion occurs when a larger data type is explicitly converted to a smaller
data type. This type of conversion can result in data loss because the larger value might not
fit into the smaller type's range.
To perform narrowing conversion, you must cast the larger data type to a smaller one using
casting.
Example:
From long to int, double to float, double to int, etc.
You need to cast explicitly, and you may lose precision or encounter data truncation.
Example of Explicit Type Conversion:
double a = 9.78;
int b = (int) a; // Explicit casting from double to int
System.out.println(b); // Output: 9 (fractional part is discarded)
In this example, the double value is explicitly cast to int, and the fractional part (.78) is
discarded.
Rules for Explicit Type Conversion:
Larger primitive data types (like double, long, float) must be cast to smaller types
(like int, short, byte) manually.
Data loss can occur if the larger type's value exceeds the range of the smaller type.
4. Type Casting Syntax
Implicit (Widening): This is automatically handled by the compiler. No special
syntax is required.
Explicit (Narrowing): This requires a cast operator (type) to specify the target type.
Example of Syntax for Explicit Casting:
int a = 10;
byte b = (byte) a; // Casting int to byte (explicit)
CONSTRUCTORS IN JAVA:
In Java, constructors are special methods that are called when an object of a class is created.
Their primary role is to initialize the object's state (i.e., assign values to the instance
variables) when the object is created.
1. What is a Constructor?
A constructor is a method that:
Has the same name as the class it belongs to.
Does not have a return type (not even void).
Is invoked automatically when an object of the class is created.
Constructors are used to set the initial values of the object's instance variables or to perform
any setup steps required before the object is used.
2. Types of Constructors in Java
There are two main types of constructors in Java:
1. Default Constructor (No-Argument Constructor)
2. Parameterized Constructor
3. Default Constructor (No-Argument Constructor)
A default constructor is a constructor that takes no arguments. If you don't explicitly define
any constructors in your class, Java provides a default constructor for you, which does
nothing but create the object.
If you do define a constructor with parameters, the default constructor is not automatically
provided.
Syntax:
class ClassName {
// Default constructor
public ClassName() {
// Initialization code (if any)
}
}
Example:
class Car {
String color;
String model;
// Default constructor
public Car() {
color = "Red";
model = "Toyota";
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Default constructor is called
car1.display();
}
}
Output:
Car Model: Toyota
Car Color: Red
In this example, when the Car object car1 is created using the default constructor, the color
and model fields are initialized to "Red" and "Toyota", respectively.
4. Parameterized Constructor
A parameterized constructor is a constructor that accepts arguments to initialize an object
with specific values at the time of its creation. This allows you to create objects with different
initial states.
Syntax:
class ClassName {
public ClassName(dataType parameter1, dataType parameter2) {
// Initialization code
}
}
Example:
class Car {
String color;
String model;
// Parameterized constructor
public Car(String c, String m) {
color = c;
model = m;
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Blue", "Honda"); // Parameterized constructor is called
car1.display();
Car car2 = new Car("Black", "Ford"); // Another object with different values
car2.display();
}
}
Output:
Car Model: Honda
Car Color: Blue
Car Model: Ford
Car Color: Black
In this example:
The Car class has a parameterized constructor that takes two arguments (String c,
String m).
Each object created with the constructor can have its own color and model values set
at the time of object creation.
5. Constructor Overloading
In Java, you can define multiple constructors with different parameter lists within the same
class. This is known as constructor overloading. It allows you to create objects in different
ways (e.g., with or without arguments).
Syntax:
class ClassName {
// Constructor with no parameters
public ClassName() {
// Initialization code
}
// Constructor with one parameter
public ClassName(dataType param1) {
// Initialization code
}
// Constructor with two parameters
public ClassName(dataType param1, dataType param2) {
// Initialization code
}
}
Example:
class Car {
String color;
String model;
// Constructor with no parameters
public Car() {
color = "Red";
model = "Toyota";
}
// Constructor with one parameter
public Car(String c) {
color = c;
model = "Unknown";
}
// Constructor with two parameters
public Car(String c, String m) {
color = c;
model = m;
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
car1.display();
Car car2 = new Car("Blue"); // Calls constructor with one parameter
car2.display();
Car car3 = new Car("Black", "Ford"); // Calls constructor with two parameters
car3.display();
}
}
Output:
Car Model: Toyota
Car Color: Red
Car Model: Unknown
Car Color: Blue
Car Model: Ford
Car Color: Black
In this example:
The Car class has three constructors: one with no parameters, one with one parameter
(color), and one with two parameters (color and model).
Based on how many arguments are passed when creating the object, the
corresponding constructor is invoked.
7. Constructor vs Method
Constructors and methods might appear similar, but they have key differences:
Overloading Yes, can have multiple constructors Yes, can have multiple methods
static {
count = 10; // Static block is executed once when the class is loaded
System.out.println("Static block is executed. Count = " + count);
}
public static void main(String[] args) {
System.out.println("Main method is executed.");
}
}
Output:
Static block is executed. Count = 10
Main method is executed.
The static block is executed before the main() method.
The static block is useful for any initialization that needs to be done when the class is
first loaded but before any instances are created.
3. Static Data (Static Variables)
Static data refers to static variables or class variables in Java. These are variables that are
shared among all instances of a class. They belong to the class itself, rather than to any
specific object. As a result, static variables are initialized only once and are shared across all
objects of the class.
Characteristics of Static Variables:
A static variable is declared using the static keyword.
It is shared by all objects of the class (i.e., there is only one copy of the static variable
for the entire class, regardless of how many objects are created).
Static variables can be accessed directly using the class name or through an object.
Syntax:
class ClassName {
static dataType variableName; // Static variable
}
Example of Static Data:
class Counter {
static int count = 0; // Static variable
Declaration Defined without static keyword Defined with the static keyword
Memory Each object has its own copy of Only one copy exists for the entire class
Allocation instance variables (shared by all objects)
Memory Efficiency Less efficient for modifications More efficient for modifications
Usage Ideal for constant strings Ideal for frequent string manipulation
Feature String StringBuffer