OOPJ(java) Unit-III
OOPJ(java) Unit-III
Advantages:
Code Optimization: It makes the code optimized, we can get values or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime..
b) Array Declaration Syntax :
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Array Declaration Initialization:
int arr[] = {10,20,30,40,50}; //declaration, instantiation and initialization
String args[] = {"ram","shyam","raj"};
System.out.println("\nAnother Array:");
for (int num : anotherArray) {
System.out.print(num + " ");
}
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac ArrayAssignmentExample.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ArrayAssignmentExample.java
Original Array:
10 2 3 4 5
Another Array:
10 2 3 4 5
System.out.println();
for(int i=0; i< array.length ; i++) //printing elements
{
System.out.print(array[i]+" ");
}
array = new int[10]; // changing size 5 to 10 create a new array with default values
System.out.println();
//printing elements
for(int i=0; i< array.length ; i++)
{
System.out.print(array[i]+" ");
}
}
}
Output:
Elements of Array are:
23456
0000000000
for(i=0;i<size;i++)
{
arr[i] = scan.nextInt();
}
Example:
import java.util.Scanner;
class SelectionSorting
{
public static void main(String ars[])
{
int arr[] = new int[100];
int n;
int i, j, min_idx;
System.out.println("Enter n value");
n = scan.nextInt();
for(i=0;i<=n-1;i++)
{
arr[i] = scan.nextInt();
}
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java SelectionSorting
Enter n value
5
Enter array elements
12
32
65
45
85
Sorted array:
12
32
45
65
85
Example:
import java.util.Scanner;
class InsertionSort
{
public static void main(String ar[])
{
int n, i, j, key;
Output:
b) Searching techniques:
The linear search algorithm is defined as a sequential search algorithm that starts at one end and goes through
each element of a list until the desired element is found; otherwise, the search continues till the end of the
dataset
Program:
import java.util.Scanner;
class LinearSearch
{
public static void main(String ar[])
{
Int size , key, index = -1;
Scanner scan = new Scanner(System.in);
if (index != -1)
System.out.println("Key found at index "+index);
else
System.out.println("Key not found in the array");
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java LinearSearch
Enter the size of the array:
6
Enter the elements
12
36
54
98
46
35
Enter the key to search for:
98
Key found at index 3
2. Search Loop:
While left is less than or equal to right, continue searching.
Calculate the middle index: mid = (left + right) / 2. This is the index where we will check for the
target element.
3. Comparison:
Compare the target element with the element at the middle index array[mid].
If array[mid] is equal to the target, then the element is found at index mid.
If array[mid] is greater than the target, then the target (if it exists) must be in the left half
of the array. Adjust right = mid - 1 to search in the left sub-array.
If array[mid] is less than the target, then the target (if it exists) must be in the right half of
the array. Adjust left = mid + 1 to search in the right sub-array.
4. Repeat:
Repeat steps 2 and 3 until left is greater than right. This means the target element is not this
means the target element is not present in the array.
5. Result:
If the target element is found during the search, return the index mid.
If the target element is not found, return a specific value (e.g., -1) to indicate its absence.
Sort an Arrays.
Search in an Arrays.
Here Arrays class provides several static methods that can be used to perform these tasks directly without the
use of loops, hence forth making our code super short and optimized.
Searches for the specified element in the array with the help of the Binary
binarySearch()
Search Algorithm
class CodeForArraySorting
{
public static void main(String args[])
{
int[] arr = { 5, 2, 23, 7, 87, -42, 509 };
Arrays.sort(arr);
// Using sort() method of Arrays class and passing arrays to be sorted as in arguments
Arrays.sort(byteArr);
Arrays.sort(intArr);
// Primitive datatypes to search
byte byteKey = 35;
int intKey = 22;
Code:
public class MatrixAdditionExample
{
public static void main(String args[])
{
//creating two matrices
int a[][] = {
{1,3,4},
{2,4,3},
{3,4,5} };
int b[][] = {
{1,3,4},
{2,4,3},
{1,2,4} };
These statements define three possible one-dimensional arrays that can be referenced through the elements of
table array.
The first element (table [0]) now references an array of one element of type int.
The second element (table [1]) now references an array of two elements of type int.
The third element (table [2]) now references an array of three elements of type int.
Like you can initialize arrays of arrays, similarly, the ragged arrays can also be initialized.
Example :
int table [][] = {
{l},
{2,2},
{3,3,3}
};
creates an int-type two dimensional array table containing three array elements.
The first element is reference to a one-dimensional array of length one, the second element is reference to one-
dimensional array of length two and the third elements is a reference to one-dimensional array of length three.
for(i=0;i<table.length;i++)
{
for(j=0;j<table[i].length;j++)
{
if(table[i][j]>max);
max = table[i] [j];
if(table[i][j]<min)
min = table[i] [j];
}
}
System.out.println("Maximum Element is : "+max);
System.out.println("Minimum Element is : "+min);
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java MaxMin
Maximum Element is : 44
Minimum Element is : 3
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ThreeDArray
Department Electronics:
Student1 scores:
75 87 69
Total scores: 231
Percentage: 77.0
Student2 scores:
90 87 85
Total scores: 262
Percentage: 87.33333333333333
Student3 scores:
56 67 76
Total scores: 199
Percentage: 66.33333333333333
Department IT:
Student1 scores:
75 87 69
Total scores: 231
Percentage: 77.0
Student2 scores:
90 87 85
Total scores: 262
Percentage: 87.33333333333333
Student3 scores:
56 67 76
Total scores: 199
Percentage: 66.33333333333333
S. Method Description
No
2) addAll() It is used to append all of the elements in the specified collection to the end of this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It increases the vector size
by one.
4) capacity() It is used to get the current capacity of this vector.
Code:
import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
Vector vec = new Vector<String>(); //Create a vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
On above example
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Types of inheritance in java (On the basis of class, there can be three types of inheritance in java)
1. single, 2. multilevel and 3. hierarchical.
SINGLE INHERITANCE
When one class extends another class(Only one class) then we call it as Single inheritance.
The below diagram represents single inheritance in java where Class B extends only one class Class A.
Here Class B will be the Sub class and Class A will be one and only Super class.
class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}
class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}
public class C extends B
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}
HIERARCHICAL INHERITANCE
In Hierarchical inheritance one parent class will be inherited by many sub classes.
As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
ClassA will be acting as a parent class for ClassB, ClassC and ClassD.
class HierarchicalInheritanceTest
{
public static void main(String args[])
{
B b = new B();
b.dispB();
b.dispA();
Note:
Multiple inheritance is not supported in java through class but multiple and hybrid inheritance is supported
through interface only. When a class extends multiple classes i.e. known as multiple inheritance.
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
MULTIPLE INHERITANCE
Multiple Inheritance is nothing but one class extending morethan one class.
Method Description
public final Class getClass() Returns the class object of “this” object and used to get actual runtime class of
the object. It can also be used to get metadata of this class.
public int hashCode() Returns the hashcode number for this object. For every object, JVM generates a
unique number which is hashcode. It returns distinct integers for distinct objects.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long causes the current thread to wait for the specified milliseconds, until another
timeout)throws thread notifies (invokes notify() or notifyAll() method).
InterruptedException
public final void wait(long causes the current thread to wait for the specified milliseconds and nanoseconds,
timeout,int nanos)throws until another thread notifies (invokes notify() or notifyAll() method).
InterruptedException
public final void wait()throws causes the current thread to wait, until another thread notifies (invokes notify() or
InterruptedException notifyAll() method).
protected void finalize()throws is invoked by the garbage collector before object is being garbage collected.
Throwable
if(a.equals(b))
{
System.out.println(" a and b are equal " );
}
if(!a.equals(c))
{
System.out.println(" a and b are not equal " );
}
}
}
Output:
a and b are equal
a and b are not equal
toString() Method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output it can be the state of an object etc.
Advantage of Java toString() method
By overriding the toString() method ,we can return values of the object, so we don't need to write much code.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno = rollno;
this.name = name;
this.city = city;
}
finalize() method
This method is called just before an object is garbage collected.
It is called the Garbage Collector on an object when the garbage collector determines that there are no
more references to the object.
We should override finalize() method to set out of system resources, perform clean-up activities and
minimize memory leaks.
Note: The finalize method is called just once on an object even though that object is eligible for
garbage collection multiple times.
Example:
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());
t = null;
System.gc(); // calling garbage collector
System.out.println("end");
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac Test.java
Test.java:16: warning: [removal] finalize() in Object has been deprecated and marked for removal
protected void finalize() // Overriding finalize()
^
1 warning
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java Test
523429237
end
finalize method called
Object Cloning in Java
Student18 s2 = (Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c)
{
}
}
}
Output:
101 amit
101 amit
Output:
Compile Time Error
3.16 Access Control and Inheritance
Refer page no: (unit-II pages 9-12 ) Topics 2.4 and 2.5
3.17 Multilevel Inheritance
Refer page Nos 28-29
3.18 Application of Keyword Super
super keyword in java is a reference variable that is used to refer parent class object.
super is an implicit keyword create by JVM and supply each and every java program
Uses of super at three levels
At variable level
At method level
At constructor level
Need of super keyword:
Whenever the derived class is inherits the base class features, there is a possibility that base class
features are similar to derived class features and JVM will gets an ambiguity.
In order to differentiate between base class features and derived class features must be preceded by
super keyword.
Syntax
super.baseclass feature
class Svariable
{
public static void main(String[] args)
{
HR obj = new HR();
obj.display();
}
}
Output
Salary: 20000.0
Salary: 10000.0
Output
Good Morning Students
Good Morning Sir
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Output
Employee class Constructor
HR class Constructor
Department()
{
System.out.println("Department constructor executed");
}
}
Student()
{
System.out.println("Student constructor executed");
}
}
public class OrderofExecution2
{
public static void main(String ar[]) /* Driver Code */
{
class A
{
}
class B extends A
{
}
A a=new B(); //upcasting
For upcasting, we can use the reference variable of class type or an interface type.
Example:
interface I
{
}
class A
{
}
class B extends A implements I
{
}
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
class TestAbstraction1
{
public static void main(String args[])
{
Shape s = new Circle1();
s.draw();
}
}
Output:
drawing circle
Declaring Interfaces
Defining an interface is similar to that of a class. We use the keyword interface to define an interface.
Syntax
interface InterfaceName
{
members declaration;
}
Example
interface Emp
{
void learn(String str);
void work();
}
Example
interface Emp
{
void learn(String str);
void work();
}
Output
Learn using coding
Develop applications
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
Step 3: Create an object of the class and call the interface methods
MyClass obj = new MyClass();
obj.method1();
obj.method2();
interface Printable
{
public void print();
}
interface Showable
{
public void show();
}
The interface that defined inside another interface is known as nested interface (inner interface).
The nested interface declared within an interface is public by default.
The nested interface declared within a class can be with any access modifier.
Every nested interface is static by default.
Note:
We can only access the nested interface by using outer interface or outer class name followed by
dot( . ), followed by the nested interface name.
Example
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface
{
public void outerMethod()
{
System.out.println("This is OuterInterface method");
}
}
class OnlyInner implements OuterInterface.InnerInterface
{
public void innerMethod()
{
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample
{
public static void main(String[] args)
{
OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();
obj_1.outerMethod();
obj_2.innerMethod();
}
}
Output:
This is OuterInterface method
This is InnerInterface method
Java provides a facility to create default methods (from java 8 version) inside the interface.
Methods which are defined inside the interface and tagged with default are known as default methods.
These methods are non-abstract methods.
Java Default Method Example:
In the following example, Sayable is a functional interface that contains a default and an abstract
method.
The concept of default method is used to define a method with default implementation.
You can override default method also to provide more specific implementation for the method.
interface Sayable
{
default void say() // Default method
{
System.out.println("Hello, this is default method");
}
void sayMore(String msg); // Abstract method
}
public class DefaultMethods implements Sayable
{
public void sayMore(String msg) // implementing abstract method
{
System.out.println(msg);
}
public static void main(String[] args)
{
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Output:
Hello, this is default method
Work is worship
Interface Description
BiConsumer<T,U> It represents an operation that accepts two input arguments and returns no result.
Consumer<T> It represents an operation that accepts a single argument and returns no result.
Function<T,R> It represents a function that accepts one argument and returns a result.
@Override
void eatsomething()
{
System.out.println("eating foods");
}
}
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler .
import java.util.*;
class TestAnnotation2
{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}
}
Output:
Now no warning at compile time.
Note: If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time
because we are using non-generic collection