0% found this document useful (0 votes)
16 views36 pages

Unit 2

Uploaded by

thannushreey30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views36 pages

Unit 2

Uploaded by

thannushreey30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject: Object Oriented Programming using JAVA

Unit 2

Unit-2
Control statements, Classes, Objects and Methods
Topic 1: Introduction
A Java program is a set of statements, which are normally executed sequentially in the order in
which they appear. This happens when options or repetitions of certain calculations are not
necessary. However, in practice, we have a number of situations, where we may have to change
the order of execution of statements based on certain conditions, or repeat a group of statements
until certain specified conditions are met. This involves a kind of decision making to see
whether a particular condition has occurred or not and then direct the computer to execute
certain statements accordingly.
When a program breaks the sequential flow and jumps to another part of the code, it is called
branching. When the branching is based on a particular condition, it is known as conditional
branching. If branching takes place without any decision, it is known as unconditional
branching.
Java language possesses such decision making capabilities and supports the following
statements known as control or decision making statements.
1. if statement
2. switch statement
3. Conditional operator statement
In this Chapter, we shall discuss the features, capabilities and applications of these statements
which are classified as selection statements.

1
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 2: Decision making with if statement


Decision-making statements are fundamental constructs in programming that allow you to
control the flow of execution based on certain conditions. They enable your program to make
choices and execute different blocks of code depending on whether a specified condition
evaluates to true or false.
1. The if Statement
Concept
The if statement is the simplest decision-making statement. It evaluates a boolean expression
(a condition that results in either true or false). If the condition is true, the block of code
immediately following the if statement is executed. If the condition is false, the block of code
is skipped, and the program continues with the statements after the if block.
Syntax
if (condition) {
// Code to be executed if the condition is true
}
• condition: A boolean expression that evaluates to true or false.
• { ... }: The code block (or body) that will be executed if the condition is true. If there's only
one statement, the curly braces are optional but recommended for clarity and to avoid errors
when adding more statements later.
Flowchart

Simple Program: Check if a Number is Positive


public class IfStatementDemo {
public static void main(String[] args) {
int number = 10;

// Check if the number is positive


if (number > 0) {
System.out.println("The number is positive.");
}

System.out.println("This statement is always executed.");


}
}
Output:
The number is positive.
This statement is always executed.

2
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 3: The if-else Statement


The if-else statement provides two possible paths of execution. It evaluates a boolean condition.
If the condition is true, the code block within the if part is executed. If the condition is false,
the code block within the else part is executed. Only one of the two blocks will ever be
executed.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Flowchart

Simple Program: Check if a Number is Even or Odd


public class IfElseStatementDemo {
public static void main(String[] args) {
int number = 7;

// Check if the number is even or odd


if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}

System.out.println("Decision complete.");
}
}
Output:
7 is an odd number.
Decision complete.

3
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 4: Nesting of if-else Statements


Nesting if-else statements means placing one if or if-else statement inside another if or else
block. This allows for more complex decision-making scenarios where a condition needs to be
evaluated only after another condition has already been met. You can create hierarchies of
conditions.
Syntax
if (condition1) {
// Code for condition1 is true
if (condition2) {
// Code for condition1 is true AND condition2 is true
} else {
// Code for condition1 is true AND condition2 is false
}
} else {
// Code for condition1 is false
if (condition3) {
// Code for condition1 is false AND condition3 is true
} else {
// Code for condition1 is false AND condition3 is false
}
}
Flowchart

Simple Program: Determine Eligibility for Discount based on Age and Purchase Amount
public class NestedIfElseDemo {
public static void main(String[] args) {
int age = 25;
double purchaseAmount = 120.0;

// Check eligibility for discount


if (age >= 18) {

4
Subject: Object Oriented Programming using JAVA
Unit 2

System.out.println("Eligible for general purchase.");


if (purchaseAmount >= 100.0) {
System.out.println("You get a 10% discount on your purchase!");
} else {
System.out.println("No purchase amount discount applied.");
}
} else {
System.out.println("Must be 18 or older to make a purchase.");
}

System.out.println("Program finished.");
}
}
Output (for age = 25, purchaseAmount = 120.0):
Eligible for general purchase.
You get a 10% discount on your purchase!
Program finished.
Output (for age = 16, purchaseAmount = 50.0):
Must be 18 or older to make a purchase.
Program finished.

5
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 5: The else-if Ladder


The else-if ladder (also known as if-else if-else) is used when you need to check multiple
conditions sequentially. It allows you to define a series of conditions, and as soon as one
condition evaluates to true, its corresponding block of code is executed, and the rest of the
ladder is skipped. If none of the if or else if conditions are true, the final else block (if present)
is executed as a default.
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false AND condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false AND condition3 is true
} else {
// Code to execute if all preceding conditions are false (optional)
}
Flowchart

Simple Program: Assign a Grade Based on Score


public class ElseIfLadderDemo {
public static void main(String[] args) {
int score = 78; // Example score

if (score >= 90) {


System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {

6
Subject: Object Oriented Programming using JAVA
Unit 2

System.out.println("Grade: F");
}

System.out.println("Grading complete.");
}
}
Output (for score = 78):
Grade: C
Grading complete.
Output (for score = 95):
Grade: A
Grading complete.

7
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 6: The switch Statement


The switch statement is a control flow statement that allows a variable to be tested for equality
against a list of values. It provides an alternative to a long if-else if-else ladder when you have
many possible execution paths based on the value of a single variable. The switch statement
works with byte, short, char, int, String (since Java 7), enums, and wrapper classes of primitive
types (Byte, Short, Character, Integer).
Syntax
Java
switch (expression) {
case value1:
// Code to execute if expression matches value1
break; // Important: Exits the switch
case value2:
// Code to execute if expression matches value2
break;
// ... more case labels
default:
// Code to execute if expression doesn't match any case (optional)
// No break needed here, as it's the last block
}
• expression: The variable whose value is being tested.
• case valueN: A case label followed by a literal value. If expression matches valueN, the
code under this case is executed.
• break;: The break keyword is crucial. It causes the program to exit the switch statement
once a match is found and its code executed. Without break, execution would "fall through"
to the next case label.
• default:: The default block is optional. It is executed if the expression does not match any
of the case values. It's similar to the final else in an if-else if ladder.
Flowchart

8
Subject: Object Oriented Programming using JAVA
Unit 2

Simple Program: Display Day of the Week


public class SwitchStatementDemo {
public static void main(String[] args) {
int dayOfWeek = 3; // 1 for Monday, 2 for Tuesday, etc.

switch (dayOfWeek) {
case 1:
System.out.println("It's Monday!");
break;
case 2:
System.out.println("It's Tuesday!");
break;
case 3:
System.out.println("It's Wednesday!");
break;
case 4:
System.out.println("It's Thursday!");
break;
case 5:
System.out.println("It's Friday!");
break;
case 6:
System.out.println("It's Saturday!");
break;
case 7:
System.out.println("It's Sunday!");
break;
default:
System.out.println("Invalid day number.");
}

System.out.println("Have a great day!");


}
}
Output (for dayOfWeek = 3):
It's Wednesday!
Have a great day!
Output (for dayOfWeek = 9):
Invalid day number.
Have a great day!

9
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 7: The Conditional Operator


In Java, the conditional operator (?:) is used as a shorthand for the if-else statement. It is the
only ternary operator in Java because it takes three operands.
Syntax
variable = (condition) ? value_if_true : value_if_false;
1. The condition is evaluated.
2. If it is true, the operator returns value_if_true.
3. If it is false, the operator returns value_if_false.
1) Example 1: Find Maximum Number
public class ConditionalUsingIfElse {
public static void main(String[] args) {
int a = 15, b = 25;
int max;

// Using if-else instead of conditional operator


if (a > b) {
max = a;
} else {
max = b;
}

System.out.println("The maximum number is: " + max);


}
}
Output
The maximum number is: 25
2) Example 2: Check Even or Odd
public class EvenOddIfElse {
public static void main(String[] args) {
int num = 10;

if (num % 2 == 0) {
System.out.println(num + " is Even");
} else {
System.out.println(num + " is Odd");
}
}
}
Output
10 is Even

10
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 8: The while Statements


The while statement is a looping or iterative control structure in Java that allows a block of
code to be executed repeatedly as long as a given condition is true.
➢ Syntax:
while (condition) {
// statements to be executed repeatedly
}
➢ How It Works
1. The condition is checked first.
2. If the condition is true, the loop body executes.
3. After execution, the condition is checked again.
4. This process repeats until the condition becomes false.
5. When the condition is false, the loop stops.
➢ Flowchart

• It is a pre-test loop (condition is checked before execution).


• If the condition is false at the beginning, the loop will not run even once.
• Used when the number of iterations is not known in advance.
➢ Process of while Statement in Java (Step by Step)
The while loop follows a simple process:
Step-by-Step Process
1. Initialization
o Set up a starting value for the loop control variable.
o Example: int i = 1;
2. Condition Checking
o Before each iteration, the while loop checks the condition inside
parentheses ( ).
o Example: while (i <= 5)
3. Execute Loop Body
11
Subject: Object Oriented Programming using JAVA
Unit 2

o If the condition is true, the block { } of statements executes.


o Example: System.out.println(i);
4. Update Control Variable
o After executing, update the control variable (increment/decrement) to
eventually make the condition false.
o Example: i++;
5. Repeat
o Go back to Step 2 (condition checking).
o The loop keeps running until the condition becomes false.
6. Exit Loop
o When the condition is false, the loop stops, and the program continues with
the next statements after the loop.
Example:
public class WhileProcess {
public static void main(String[] args) {
int i = 1; // Step 1: Initialization

while (i <= 3) { // Step 2: Condition checking


System.out.println("i = " + i); // Step 3: Execute body
i++; // Step 4: Update variable
} // Step 5: Repeat until condition is false

System.out.println("Loop finished."); // Step 6: Exit loop


}
}
How It Works Here
• Initially i = 1 → condition i <= 3 is true → prints i = 1 → i becomes 2.
• Now i = 2 → condition true → prints i = 2 → i becomes 3.
• Now i = 3 → condition true → prints i = 3 → i becomes 4.
• Now i = 4 → condition false → loop exits → prints "Loop finished.".

Example 1: Print Numbers 1 to 5


public class WhileExample {
public static void main(String[] args) {
int i = 1; // initialization

while (i <= 5) { // condition


System.out.println(i);
i++; // increment
}
}
}
Output
1
2
3
4
5

12
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 9: The do-while Statement


The do-while loop is a looping control statement in Java that executes a block of code at
least once, and then continues to execute it as long as the condition is true.
It is similar to the while loop, but the condition is checked after executing the loop body,
not before.
Hence, the loop always runs at least one time, even if the condition is false at the beginning.
➢ Syntax
do {
// statements to be executed
} while (condition);

Note: The condition ends with a semicolon (;).


➢ How It Works
1. The block of code inside { } executes first.
2. Then the condition in while(condition) is checked.
3. If the condition is true, the loop repeats.
4. If the condition is false, the loop stops.

• Condition is checked after executing the loop.


• Ensures the loop body executes at least once, even if the condition is false initially.
• Ends with a semicolon (;) after the while(condition).
➢ Flowchart:

➢ Step-by-Step Process
1. Initialization – Set up the loop control variable.
2. Execute Loop Body – Run the block of code at least once.
3. Condition Check – After execution, check the condition.
4. Repeat or Exit – If true → repeat, if false → exit.

13
Subject: Object Oriented Programming using JAVA
Unit 2

➢ Example Program: Print Numbers 1 to 5


public class DoWhileExample {
public static void main(String[] args) {
int i = 1; // Step 1: Initialization

do {
System.out.println("i = " + i); // Step 2: Execute loop body
i++; // Update variable
} while (i <= 5); // Step 3: Check condition, Step 4: Repeat or Exit

System.out.println("Loop finished."); // After loop ends


}
}
Output
i=1
i=2
i=3
i=4
i=5
Loop finished.
➢ Step-by-Step Process for This Example
1. i = 1 → Loop enters and prints i = 1.
2. i increments to 2 → condition i <= 5 is true → repeats.
3. i = 2 → prints → increments to 3 → condition true → repeats.
4. This continues until i = 6.
5. Condition i <= 5 becomes false → loop exits → prints "Loop finished.".
➢ Example Where Condition is False Initially
public class DoWhileFalseExample {
public static void main(String[] args) {
int i = 10;

do {
System.out.println("This prints at least once, even if condition is false!");
} while (i < 5); // condition is false
}
}
Output
This prints at least once, even if condition is false!
➢ Difference Between while and do-while
Feature while Loop do-while Loop
Condition Check Before executing the loop body After executing the loop body
Minimum Execution May execute 0 times Executes at least 1 time
Syntax End No semicolon after loop Requires a semicolon after while

14
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 10: The for statement


➢ The for loop in Java is a control structure that allows you to repeat a block of code a
specific number of times.
➢ It is mostly used when you know in advance how many times you want to execute the
statements.
➢ Syntax
for (initialization; condition; update) {
// statements to execute repeatedly
}
➢ Explanation of Parts
1. Initialization → Runs once, sets the starting point.
2. Condition → Checked before every iteration; if true, loop continues; if false, loop
stops.
3. Update → Changes the control variable (increment/decrement) after each iteration.
➢ Flowchart:

➢ How It Works (Process)


1. Initialize the loop variable.
2. Check the condition:
o If true, execute the loop body.
o If false, exit the loop.
3. Update the loop variable.
4. Repeat steps 2–3 until the condition becomes false.

15
Subject: Object Oriented Programming using JAVA
Unit 2

➢ Example Program: Print Numbers 1 to 5


public class ForExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { // initialization; condition; update
System.out.println("Number: " + i); // loop body
}
}
}
➢ Step-by-Step Execution
1. i = 1 → condition i <= 5 → true → print Number: 1 → i++ → i = 2.
2. i = 2 → condition true → print Number: 2 → i++.
3. Repeats for i = 3, 4, 5.
4. When i = 6, condition false → loop stops.
➢ Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
➢ Example 2: Print Even Numbers (1–10)
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
}
}
Output:
2
4
6
8
10
• Used when the number of iterations is known.
• Combines initialization, condition, and update in one line.
• Can also be written in reverse (counting down).

16
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 11: Jumps in Loops in Java


In Java, loops (for, while, do-while) are used to repeat a block of code.
Sometimes, we may want to alter the normal flow of the loop (for example, stop it early, skip
some steps, or exit a method).
Java provides jump statements to control this flow.
The three main jump statements used with loops are:
1. break
2. continue
3. return
1. Break Statement
• The break statement is used to exit the loop immediately when a certain condition is
met.
• After break executes, control comes out of the loop completely, and execution
continues with the next statement after the loop.
How it works step by step:
1. The loop starts normally.
2. Each iteration checks the condition.
3. When break is encountered, the loop terminates immediately.
4. Control jumps to the first statement after the loop.
Syntax:
break;
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // exit loop when i is 3
}
System.out.println("i = " + i);
}
System.out.println("Loop ended.");
}
}
Output:
i=1
i=2
Loop ended.
The loop stops when i == 3.
2. Continue Statement
• The continue statement is used to skip the current iteration of the loop.
• The loop itself does not end; instead, it moves to the next iteration.
➢ How it works step by step:
1. The loop starts and runs normally.
2. When continue is encountered, the remaining statements in that iteration are skipped.
3. The loop goes back to check the condition for the next iteration.
Syntax:
continue;
Example:
public class ContinueExample {

17
Subject: Object Oriented Programming using JAVA
Unit 2

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skip this iteration
}
System.out.println("i = " + i);
}
System.out.println("Loop completed.");
}
}
Output:
i=1
i=2
i=4
i=5
Loop completed.
The value 3 is skipped.

3. Return Statement
• The return statement is used to exit from the current method.
• When used inside a loop, it terminates the method completely, not just the loop.
➢ How it works step by step:
1. The loop starts normally.
2. When return is encountered, the method ends immediately.
3. No further code in the method is executed.
Syntax:
return;
Example:
public class ReturnExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
return; // exit method completely
}
System.out.println("i = " + i);
}
// This line will never be executed
System.out.println("Loop ended.");
}
}
Output:
i=1
i=2
When i == 3, the entire main method ends, so "Loop ended." is never printed.

18
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 12: Defining a Class


In Java, a class is a fundamental building block of object-oriented programming. It acts as a
blueprint or template from which individual objects are created. A class defines the
properties (also called fields or attributes) and behaviors (methods) that the objects of that
class will have. For example, consider a Student class; it may have properties such as name
and age and behaviors such as displayInfo(). These properties store data, and the
methods define actions that can be performed on that data.
To define a class in Java, we use the class keyword followed by the class name. Inside the
class, we can declare fields and methods. Once a class is defined, we can create objects of that
class using the new keyword. An object is an instance of a class and represents a real-world
entity. For example, if Student is a class, then Student s1 = new Student();
creates an object s1 of type Student. Using this object, we can access fields and call methods
defined in the class.
The basic syntax of a class is:
class ClassName {
// fields
dataType variableName;

// methods
returnType methodName(parameters) {
// code
}
}
For example, consider the following program:
class Student {
String name;
int age;

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class StudentTest {


public static void main(String[] args) {
Student s1 = new Student(); // creating an object
s1.name = "Sowmya"; // setting field values
s1.age = 20;
s1.displayInfo(); // calling method
}
}
Output:
Name: Sowmya
Age: 20

19
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 13: Adding variables


In Java, variables declared inside a class are used to define the properties or state of objects
created from that class. These variables store data and can have different lifetimes, scopes, and
behaviors depending on how they are declared. The three main types of variables in a class are
instance variables, static variables, and local variables. Let us understand each type in detail.
1. Instance Variables
Instance variables are variables that are declared inside a class but outside any method,
constructor, or block. They belong to individual objects of the class, which means that every
object created from the class gets its own separate copy of these variables. The values stored
in these variables can differ from one object to another, and any change in one object’s
variable does not affect the other objects. Instance variables are automatically assigned
default values if they are not explicitly initialized. For example, numeric variables default
to 0, objects default to null, and booleans default to false. These variables are accessed
through objects using the dot (.) operator.
Syntax for Instance Variables:
class ClassName {
// Instance Variable
dataType variableName;

void method() {
// using the instance variable
}
}
2. Static Variables
Static variables are declared using the keyword static inside a class but outside any method,
constructor, or block. Unlike instance variables, static variables do not belong to any
particular object; instead, they belong to the class itself. This means that there is only one
copy of the static variable, and it is shared among all objects of the class. Changing the
value of a static variable through one object will reflect across all other objects. These
variables also have a default value if they are not explicitly initialized. Static variables can
be accessed directly using the class name, which makes them useful for storing common
properties that should be the same for every object, such as a school name or company
name.
Syntax for Static Variables:
class ClassName {
// Static Variable
static dataType variableName;

void method() {
// using static variable
}
}
3. Local Variables
Local variables are variables that are declared inside a method, constructor, or block. These
variables are created when the method or block is executed and are destroyed once the
execution is finished. They exist only within the scope of the method or block where they
are declared, meaning they cannot be accessed outside of it. Unlike instance and static
variables, local variables are not automatically initialized; therefore, the programmer must
assign them a value before using them. Local variables are mainly used to store temporary
data within methods.

20
Subject: Object Oriented Programming using JAVA
Unit 2

Syntax for Local Variables:


class ClassName {
void methodName() {
// Local Variable
dataType variableName = value;
// use local variable here
}
}
➢ Example Program Demonstrating All Three Types:
// Class Definition
class Student {
// Instance Variables
String name;
int age;

// Static Variable
static String college = "ABC University";

// Method with Local Variable


void display() {
// Local Variable
String course = "Computer Science";

// Displaying values
System.out.println("Name: " + name); // Instance variable
System.out.println("Age: " + age); // Instance variable
System.out.println("College: " + college); // Static variable
System.out.println("Course: " + course); // Local variable
}
}

// Main Class to Execute the Program


public class Main {
public static void main(String[] args) {
// Creating first object
Student s1 = new Student();
s1.name = "John";
s1.age = 20;

// Creating second object


Student s2 = new Student();
s2.name = "Alice";
s2.age = 22;

// Displaying details of both students


s1.display();
System.out.println("------------------");
s2.display();
}
}

21
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 14: Adding methods


In Java, a method is a block of code that performs a specific task and is defined inside a class.
Methods help in organizing the program into smaller, manageable sections and promote code
reusability. Adding methods to a class allows objects of that class to perform certain actions or
behaviors. Methods are executed only when they are called.
There are mainly two types of methods in a class: instance methods and static methods.
Additionally, we can also have methods with parameters, methods with return values, and
overloaded methods.
1. Instance Methods
Instance methods are defined without the static keyword. These methods operate on
instance variables and can access both instance and static variables of the class. To call an
instance method, we need to create an object of the class and use the dot (.) operator. These
methods define the behavior of individual objects.
Syntax for Instance Method:
class ClassName {
// Instance Method
returnType methodName() {
// code to execute
}
}
• returnType specifies the type of value the method returns (use void if no value is
returned).
• methodName is the name of the method.
• Inside the braces {}, we write the code that defines what the method does.
2. Static Methods
Static methods are declared with the keyword static. They belong to the class rather than to
a specific object, which means they can be called without creating an object. Static methods
can directly access only static variables and other static methods. If they need to access
instance variables, they must do so through an object.
Syntax for Static Method:
class ClassName {
// Static Method
static returnType methodName() {
// code to execute
}
}
Static methods are often used for utility functions or tasks that do not depend on object-
specific data.
3. Methods with Parameters and Return Values
Methods can take parameters (input values) and return results. Parameters are specified
inside the parentheses and allow data to be passed into the method. The return statement is
used to send a value back to the caller.
Syntax for Method with Parameters and Return Value
class ClassName {
returnType methodName(dataType parameter1, dataType parameter2) {
// use parameters
return value; // if returnType is not void
}
}

22
Subject: Object Oriented Programming using JAVA
Unit 2

Example:
// Class Definition
class Student {
// Instance Variables
String name;
int age;

// Method to set student details


void setDetails(String n, int a) {
name = n;
age = a;
}

// Method to display student details


void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Main Class
public class Main {
public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student();

// Using methods to set and display details


s1.setDetails("John", 20);
s1.displayDetails();
}
}
Output:
Name: John
Age: 20

23
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 15: Creating objects


In Java, a class is a blueprint for creating objects. An object is an instance of a class that
contains its own data (stored in instance variables) and can perform actions using its methods.
To use a class, we must create its objects.
Creating objects is a fundamental concept in Object-Oriented Programming (OOP) because it
allows us to work with real-world entities represented by classes.
➢ How to Create Objects in Java?
To create an object of a class, we use the new keyword followed by a call to the class
constructor.
General Syntax: ClassName objectName = new ClassName();
• ClassName is the name of the class.
• objectName is the reference variable that holds the object.
• new is a keyword that allocates memory for the object.
• ClassName() is the constructor that initializes the object.
➢ Steps Involved in Creating an Object
1. Declaration: A reference variable is declared to hold the object.
2. Instantiation: The new keyword is used to create the object.
3. Initialization: The constructor is called to initialize the object.
Example: Creating Objects
// Class Definition
class Student {
String name;
int age;

// Method to display details


void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Main Class
public class Main {
public static void main(String[] args) {
// Creating first object of Student
Student s1 = new Student();
s1.name = "John";
s1.age = 20;

// Creating second object of Student


Student s2 = new Student();
s2.name = "Alice";
s2.age = 22;

// Displaying details using objects


s1.display();
System.out.println("------------------");
s2.display();
}
}

24
Subject: Object Oriented Programming using JAVA
Unit 2

Output
Name: John
Age: 20
------------------
Name: Alice
Age: 22

25
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 16: Accessing class members


In Java, a class member refers to the variables (fields) and methods defined inside a class. To
use or access these members, we need to know the correct way to reference them. The way
we access class members depends on whether they are instance members or static members.
1. Accessing Instance Members
Instance members include instance variables and instance methods. These belong to
individual objects of a class. To access them, you must first create an object of that class
using the new keyword. Then, you use the object reference along with the dot (.) operator.
Syntax:
ClassName objectName = new ClassName();
objectName.instanceVariable;
objectName.instanceMethod();
Example:
class Student {
String name; // Instance variable
int age;

void display() { // Instance method


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student(); // Create object
s1.name = "John"; // Access instance variable
s1.age = 20;
s1.display(); // Call instance method
}
}
2. Accessing Static Members
Static members belong to the class itself, not to any specific object. They can be
accessed directly using the class name without creating an object. However, they can also
be accessed using an object reference (not recommended but allowed).
Syntax:
ClassName.staticVariable;
ClassName.staticMethod();
Example:
class Student {
static String college = "ABC University"; // Static variable

static void showCollege() { // Static method


System.out.println("College: " + college);
}
}

public class Main {


public static void main(String[] args) {
// Accessing static members using class name

26
Subject: Object Oriented Programming using JAVA
Unit 2

System.out.println(Student.college);
Student.showCollege();
}
}
3. Accessing Members Using this Keyword
The this keyword is used inside instance methods or constructors to refer to the current
object of the class. It helps to differentiate between instance variables and local variables
when they have the same name.
Example:
class Student {
String name;
int age;

Student(String name, int age) {


this.name = name; // 'this' refers to instance variable
this.age = age;
}

void display() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student("Alice", 22);
s1.display();
}
}
4. Access Modifiers and Accessing Members
Access to class members also depends on access modifiers:
• public – Accessible from anywhere.
• private – Accessible only within the same class.
• protected – Accessible within the same package and subclasses.
• default (no modifier) – Accessible only within the same package.
Example:
class Student {
String name; // Instance variable
int age;
static String college = "ABC"; // Static variable

void setDetails(String n, int a) { // Instance method


name = n;
age = a;
}

void displayDetails() { // Instance method


System.out.println("Name: " + name);
System.out.println("Age: " + age);

27
Subject: Object Oriented Programming using JAVA
Unit 2

static void showCollege() { // Static method


System.out.println("College: " + college);
}
}

public class Main {


public static void main(String[] args) {
// Accessing instance members using object
Student s1 = new Student();
s1.setDetails("John", 20);
s1.displayDetails();

System.out.println("---------------");

// Accessing static members using class name


System.out.println(Student.college);
Student.showCollege();
}
}
Output:
Name: John
Age: 20
---------------
ABC
College: ABC

28
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 17: Constructors


In Java, a constructor is a special method that is used to initialize objects of a class. When an
object is created using the new keyword, the constructor is automatically called to set up the
initial state of the object. Unlike normal methods, constructors have some special rules.
➢ Characteristics of Constructors
1. The constructor name must be the same as the class name.
2. Constructors do not have a return type, not even void.
3. They are automatically invoked when an object is created.
4. Constructors are mainly used to initialize instance variables.
5. A class can have multiple constructors (constructor overloading).
6. If no constructor is explicitly defined, Java provides a default constructor.
➢ Types of Constructors in Java
Java supports two main types of constructors:
1. Default Constructor
A default constructor is a constructor that does not take any parameters. It is provided by
Java if no constructor is defined, or you can explicitly define it. It assigns default values to
object variables.
Syntax:
class ClassName {
// Default Constructor
ClassName() {
// initialization code
}
}

2. Parameterized Constructor
A parameterized constructor takes arguments to initialize an object with specific values at
the time of creation.
Syntax:
class ClassName {
// Parameterized Constructor
ClassName(dataType parameter1, dataType parameter2) {
// initialization code using parameters
}
}
Example : Using a Default Constructor
class Student {
String name;
int age;

// Default Constructor
Student() {
name = "Unknown";
age = 0;
}

void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

29
Subject: Object Oriented Programming using JAVA
Unit 2

public class Main {


public static void main(String[] args) {
// Object creation calls the default constructor
Student s1 = new Student();
s1.display();
}
}

30
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 18: Method Overloading


In Java, method overloading is a feature that allows a class to have more than one method
with the same name but different parameter lists. This helps in creating methods that
perform similar tasks but with different inputs. Method overloading increases the readability
and flexibility of the program.
➢ Definition:
Method overloading occurs when two or more methods in the same class have:
• The same method name,
• Different number of parameters, or
• Different types of parameters, or
• Different order of parameters.
➢ Key Points About Method Overloading
1. Methods must have the same name but a different parameter list (number or type of
parameters must be different).
2. Method overloading is resolved at compile time (known as compile-time
polymorphism).
3. Changing only the return type does not constitute method overloading; parameters must
differ.
4. Overloaded methods can have different access modifiers and return types as long as
their parameter list is different.
➢ Syntax of Method Overloading
class ClassName {
// First method
returnType methodName(dataType param1) {
// code
}

// Overloaded method with different parameters


returnType methodName(dataType param1, dataType param2) {
// code
}
}
Example : Simple Method Overloading
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


double add(double a, double b) {
return a + b;
}
}

31
Subject: Object Oriented Programming using JAVA
Unit 2

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Calling different overloaded methods


System.out.println("Sum of two integers: " + calc.add(10, 20));
System.out.println("Sum of three integers: " + calc.add(10, 20, 30));
System.out.println("Sum of two doubles: " + calc.add(5.5, 4.5));
}
}
Output:
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 10.0
Difference Between Method Overloading and Method Overriding
Feature Method Overloading Method Overriding
Definition Same method name with different Same method name, same
parameter list in the same class. parameters, but defined in
subclass.
Polymorphism Compile-time polymorphism. Runtime polymorphism.
Type
Access Happens within the same class. Happens across superclass and
subclass.
Return Type Can be different if parameters Must be same (or covariant).
differ.

32
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 19: Static Members


In Java, the keyword static is used to create members that belong to the class rather than to any
specific object. This means that static members are shared by all objects of the class. Static
members are loaded into memory only once when the class is loaded, making them memory-
efficient and easy to access without creating objects.
➢ Types of Static Members
Static members can be:
1. Static Variables (also known as Class Variables)
2. Static Methods
3. Static Blocks
4. Static Nested Classes (optional advanced topic)
1. Static Variables
A static variable belongs to the class, not to objects. All objects share the same copy of the
static variable. Changing the value of a static variable in one object affects all other objects.
Syntax:
class ClassName {
static dataType variableName = value;
}

2. Static Methods
A static method belongs to the class rather than any specific object. Therefore, it can be called
using the class name without creating an object. Static methods can only directly access static
variables and other static methods. They cannot use the this keyword because this refers to an
object, and static methods do not belong to any particular object.
Syntax:
class ClassName {
static returnType methodName() {
// code
}
}

3. Static Blocks
A static block is a block of code inside a class that runs only once when the class is loaded. It
is typically used to initialize static variables.
Syntax:
class ClassName {
static {
// initialization code
}
}
Example:
class Student {
String name; // Instance variable
int age;
static String college = "ABC University"; // Static variable

// Constructor
Student(String n, int a) {
name = n;
age = a;

33
Subject: Object Oriented Programming using JAVA
Unit 2

// Instance Method
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("College: " + college); // Accessing static variable
}

// Static Method
static void showCollege() {
System.out.println("College Name: " + college);
}

// Static Block
static {
System.out.println("Static Block Executed: College initialized.");
}
}

public class Main {


public static void main(String[] args) {
// Creating objects
Student s1 = new Student("John", 20);
Student s2 = new Student("Alice", 22);

// Displaying object details


s1.display();
System.out.println("------------------");
s2.display();

System.out.println("------------------");

// Accessing static method directly with class name


Student.showCollege();

// Changing static variable using class name


Student.college = "XYZ University";
System.out.println("After Changing College:");
s1.display();
}
}
Output:
Static Block Executed: College initialized.
Name: John
Age: 20
College: ABC University
------------------
Name: Alice
Age: 22

34
Subject: Object Oriented Programming using JAVA
Unit 2

College: ABC University


------------------
College Name: ABC University
After Changing College:
Name: John
Age: 20
College: XYZ University

35
Subject: Object Oriented Programming using JAVA
Unit 2

Topic 20: Nesting of Methods


In Java, nesting of methods refers to the process where one method is called from another
method within the same class. Although Java does not allow defining a method inside another
method (like in some other languages), it allows calling one method from another. This is
known as method nesting.
➢ Concept of Nested Method Calls
When a method is called from within another method, control is transferred to the called
method, and after its execution, the control returns to the calling method. This technique
improves code reusability and avoids writing duplicate code.
➢ Key Points About Nested Method Calls
1. Java does not allow declaring a method inside another method, but you can call a
method from another method.
2. The calling method can pass arguments to the called method if required.
3. After the called method completes, control returns to the calling method.
4. This is commonly used to organize complex tasks into smaller methods.
Syntax
class ClassName {
void method1() {
// code
method2(); // calling another method
}
void method2() {
// code executed when method2 is called
}
}

Example 1: Simple Nesting of Methods


class Calculator {

// Method to start calculation


void startCalculation() {
System.out.println("Starting calculation...");
addNumbers(); // Calling another method
}
// Another method being called
void addNumbers() {
int a = 10, b = 20;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.startCalculation(); // Calling the first method
}
}
Output
Starting calculation...
Sum: 30

36

You might also like