Ooptj r23 Unit 3
Ooptj r23 Unit 3
UNIT III
1.Introduction to Arrays:
An Array is a collection of elements that share the same type and name. The elements from the
array can be accessed by the index.
An array is a structure consisting of a group of elements of the same type. When a large number
of data values of the same type are to be processed, it can be done efficiently by declaring an
array of the data type.
Examples:
int numbers []; // an array of whole numbers
char name []; // A name is an array of characters
float priceList []; // An array of floating point numbers.
Initialization
With above declaration no memory is allocated. Memory is allocated when new operator is used
or when it is initialized with declaration as shown below.
int numbers []=new int[5]; //allocating memory with new
or int numbers[]={ 3,4,12,8}; //allocating with initialization
A two-dimensional array needs two square brackets one for rows and other for columns and may
be initialized as follow:
type identifier [][];// declaration of array of arrays
int total_sales[][]={{120,100,45},{30,45,60,},{80,90,70}}; //initialization
6. Array of Strings
We can form array with elements as String as we have used primitive types.The String is
class in java standard library.
Syntax: String s[]={“JAVA”, “FLAT”, “DBMS”};
Example,
}
}
Output:
D:/CSE>javac ArrOperations.java
D:/CSE>java ArrOperations
Enter the size of the arrays: 4
Enter elements into arr1:
2
4
6
8
Enter elements into arr2:
12
14
16
18
Addition of two arrays is:
14 18 22 26
These arguments in the method call are assigned to parameters in the method definition in the
order.
Example,
static void display(int a[])
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
static void add(int a[],int b[])
{
int c[]=new int[a.length];
System.out.println("Addition of two arrays is:");
for(int i=0;i<c.length;i++)
{
c[i]=a[i]+b[i];
}
display(c); //method call
}
In this process, the 2nd array (arr2) becomes a reference to the assigned array (arr1). The
second array is not a new array, instead a second reference is created. In this context both arr1
and arr2 are referring the same memory.
If a change is done on arr1, then it is reflected on arr2. Let us understand this with an example
program.
1. Bubble Sort
Bubble sort is a very simple method that sorts the array elements by repeatedly moving
the largest element to the highest index position of the array segment (in case of
arranging elements in ascending order).
In bubble sorting, consecutive adjacent pairs of elements in the array are compared with
each other. If the element at the lower index is greater than the element at the higher
index, the two elements are interchanged. This process will continue till the list of
unsorted elements exhausts.
This procedure of sorting is called bubble sorting because elements ‘bubble’ to the top of
the list. At the end of the first pass, the largest element in the list will be placed at its
proper position (i.e., at the end of the list).
The basic methodology of the working of bubble sort is given as follows:
a) In Pass 1, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–2] is compared with A[N–1]. Pass 1
involves n–1 comparisons and places the biggest element at the highest index of the
array.
b) In Pass 2, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–3] is compared with A[N–2]. Pass 2
involves n–2 comparisons and places the second biggest element at the second highest
index of the array.
c) In Pass 3, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–4] is compared with A[N–3]. Pass 3
involves n–3 comparisons and places the third biggest element at the third highest index
of the array.
d) In Pass n–1, A[0] and A[1] are compared so that A[0]<A[1]. After this step, all the
elements of the array are arranged in ascending order.
Example : Let us consider an array A[] that has the following elements:
A[] = {30, 52, 29, 87, 63, 27, 19, 54}
Pass 1:
a) Compare 30 and 52. Since 30 < 52, no swapping is done.
b) Compare 52 and 29. Since 52 > 29, swapping is done. 30, 29, 52, 87, 63, 27, 19, 54
c) Compare 52 and 87. Since 52 < 87, no swapping is done.
d) Compare 87 and 63. Since 87 > 63, swapping is done. 30, 29, 52, 63, 87, 27, 19, 54
e) Compare 87 and 27. Since 87 > 27, swapping is done. 30, 29, 52, 63, 27, 87, 19, 54
f) Compare 87 and 19. Since 87 > 19, swapping is done. 30, 29, 52, 63, 27, 19, 87, 54
g) Compare 87 and 54. Since 87 > 54, swapping is done. 30, 29, 52, 63, 27, 19, 54, 87
Observe that after the end of the first pass, the largest element is placed at the highest
index of the array. All the other elements are still unsorted.
Pass 2:
a) Compare 30 and 29. Since 30 > 29, swapping is done.
Pass 6:
a) Compare 27 and 19. Since 27 > 19, swapping is done.
19, 27, 29, 30, 52, 54, 63, 87
b) Compare 27 and 29. Since 27 < 29, no swapping is done.
Observe that after the end of the sixth pass, the sixth largest element is placed at the sixth
largest index of the array. All the other elements are still unsorted.
Pass 7:
a) Compare 19 and 27. Since 19 < 27, no swapping is done.
1. Linear Search
Linear search, also called as sequential search, is a very simple method used for
searching an array for a particular value. It works by comparing the value to be searched with
every element of the array one by one in a sequence until a match is found. Linear search is
mostly used to search an unordered list of elements (array in which data elements are not sorted).
Example: Consider an unordered list L = { 10, 8, 2, 7, 3, 4, 9, 1, 6, 5 }
Working of Linear Search: Search element : 7
2. Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list. Binary
search is a fast search algorithm with run-time complexity of Ο(log n).This search
algorithm works on the principle of divide and conquer.
The middle element position is calculated by dividing the sum of lower bound and upper
bound by 2. i.e) if Low = first element position and High = last element position then
calculate the middle element position= (Low + High) /2 and compare searching element
with A[Mid ].
The comparison of searching element with middle element yields the following cases:
Comparing – Here two arrays are compared. The outcome of the comparison will be a Boolean
value either true, or false.
public static boolean equals (int[] a, int[] b)
for(char x:a)
System.out.print(x+"\t");
System.out.println()
for(int x:arr2)
System.out.print(x+"\t");
A=new int[r][c];
B=new int[r][c];
for(i=0;i<r;i++)//reading elements into matrix A
{
for(j=0;j<c;j++)
{
System.out.printf("Enter A[%d][%d] element:",i,j);
A[i][j]=in.nextInt();
}
}
for(i=0;i<r;i++) //reading elements into matrix B
{
for(j=0;j<c;j++)
{
System.out.printf("Enter B[%d][%d] element:",i,j);
B[i][j]=in.nextInt();
}
}
System.out.println("Matrix A is:"); //display arrays A and B
System.out.println(Arrays.deepToString(A));
System.out.println("Matrix B is:");
System.out.println(Arrays.deepToString(B));
C=new int[r][c];
//Matrix Addition
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("Matrix C is:");
System.out.println(Arrays.deepToString(C));
}
}
Matrix Multiplication
// Check if multiplication is Possible
if (row2 != col1) {
System.out.println(
"\nMultiplication Not Possible");
}
else{
// Matrix to store the result. The product matrix will be of size row1 x col2
int C[][] = new int[row1][col2];
for (i = 0; i < row1; i++) { // Multiply the two matrices
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
Example Program:
Example Program
class Three–dimensionalArrayEx
{
public static void main(String[] args)
Where B is derived class which is inheriting the properties, and class A is the super class from
which properties are acquired.
i) Single Inheritance
In Single Inheritance one class extends another class (one class only). A subclass inherits
the properties of one super class.
v) Hybrid Inheritance:
Hybrid inheritance is one of the inheritance types in Java which is a combination of
Single and Multiple inheritance. When one or more types of inheritance are combined,
then it becomes a hybrid inheritance.
Hence Java does not support hybrid inheritance as well with classes. But like
multiple inheritance, we can implement hybrid inheritance in Java using interfaces.
In the above diagram, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Disadvantages of Inheritance
The tight coupling between super and subclasses increases and it becomes very difficult
to use them independently.
Program processing time increases as it takes more time for the control to jump through
various levels of overloaded classes.
When some new features are added to super and derived classes as a part of maintenance,
the changes affect both the classes.
When some methods are deleted in super class that is inherited by a subclass, the methods
of subclass will no longer override the super class method.
The syntax of different types of inheritance:
27. Binding
There are two types of Bindings: static binding and dynamic binding
Static Binding: When binding is done at compile time by the compiler, it is known as Static
Binding, or Early Binding. Example, static, private, and final methods are bound at compile time.
Hence, these cannot be overridden.
Dynamic Binding: The Compiler not able to resolve the method call at compile time. This is
also called ‘Late Binding’. The method overriding is the best example for dynamic Binding.
The basic difference between static and dynamic binding is that static binding occurs at compile
time, whereas dynamic binding happens at run time.
Example Program for Static Binding StatBinding.java
class Vehicle {
final void display()
{
System.out.println("Vehicle Details");
}
}
class Car extends Vehicle{
void display()
{
System.out.println("Car Details");
}
}
class StatBinding {
public static void main(String arg[])
{
Car c=new Car();
c.display();
}
}
Output:
D:\CSE>javac StatBinding.java
StatBinding.java:10: error: display() in Car cannot override display() in Vehicle
void display()
^
overridden method is final
1 error
Example program for Dynamic Binding DynamicBinding.java
class Vehicle {
void display()
{
System.out.println("Vehicle Details");
}
}
class Car extends Vehicle {
void display()
{
System.out.println("Car Details");
}
}
class DynamicBinding {
Interface References:
An interface reference can only access the methods declared in that interface. It cannot access
other methods of the class implementing that interface. For interface references, variables can be
declared as object references. In this case, the object reference would use interface as the type
instead of class. The appropriate method is called on the basis of actual instance of the interface
that is being referred to. If the implementing class has methods other than definitions of abstract
methods, these methods cannot be called with interface reference object. Such methods have to
be called with object of implementing class.
// Illustration of implementing multiple interfaces with Interface References
interface InterfaceA
{
void show();
}
interface InterfaceB
{
void add(int a,int b);
}
class MultiInterface implements InterfaceA, InterfaceB
{
Functional Consumer<T>
It declares one abstract method void accept(T t). The method only consumes its
argument. It does not give any return value. This is mainly used to display or to set the values.
The interface declaration is @FunctionalInterface
public interface Consumer
{
void accept(T t);
}
Example Program,
import java.util.function.Consumer;
class FunTest{
static void disp(double t)
{
System.out.println(t+"\t");
}
public static void main(String arg[]) {
Consumer<Double>consumer=(Double d)->{disp(d);};
consumer.accept(3.14);
}
}
Functional Supplier
The functional Supplier is opposite to the Consumer. It simply supplies an object through its
method get(), which does not take any argument.This method can be used in a situation where
there is no input, but there is output. The declaration of the function is as follow:
@FunctionInterface
public interface Supplier
{
T get();
}
Example Program,
import java.util.function.Supplier;
class MyNumber
{ int getNumber()
{
return (int) (Math.random()*100);
Output:
}
D:\CSE>java SupplierTest
}
The new number is:42
class SupplierTest
{
public static void main(String arg[])
{
Supplier<MyNumber> supplier=MyNumber::new;
MyNumber number=supplier.get();//supplies an object as argument
40. Annotations
Annotation framework in Java language was first introduced in Java 5 through a
provisional interface. It is a type of metadata that can be integrated with the source code without
affecting the running of the program. Annotations may be retained(continued) up to runtime and
may be used to instruct the compiler and runtime system to do or not to do certain things. Since
Java SE 8, the annotations may be applied to classes, fields, interfaces, methods, and type
declarations like throw clauses. The annotations are no longer simply for metadata inclusion in
the program but have become a method for user’s communication with compiler or runtime
system.
For example, consider a super class method that is overridden in the sub class. In this
context both methods signatures must be same (Example; method name, list of arguments and
their types) If, by mistake, a type or parameter in the sub class definition is changed, then method
overriding will no longer work, instead it becomes method overloading. In this situation the
program will still compile without any error, but the result will not be as expected. It is difficult
to catch such error. The solution to it is to add annotation before the sub class method name as
follow: @Override. This will cause the compiler to check and report whether this is a overridden
method or not. In this way it helps program to catch error.
Example Program,
class X
{
void add(int x, double y) //int and float as parameters
{
System.out.println("Floating point Sum is :"+(x+y));
}
}
class Y extends X
{
@Override
void add(int x, int y) // integers as paramters
{
System.out.println("Integer Sum is :"+(x+y));
}
}
class AnnoTest
{
public static void main(String arg[])
{
Y y=new Y();
y.add(2,3.4);
}
}