0% found this document useful (0 votes)
3 views

Java Notes Till Mids

The document provides an overview of Object Oriented Programming (OOP) concepts, including classes, objects, constructors, and methods. It explains how to create and use classes, the importance of maintainable design, and the principles of method and constructor overloading. Additionally, it covers the syntax for defining classes and methods, as well as the use of static variables in OOP.

Uploaded by

mujrim36102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Notes Till Mids

The document provides an overview of Object Oriented Programming (OOP) concepts, including classes, objects, constructors, and methods. It explains how to create and use classes, the importance of maintainable design, and the principles of method and constructor overloading. Additionally, it covers the syntax for defining classes and methods, as well as the use of static variables in OOP.

Uploaded by

mujrim36102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

CC-121 Object Oriented Programming

20 Object Oriented Model:


 Object oriented design is related to real world. In real world everything (living or non-living) is
classify in different classes according to their common attributes and behaviours.
 So big problem is decomposed into different classes and objects.
 In object oriented model class is a basic unit of decomposition.
 Every problem is decomposed according to common attributes and behaviours.

21 Class:
 Class is a template or pattern or model that is used to create object.
 Class is user defined data type.
 Class has two types of Members:

67
CC-121 Object Oriented Programming

22 Maintainable Design
In object oriented design the data is decentralized. Every class has its own data members. Due to this
the object oriented design and program is easily more maintainable.

22.1 General Syntax of class:

class ClassName
{
// Class_Level_Variables (Both Instance and Shared Variables)
dataType VariableName;

// Behaviours / Methods
returnType methodName(List_of_Parameters)
{
return variable/expression/literal; // Method Body
}
// ……More methods
}

23 Object:
 Everything which has some properties/attributes (data members of a class) and behaviors
(methods of a class) is called object.
 Object is an instance of a class. Every object/instance of the class maintain its own copy of data
members or instance variables of the class.
 Everything in real world is an object whether living or non-living.
 Every object is classified according to their features and behaviours.
 The object having common features and behaviours belongs to same class.

68
CC-121 Object Oriented Programming

How to create Rectangle class with states and behaviors

Step 1: Step 2:

Create class Add States/instance


New datatype
Rectangle is created in variables
class Rectangle
the form of class
class Rectangle
{
{
double width;
} Instance variables
double height;
Features or attributes
}

Step 3:
Add behaviors/methods
class Rectangle
{
double width;
double height;
double area()
method
{
return width * height;
}
}

69
CC-121 Object Oriented Programming

How to access Rectangle class states and behaviors in class inside main method:

Step 1:
Synatx:
Create Object
ClassName varName;
class MainDemoRectangle
varName = new ClassName();
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
// or can be split into Two Statements
Rectangle r1;
allocates stack memory to r1 at
r1=new Rectangle(); the time of declaration.

}
new operator used to allocate
heap memory for class level
variables at runtime.

Memory Map:

Rectangle r1;
main() Stack

r1 null

r1=new Rectangle();

'0000

main() Stack
default constructor
Heap initializes the real
width 0.0 type variables with
height 0.0 default values 0.0
area()
r1 null 0x001A 0x001A

70
CC-121 Object Oriented Programming

Step 2:
Syntax:
Access members (variables and methods)
objectName.InstanceVariable/method;
class MainDemoRectangle
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
r1.width= 5.8;
r1.height= 60.5;
double ar = r1.area();
System.out.println(r1.width); // 5.8
System.out.println(r1.height); // 60.5
System.out.println(ar);
}
}

Memory Map:
'0000
main() Stack
Heap

width 5.8
height 60.5
area()
r1 null 0x001A 0x001A

71
CC-121 Object Oriented Programming

Output of the following program:

24 Class Diagram | Unified Modeling Language (UML)


24.1 UML Class Notation
class notation is a graphical representation used to depict classes and their relationships in object-oriented
modeling.

1. Class Name:

The name of the class is typically written in the top compartment of the class box and is centered.

F IGURE 1T HE UML CLASS DIAGRAM


2. Attributes:

Attributes, also known as properties or fields, represent the data members of the class. They are listed in the
second compartment of the class box.

F IGURE 2 A CLASS AND ITS ATTRIBUTES


Every object of the class has a specific value for every attribue. The object's name starts with a lowercase letter,
followed by a colon, then the class name, and the entire name is underlined.

72
CC-121 Object Oriented Programming

F IGURE 3 AN OBJECT HAS A SPECIFIC VALUE FOR EACH ONE OF ITS CLASS 'S ATTRIBUTES
Methods:

Methods, also known as functions or operations, represent the behavior or functionality of the class. They are
listed in the third compartment of the class box.

F IGURE 4 CLASS METHOD

73
CC-121 Object Oriented Programming

25 Constructor:
 Constructor is a special method.
 Constructor name is similar as class Name.
 Constructor having no return type. Not even a void.
 Constructor is called at the time of object creation.
 The major purpose of constructor is to initialize the class level variables specially
instance variable of an object.
 When no constructor is available in a class, the default constructor is called by Java
Runtime environment.
 The default constructor initializes the instance variable with default values:

 integer type variables with zero.


 real type variables with 0.0.
 boolean type variables with false.
 char type variables with \0 character.
 any other class type variable with null reference.

74
CC-121 Object Oriented Programming

/***Limitation: No Constructor is available in your Own Class. Then default constructor is


called by JRE and Initialize the data members in default way. ***/

class A
{
int x;
double y;
char c;
A o;
boolean b;
void show()
{
System.out.println(" x="+x + "\t" + "y=" +y + "\t" + "c=" +c + "\t" + "o=" +o + "\t"
+ "b=" +b);
}
}
class MainDemo
{
public static void main(String[] arg)
{
A obj = new A();
default constructor is called
obj.show();
}
}
Output of the following program:

75
CC-121 Object Oriented Programming

/***Create Constructor***/ In the presence of constructor in your own class No default


constructor is called by JRE. The available constructor of our own class is called by JRE.

class A
{
int x;
double y;

Constructor name is similar as class name.


A()
{
x=10;
y=5.6;
}

void show()
{
System.out.println(" x="+ x + "\t" + "y=" + y);
}
}
class MainDemo1
{
public static void main(String[] arg)
{
A obj = new A();
obj.show();
}
}

Output of the following program:

76
CC-121 Object Oriented Programming

/***Limitation: Without parameter constructor initialize instance variables for each object of
the class A with same values. Solution: Use Parameterized Constructor ***/
class A
{
int x;
double y;
A(int i, double j)
{ Formal parameters

x=i;
y=j;
}
void show()
{
System.out.println(" x="+ x + "\t" + "y=" + y);
}
}
class MainDemo3
{
public static void main(String[] arg)
{
A obj = new A(10,20.4);
Actual parameters
obj.show();
} With parameterized constructor, every object is created with
customized values as happened in real world.
}

Output of the following program:

77
CC-121 Object Oriented Programming

/***Limitation: Every object of class A created with same number of Parameters


Solution: Constructor Overloading ***/

26 Constructor overloading:
When a class having more than one constructor, then call of constructor is resolved with
number of parameters or type of parameters or with both.
Benefit:
Every object created by the programmer by calling the relevant constructor according to the
requirement.

class A
{
int x;
double y;
A()
{
x = 10;
y = 5.6;
}
A(int i, double j)
{
x = i;
y = j;
}
A(double i)
{
x = (int) i; // Explicit typecasting
y = i;

78
CC-121 Object Oriented Programming

}
void show()
{
System.out.println("x = " + x + "\t” + “y = " + y);
}
}
public class MainDemo4
{
public static void main(String[] args)
{
A obj1 = new A(600, 0.75); // Constructor with int and double
A obj2 = new A(10.5); // Constructor with double
A obj3 = new A(); // Default constructor
obj1.show();
obj2.show();
obj3.show();
}
}
Output of the following program:

79
CC-121 Object Oriented Programming

27 Method:
 In general method is a process that takes input and manipulate the data and provide
output.
 In java, a method is a block of code that performs a specific task and is defined within a
class. It only runs /execute when it is called.

27.1 General Syntax of Method:

return_type method_name(list_of_parameters) Method Header

{ Method Signature = method name and a


return variable/expression/literal; parameter list.

Method Body

Return Type: Methods may return a value of a particular data type using the return statement.
If a method does not return any value, its return type is void.

List_of_parameters: List_of_parameters is a sequence of datatype and identifier pairs


separated by comma. Parameters are essentially variables that receive the value of arguments
passed to the method when it is called. List of parameters available in method definition is
called formal parameters.

27.2 Method Signature:


It consists of the method name and a parameter list.
 number of parameters
 type of the parameters
 order of the parameters
Note: The return type and exceptions are not considered as part of it.

80
CC-121 Object Oriented Programming

There are two important things to understand about returning values:

 The type of data returned by a method must be compatible with the return type

specified by the method. For example, if the return type of some method is boolean, you
could not return an integer.

 The variable receiving the value returned by a method must also be compatible with
the return type specified for the method.

27.3 Adding a Method That Takes Parameters:


class Test
{ List_of_parameter

// Program for square datatype of the parameter and variable name


Accepts one parameter of type double named n
double mySquare(double n)
return_type
{ method_name

return n * n;
}

Accepts two parameters:


// Program for sum x of type int

double sum(int x, double y) y of type double

{ Formal parameters
return x + y;
}

// Program for multiply


long multiply(int n, int m)
{
return (long) n * m;

81
CC-121 Object Oriented Programming

// Program for factorial


long factorial(int n)
{
long fact = 1;
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
return fact;
}

// Program for power


long myPower(int n, int p)
{
long pow = 1;
for (int i = 1; i <= p; i++)
{
pow = pow * n;
}
return pow;
}

// Program for pattern


void trianglePattern()
{
for (int r = 1; r <= 5; r++)
{

82
CC-121 Object Oriented Programming

for (int c = 1; c <= r; c++)


{
System.out.print("*");
}
System.out.print("\n");
}
}

// Program for lowercase


char lowerCase(char ch)
{
if (ch >= 'A' && ch <= 'Z')
{
ch = (char) (ch + 32);
}
return ch;
}

// Program for uppercase


char upperCase(char ch)
{
if (ch >= 'a' && ch <= 'z')
{
ch = (char) (ch - 32);
}
return ch;
}
}

83
CC-121 Object Oriented Programming

class MainDemoTestMethod
{
public static void main(String[] args)
{
Test o = new Test(); variable receiving the value returned by a method
double sqr = o.mySquare(6);
Actual Parameter
System.out.println(6 + " Square is " + sqr);
double sm = o.sum(7, 2.6);
Actual Parameters
System.out.println("The Sum of x and y is " + sm);

long mul = o.multiply(99999999, 999999);


System.out.println(mul + " is the answer of multiply");
long factAns = o.factorial(10);
System.out.println(10 + " factorial is " + factAns);
long numPow = o.myPower(2, 4);
System.out.println(2 + " Power " + 4 + " is " + numPow);
char lCase = o.lowerCase('B');
System.out.println('B' + " lower Case " + lCase);
char uCase = o.upperCase('b');
System.out.println('b' + " Upper Case " + uCase);
}
}
Output of the following program:

84
CC-121 Object Oriented Programming

28 Method overloading:
 In method overloading more than one methods are created in a class with same name
but different number of parametrs or datatype of parametrs or both.
 Method overloading can never depends upon return type of the method. Because at the
time of method calling, the method calling is resolved with method name and with
parameters.
 Return type not mentioned at the time of method calling.

Here is the program demonstrating method overloading:

class MethodOverload
{
int square(int n)
{
System.out.println("Integer Square Calling");
return n*n;
}

float square(float n)
{
System.out.println("float Square Calling");
return n*n;
}
void square()
{
System.out.println(2*2);
}
double square(double n)
{

85
CC-121 Object Oriented Programming

Output of the following program:

29 static variable:
 static variable is not an instance variable.
 static variable is a shared variable.
 Shared variable means all the instances of the class shared the same place. The
individual copy of variable can never be created with each object.
 static variable is called or referred with class Name as for as object Name. most suitable
way is to refer the static variable with class Name.
 memory allocated to static variable when static block is executed at the time of class
loading or in the absence of static block when first object of the class is created.
 static variable is also called history variable. Normally maintain the history of total
Number of objects created.

Input:

class Mobile

String brand;

int price;

String mobileType;
86
CC-121 Object Oriented Programming

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

class MainDemoMobile{

public static void main(String[] arg){

Mobile obj1 = new Mobile();

//First Object instance variables

obj1.brand = "Apple";

obj1.price = 70000;

obj1.mobileType = "SmartPhone";

Mobile obj2 = new Mobile();

//Second Object instance variables

obj2.brand = "Samsung";

obj2.price = 90000;

obj2.mobileType = "SmartPhone";

obj1.show();

obj2.show();

87
CC-121 Object Oriented Programming

Output of the following code:

In above code every mobile is a smart phone. So, no need to create the copy of mobileType
variable for each object. To share the mobileType variable with all the objects of Mobile class,
make it static.

Input:

class Mobile

String brand;

int price;

static String mobileType;

public Mobile(String n, int p)

brand = n;

price = p;

mobileType = "SmartPhone";//No need to initialize for each object

public void show()

88
CC-121 Object Oriented Programming

System.out.println(brand + " : "+ price + " : "+ mobileType);

class MainDemoMobileConstructor{

public static void main(String[] arg){

Mobile obj1 = new Mobile("Apple",7000);

Mobile obj2 = new Mobile("Samsung", 90000);

obj1.show();

obj2.show();

Output of the following code:

Input:

class Mobile

String brand;

int price;

static String mobileType;

89
CC-121 Object Oriented Programming

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

class MainDemoMobileSharedVariable{

public static void main(String[] arg){

Mobile obj1 = new Mobile();

//First Object instance variables

obj1.brand = "Apple";

obj1.price = 70000;

//shared variable can be accessed with class name

Mobile.mobileType = "SmartPhone";

Mobile obj2 = new Mobile();

//Second Object instance variables

obj2.brand = "Samsung";

obj2.price = 90000;

//shared variable can be accessed with class name

Mobile.mobileType = "SmartPhone1";

obj1.show();

obj2.show();

90
CC-121 Object Oriented Programming

Output of the following program:

30 static block:
static block is a proper place for the initialization of static variable.

Input:

class Mobile

String brand;

int price;

static String mobileType;

static{

//static block is a proper place for the initialization of static variable

mobileType = "SmartPhone";

public Mobile(String n, int p)

brand = n;

price = p;

//No need to initialize for each object

91
CC-121 Object Oriented Programming

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

class MainDemoMobileStaticBlock{

public static void main(String[] arg){

Mobile obj1 = new Mobile("Apple",7000);

Mobile obj2 = new Mobile("Samsung", 90000);

obj1.show();

obj2.show();

Output of the following program:

92
CC-121 Object Oriented Programming

31 static method:
From static method non-static variables can never be referenced.

Input:

class Mobile

String brand;

int price;

static String mobileType;

static{

//static block is a proper place for the initialization of static variable

mobileType = "SmartPhone";

public Mobile(String n, int p)

brand = n;

price = p;

//No need to initialize for each object

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

public static void show1()

93
CC-121 Object Oriented Programming

System.out.println(brand + " : "+ price + " : "+ mobileType);

class MainDemoMobileStaticMethod{

public static void main(String[] arg){

Mobile obj1 = new Mobile("Apple",7000);

Mobile obj2 = new Mobile("Samsung", 90000);

obj1.show1();

obj2.show1();

Output of the following program:

Input:

class Mobile

String brand;

94
CC-121 Object Oriented Programming

int price;

static String mobileType;

static{

//static block is a proper place for the initialization of static variable

mobileType = "SmartPhone";

public Mobile(String n, int p)

brand = n;

price = p;

//No need to initialize for each object

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

public static void show1(Mobile o)

System.out.println(o.brand + " : "+ o.price + " : "+ mobileType);

class MainDemoMobileStaticMethodNoError{

public static void main(String[] arg){

95
CC-121 Object Oriented Programming

Mobile obj1 = new Mobile("Apple",7000);

Mobile obj2 = new Mobile("Samsung", 90000);

obj1.show1(obj1);

obj2.show1(obj2);

Output of the following program:

Input:

class Mobile

String brand;

int price;

static String mobileType;

static{

//static block is a proper place for the initialization of static variable

mobileType = "SmartPhone";

System.out.print("In Static Block");

96
CC-121 Object Oriented Programming

public Mobile(String n, int p)

brand = n;

price = p;

System.out.print("In Constructor");

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

public static void show1(Mobile o)

System.out.println(o.brand + " : "+ o.price + " : "+ mobileType);

class MainDemoMobileStaticBlockClassLoad{

public static void main(String[] arg) throws ClassNotFoundException{

Class.forName("Mobile");

Output of the following program:

97
CC-121 Object Oriented Programming

Input:

class Mobile

String brand;

int price;

static String mobileType;

static{

//static block is a proper place for the initialization of static variable

mobileType = "SmartPhone";

System.out.println("In Static Block");

public Mobile(String n, int p)

brand = n;

price = p;

System.out.println("In Constructor");

public void show()

System.out.println(brand + " : "+ price + " : "+ mobileType);

public static void show1(Mobile o)

98
CC-121 Object Oriented Programming

System.out.println(o.brand + " : "+ o.price + " : "+ mobileType);

class MainDemoMobileStaticBlockClassLoadWithConstructor{

public static void main(String[] arg) throws ClassNotFoundException{

Class.forName("Mobile");

Mobile obj1 = new Mobile("Apple",7000);

Mobile obj2 = new Mobile("Samsung", 90000);

Output of the following program:

99
CC-121 Object Oriented Programming

32 Variable Arguments:
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments.
Variable Arguments in Java simplify the creation of methods that need to take a variable
number of arguments.

32.1 General Syntax:


The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

return_type method_name(data_type... variableName)

This syntax tells the compiler that method( ) can be called with zero or more arguments.

Input:

class VarArgs

void varTest(int ... y)

System.out.print("Number of Arguments " +y.length + " Contents:");

for (int i:y)

System.out.print(i + " ");

System.out.println();

class MainDemoVarArgs

public static void main(String[] args)


100
CC-121 Object Oriented Programming

VarArgs obj = new VarArgs();

obj.varTest(5); // 1 Argument

obj.varTest(5,6);// 2 Arguments

obj.varTest(5,6,7); // 3 Arguments

obj.varTest();

Output of the following program:

 Inside the varTest() method, y is treated like an array because it is an array. The ...
syntax just tells the compiler that the method can accept a variable number of
arguments, which will be stored in the array y.
 In the main() method, the varTest() method is called with different numbers of
arguments, including no arguments. The arguments are automatically placed into an
array and passed to y. If no arguments are given, the array is empty, and its length is
zero.
 A method can include formal parameters along with a variable-length parameter, but
the variable-length parameter must always be declared last in the method's parameter
list.

101
CC-121 Object Oriented Programming

int varTest(int a, int b, double c, int ... v) Declaration is correct

int varTest(int a, int b, double c, int ... v, boolean b) Declaration is incorrect

int varTest(int a, int b, double c, int ... v, double ... m) Declaration is incorrect

Input: //Use varargs with standard arguments.

class VarArgs2

// Here, s is a normal parameter and v is a varargs parameter.

void varTest(String s, int ... y)

System.out.print(s +y.length + " Contents:");

for (int i:y)

System.out.print(i + " ");

System.out.println();

class MainDemoVarArgsFormalParameter

public static void main(String[] args)

VarArgs obj = new VarArgs();

obj.varTest("One vararg:", 5);

obj.varTest("Two vararg:", 5,6);

102
CC-121 Object Oriented Programming

obj.varTest("Three vararg:", 5,6,7);

Output of the following program:

103
CC-121 Object Oriented Programming

33 Array:
 Array is the collection means Array is used to store more than one values.
 An array is an object that consists of a sequence of elements that are numbered 0, 1,
2, . . .
 The element numbers are called index numbers.
 Array elements can be accessed by their index numbers using the subscript operator
[], as a[0], a[1], a[2], and so on.
 Array is a vector because each element is accessed with array Name and index
number.
 Array is the linear data structure because an element of an array is followed by
another element of array.
 Arrays are objects.
 Arrays are created dynamically (at run time) in Java.

33.1 General Syntax:


dataType[] arrayName = new dataType[arraySize];
Array Size
33.2 Specific Syntax: written in
Array Size the form of
int[] arr = new int[5]; constant /
variable /
expression

Name of Array Allocate Heap Memory (runtime)

or declaration can be split into two lines

dataType[] arrayName;
int[] arr;
arrayName = new dataType[arraySize];

arr = new int[5];

104
CC-121 Object Oriented Programming

Memory Map of 1-D Array: Index No.

Stack

arr arr[0] arr[1] arr[2] arr[3] arr[4]


2001 0 0 0 0 0
2001 2005 2009 2013 2017

Heap
Address of first element

Elements/Components

 new: operator is used to allocate memory from heap as specified in array size with
respect to the datatype at runtime when this statement is executed. (just like memory
allocation to the instance variable(s) of a class during object creation).
 Because array is an object array length data member that is initialized with the size of
array at the time of array object creation. After that array size can never be changed.
 DataType[arraySize]  behave like the constructor initialize each component/element
of an array with default value.
 DataType[] ArrayName  ArrayName allocates memory in Stack. ArrayName is used to
store the reference. A heap memory that is returned by new operator. (After allocating
memory from heap and initialized of each component of array with default value as
mentioned above.
 An array object contains a sequence of variables.
 The variables are called the components or elements of the array.
 An array type variable holds a reference to the array object.
 The length of an array is its number of components.
 An array’s length is set when the array is created, and it cannot be changed.

 Array index values must be integers in the range 0...length –1.


105
CC-121 Object Oriented Programming

 An ArrayIndexOutOfBoundsException is thrown when mentioned index number


exceeded the length of array.

34 1-D Array initialization at the time of declaration:


int[] table = {10,20,30,40,50}

float[] table = {2.5f,4.5f,7.8f,5.7f,4.3f}

 Here is a simple Java program that demonstrates how to declare, initialize, and
traverse an array using a for loop.

Input:
class MainDemoArray
{
public static void main(String[] args)
{
int[] arr = new int[5]; // Declaring an array of size 5
arr[0]= 10;
arr[1]= 20;
arr[2]= 30;
arr[3]= 40;
arr[4]= 50;
// Using a for loop to print each element of the array
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}

106
CC-121 Object Oriented Programming

}
}
Memory:

Stack

arr arr[0] arr[1] arr[2] arr[3] arr[4]

2001 0 10 0 20 0 30 0 40 0 50

2001 2005 2009 2013 2017

Heap

Output:

 Finds the maximum value in an array of integers and prints it.


Input:
class MainDemoArrayMaxValue
{
public static void main(String[] args)
{
int[] arr = {10,40,67,89,30};

107
CC-121 Object Oriented Programming

int max = arr[0]; // Initialize 'max' with the first element of the array i.e. 10

for(int i=1;i<arr.length;i++) // Loop through the rest of the array


{

if(arr[i] > max) // If the current element is greater than max, update max
{
max = arr[i]; // Assign the larger value to max
}
}
System.out.println("Max value is:" +max ); // Print the maximum value

}
}
Memory:
arr arr[0] arr[1] arr[2] arr[3] arr[4]

2001
10 40 67 89 30
2001 2005 2009 2013 2017
Stack Heap
Iteration Process:
1. First Iteration (i=1)
Compare arr[1] (40) with max (10), update max = 40
2. Second Iteration (i=2)
Compare arr[2] (67) with max (40), update max = 67
3. Third Iteration (i=3)
Compare arr[3] (89) with max (67), update max = 89
4. Fourth Iteration (i=4)
Compare arr[4] (30) with max (89), no change.

108
CC-121 Object Oriented Programming

Output:

 Finds the minimum value in an array of integers and prints it.


Input:
class MainDemoArrayMinValue
{
public static void main(String[] args)
{
int[] arr = {10,40,67,89,30};
int min= arr[0]; // Initialize 'min' with the first element of the array i.e. 10

for(int i=1;i<arr.length;i++) // Loop through the rest of the array


{

if(arr[i] < min) // If the current element is smaller than min, update min
{
min = arr[i]; // Assign the smaller value to min
}
}
System.out.println("Min value is:" +min); // Print the minimum value

}
}

109
CC-121 Object Oriented Programming

Memory:
arr arr[0] arr[1] arr[2] arr[3] arr[4]

2001
10 40 67 89 30
2001 2005 2009 2013 2017
Stack Heap

Iteration Process:
1. First Iteration (i=1)
Compare arr[1] (40) with min (10), no change (since 40 > 10).

2. Second Iteration (i=2)


Compare arr[2] (67) with min (10), no change (since 67 > 10).

3. Third Iteration (i=3)


Compare arr[3] (89) with min (10), no change (since 89 > 10).

4. Fourth Iteration (i=4)


Compare arr[4] (30) with min (10), no change (since 30 > 10).

Output:

110
CC-121 Object Oriented Programming

Linear Search:
Linear Search is also known as Sequential Search because it checks each element in a sequence,
one by one, until it finds the target value or reaches the end of the list.

Input:
class LinearSearch
{
public static void main(String[]args)
{
int arr[] = {11,2,57,13,9,25};
int key = 57; // element to be search
int index = -1; // default value if element not found
for(int i=0;i<arr.length;i++)
{
if(key==arr[i])
{
index = i; // store index no if match found
break; // if element found, exit from the loop
}
}
if(index>-1)
{
System.out.println(key+ " value at " +index+ " index ");
}
}
}

111
CC-121 Object Oriented Programming

Iteration Process:
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]
11 2 57 13 9 25

Iteration i (Index) arr[i] (Current Element) Compare (key == arr[i]) index Updated? Loop Action

1st 0 11 57 == 11 (False) No Continue loop

arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]


11 2 57 13 9 25

Iteration i (Index) arr[i] (Current Element) Compare (key == arr[i]) index Updated? Loop Action

2nd 1 2 57 == 2 (False) No Continue loop

arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]


11 2 57 13 9 25

Iteration i (Index) arr[i] (Current Element) Compare (key == arr[i]) index Updated? Loop Action

3rd 2 57 57 == 57 (True) Yes Loop Break

Output:

112
CC-121 Object Oriented Programming

Binary Search:
Binary Search is an efficient searching algorithm that finds a target value in a sorted array by
repeatedly dividing the search space in half. This method is easy and short from linear search.
The assumption of binary search is that the array values always in sorted form (Ascending
order).
How It Works:
1. Find the middle element of the array.
2. Compare the target value with the middle element:
 If the target matches, return the index.
 If the target is smaller, search the left half.
 If the target is greater, search the right half.
3. Repeat the process until the target is found or the search space becomes empty.

Input:
class BinarySearch
{
public static void main(String[] args)
{
int[] arr = {11,20,35,50,67,70,75};
int key = 67;
int index = -1;
int low = 0, high = arr.length - 1;
for(int mid=(low+high)/2; low <= high; mid=(low+high)/2)
{

if (key == arr[mid])
{
index = mid; // Target found

113
CC-121 Object Oriented Programming

break;
}
if (key > arr[mid])

{
low = mid + 1; // Search in right half
}

if (key < arr[mid])


{
high = mid - 1; // Search in left half
}
}

if (index > -1)


{
System.out.println( key + " Element found at index " + index);
}
else
{
System.out.println("Element not found");
}
}
}
Iteration Process:
arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6]
11 20 35 50 67 70 75

low mid high

Iteration low high mid = (low+high)/2 arr[mid] Comparison Action


(key vs arr[mid])
1st 0 6 (0+6)/2 = 3 50 67 > 50 (key is greater) Search right
(low = mid + 1 = 4)

114
CC-121 Object Oriented Programming

arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6]


11 20 35 50 67 70 75

low mid high

Iteration low high mid = (low+high)/2 arr[mid] Comparison Action


(key vs arr[mid])
2nd 4 6 (4+6)/2 = 5 70 67 < 70 (key is smaller) Search left
(high = mid - 1 = 4)

arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6]


11 20 35 50 67 70 75

low

mid

high

Iteration low high mid = (low+high)/2 arr[mid] Comparison Action


(key vs arr[mid])
3rd 4 4 (4+4)/2 = 4 67 67 == 67 (key found) Stop, index = 4

Output:

115
CC-121 Object Oriented Programming

Bubble Sort:
Bubble sort is a simple sorting algorithm that compares adjacent elements in a list and swaps
them if they are in the wrong order. This process continues until the entire list is sorted.

How it works:
 In each pass, the largest value moves to its correct position at the end of the list, while
smaller values gradually move up, similar to bubbles rising in water.
 The algorithm continues this process step by step until the list is fully sorted.

int[] arr = {8, 5, 7, 3, 2}

arr[0] arr[1] arr[2] arr[3] arr[4]


8 5 7 3 2
2001 2005 2009 2013 2017

1st Pass 2nd Pass

8 5 5 5 5 5 5 5 5

5 8 7 7 7 7 7 3 3

7 7 8 3 3 3 3 7 2

3 3 3 8 2 2 2 2 7

2 2 2 2 8 8 8 8 8

4 Comparison 3 Comparison
4 Swap 3 Swap

116
CC-121 Object Oriented Programming

4th Pass
3rd Pass

5 3 3 3 2

3 5 2 2 3

2 2 5 5 5

7 7 7 7 7

8 8 8 8 8

2 Comparison 1 Comparison
2 Swap 1 Swap

Input:
class BubbleSortExample
{
public static void main(String[] args)
{
int[] arr = {8, 5, 7, 3, 2};
int n = arr.length;
for (int i = 0; i < n - 1; i++) // Outer loop for passes
{
for (int j = 0; j < n - 1 - i; j++) // Inner loop for comparing adjacent elements
{
if (arr[j] > arr[j + 1]) // Swapping elements if they are in the wrong order
{
int temp = arr[j]; // Store the left element in a temporary variable
arr[j] = arr[j + 1]; // Move the right element to the left position

117
CC-121 Object Oriented Programming

arr[j + 1] = temp; // Place the stored left element in right position


}
}
}
// Print the sorted array
System.out.println("Sorted Array:");
for (int num : arr)
{
System.out.print(num + " ");
}
}
}
Output:

118
CC-121 Object Oriented Programming

Selection sort:
Selection Sort is a simple sorting algorithm that repeatedly finds the smallest element from the
unsorted array and swaps it with the first element. This process continues until the entire array
is sorted. In selection sort, the selected value is compared with other values of the collection
and smallest value set at the top of the selection.
int[] arr = {8, 5, 7, 3, 2}

arr[0] arr[1] arr[2] arr[3] arr[4]


8 5 7 3 2
2001 2005 2009 2013 2017

1st Pass 2nd Pass

8 5 5 3 2 2 2 2 2

5 8 8 8 8 8 7 5 3

7 7 7 7 7 7 8 8 8

3 3 3 5 5 5 5 7 7

2 2 2 2 3 3 3 3 5

4th Pass
3rd Pass

2 2 2 2 2

3 3 3 3 3

8 7 5 5 5

7 8 8 8 7

5 5 7 7 8

119
CC-121 Object Oriented Programming

Input:
class SelectionSortExample
{
public static void main(String[] args)
{
int[] arr = {8, 5, 7, 3, 2}; // Given array
int n = arr.length;
// Selection Sort Logic
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

// Final Sorted Array (Moved outside the loop)


System.out.println("\nFinal Sorted Array:");
for (int num : arr) // Using for-each loop again
{
System.out.print(num + " ");
}
System.out.println();
}

120
CC-121 Object Oriented Programming

}
Output:

121

You might also like