Java Notes Till Mids
Java Notes Till Mids
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.
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
Step 1: Step 2:
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
1. Class Name:
The name of the class is typically written in the top compartment of the class box and is centered.
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.
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.
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:
74
CC-121 Object Oriented Programming
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
class A
{
int x;
double y;
void show()
{
System.out.println(" x="+ x + "\t" + "y=" + y);
}
}
class MainDemo1
{
public static void main(String[] arg)
{
A obj = new A();
obj.show();
}
}
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.
}
77
CC-121 Object Oriented Programming
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.
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.
80
CC-121 Object Oriented Programming
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.
return n * n;
}
{ Formal parameters
return x + y;
}
81
CC-121 Object Oriented Programming
82
CC-121 Object Oriented Programming
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);
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.
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
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
class MainDemoMobile{
obj1.brand = "Apple";
obj1.price = 70000;
obj1.mobileType = "SmartPhone";
obj2.brand = "Samsung";
obj2.price = 90000;
obj2.mobileType = "SmartPhone";
obj1.show();
obj2.show();
87
CC-121 Object Oriented Programming
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;
brand = n;
price = p;
88
CC-121 Object Oriented Programming
class MainDemoMobileConstructor{
obj1.show();
obj2.show();
Input:
class Mobile
String brand;
int price;
89
CC-121 Object Oriented Programming
class MainDemoMobileSharedVariable{
obj1.brand = "Apple";
obj1.price = 70000;
Mobile.mobileType = "SmartPhone";
obj2.brand = "Samsung";
obj2.price = 90000;
Mobile.mobileType = "SmartPhone1";
obj1.show();
obj2.show();
90
CC-121 Object Oriented Programming
30 static block:
static block is a proper place for the initialization of static variable.
Input:
class Mobile
String brand;
int price;
static{
mobileType = "SmartPhone";
brand = n;
price = p;
91
CC-121 Object Oriented Programming
class MainDemoMobileStaticBlock{
obj1.show();
obj2.show();
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{
mobileType = "SmartPhone";
brand = n;
price = p;
93
CC-121 Object Oriented Programming
class MainDemoMobileStaticMethod{
obj1.show1();
obj2.show1();
Input:
class Mobile
String brand;
94
CC-121 Object Oriented Programming
int price;
static{
mobileType = "SmartPhone";
brand = n;
price = p;
class MainDemoMobileStaticMethodNoError{
95
CC-121 Object Oriented Programming
obj1.show1(obj1);
obj2.show1(obj2);
Input:
class Mobile
String brand;
int price;
static{
mobileType = "SmartPhone";
96
CC-121 Object Oriented Programming
brand = n;
price = p;
System.out.print("In Constructor");
class MainDemoMobileStaticBlockClassLoad{
Class.forName("Mobile");
97
CC-121 Object Oriented Programming
Input:
class Mobile
String brand;
int price;
static{
mobileType = "SmartPhone";
brand = n;
price = p;
System.out.println("In Constructor");
98
CC-121 Object Oriented Programming
class MainDemoMobileStaticBlockClassLoadWithConstructor{
Class.forName("Mobile");
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.
This syntax tells the compiler that method( ) can be called with zero or more arguments.
Input:
class VarArgs
System.out.println();
class MainDemoVarArgs
obj.varTest(5); // 1 Argument
obj.varTest(5,6);// 2 Arguments
obj.varTest(5,6,7); // 3 Arguments
obj.varTest();
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, double ... m) Declaration is incorrect
class VarArgs2
System.out.println();
class MainDemoVarArgsFormalParameter
102
CC-121 Object Oriented Programming
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.
dataType[] arrayName;
int[] arr;
arrayName = new dataType[arraySize];
104
CC-121 Object Oriented Programming
Stack
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.
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
2001 0 10 0 20 0 30 0 40 0 50
Heap
Output:
107
CC-121 Object Oriented Programming
int max = arr[0]; // Initialize 'max' with the first element of the array i.e. 10
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:
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).
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
Iteration i (Index) arr[i] (Current Element) Compare (key == arr[i]) index Updated? Loop Action
Iteration i (Index) arr[i] (Current Element) Compare (key == arr[i]) index Updated? Loop Action
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
}
114
CC-121 Object Oriented Programming
low
mid
high
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.
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
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}
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;
}
}
}
120
CC-121 Object Oriented Programming
}
Output:
121