Java Unit-3 Material
Java Unit-3 Material
1. Introduction to Arrays:
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. The complete data gets represented by a single object with
a single name in the computer memory. An array is a sequence of objects of the same data
type. The type of data that the array holds becomes the type of the array, which is also called
base type of the array.
When the elements of the array are again arrays, then the array is said to be
multidimensional array. A one-dimensional array has elements where each element is
accessed by an index value. Two-dimensional array is actually an array of one-dimensional
arrays. Each element of two-dimensional array needs two index values: one position of the
array in 2-D array, and other refers to the position in that array.
2. Declaration and Initialization of Arrays
The declaration of array starts with array type, followed by an identifier, and square brackets
and ends with semicolon as shown below:
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.
. 1|Page
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
The operator new, which is a keyword, allocates memory for storing the array
elements. For example, with the following declaration.
int[] numbers = new int[4];
Here, the compiler allocates 4 memory spaces, each equal to 4 bytes for storing the int type
values. When array is created as above the elements of the array are automatically initialized
to default values based on the type of array. Default values for int, float, char are 0,0.0, and
space respectively.
. 2|Page
5. Determination of Array Size:
The size of length of the array is determined by the following code:
int size=array_name.length;
Here, length is an attribute of array object
This size or length can be used in the for loop to access the elements as shown below:
for(int i=0;i<array_name.length;i++)
{
[Link](a[i] +”\n”);
}
Use of for–each Loop:
The for–each loop may be used to access each element of the one dimensional array.
for (int x: numbers)
{ [Link](x);
}
For a two-dimensional array the nested for–each loops are used.
int TwoArray [][]= {{1,2,3},{4,5,7}};
for(int [] y : TwoArray)
{
for(int x : y)
[Link](x + “ ”);
[Link]();
}
6. Array of Strings
We can form array with elements as String as we have used primitive [Link]
String is class in java standard library.
Syntax: String s[]={“JAVA”, “FLAT”, “DBMS”};
Example,
class StrTest
{ public static void main(String arg[])
{ String str[]={"JAVA”, “FLAT”, “DBMS”};
for(String x:str)
{
[Link](x);
}
}
}
. 3|Page
Example program for Operations on Array Elements, [Link]
import [Link].*;
class ArrOperations
{
static void display(int a[])
{
for(int i=0;i<[Link];i++)
{
[Link](a[i]+"\t");
}
}
public static void main(String arg[])
{ int []arr1,arr2,arr3; // arrays declaration
int n,i;
Scanner in=new Scanner([Link]);
[Link]("Enter the size of the arrays:");
n=[Link]();
arr1=new int[n]; //memory allocation to array
arr2=new int[n];
arr3=new int[n];
//reading elements into array
[Link]("Enter elements into arr1:");
for(i=0;i<n;i++)
{
[Link]("Enter %d element:",i);
arr1[i]=[Link]();
}
[Link]("Enter elements into arr2:");
for(i=0;i<n;i++)
{
[Link]("Enter %d element:",i);
arr2[i]=[Link]();
}
[Link]("Addition of two arrays is:");
for(i=0;i<n;i++)
{
arr3[i]=arr1[i]+arr2[i];
}
display(arr3); //method call
}
}
Output:
D:/CSE>javac [Link]
D:/CSE>java ArrOperations
Enter the size of the arrays: 4
Enter elements into arr1:
Enter 0 element:2
Enter 1 element:4
Enter 2 element:6
. 4|Page
Enter 3 element:8
Enter elements into arr2:
Enter 0 element:12
Enter 1 element:14
Enter 2 element:16
Enter 3 element: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<[Link];i++)
{
[Link](a[i]+"\t");
}
}
static void add(int a[],int b[])
{
int c[]=new int[[Link]];
[Link]("Addition of two arrays is:");
for(int i=0;i<[Link];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.
. 5|Page
Example, Illustration of assigning of an array to another array
class AssignOneArraytoAnother
{
public static void main(String arg[])
{
int[] arr1,arr2; //declaration
arr1=new int[]{2,4,6,8}; //memory allocation and initialization to array
arr2=arr1; // assigning arr1 to arr2
[Link]("Elements of arr2 are:"); //display arr2
for(int x:arr2)
[Link](x+"\t");
for(int i=0;i<[Link];i++)
arr1[i]=arr1[i]*5; //modifying the arr1 elements
[Link]("\nElements of arr1 after modification are:"); //display arr1
for(int x:arr1)
[Link](x+"\t");
[Link]("\nElements of arr2 after modification are:"); //display arr2
for(int x:arr2)
[Link](x+"\t");
}
} Output:
. 6|Page
for(int x:arr1)
[Link](x+"\t");
arr1=new int[6]; //dynamic change of array size
//display arr1
[Link]("\nElements of arr1 after Size Change are:");
for(int x:arr1)
[Link](x+"\t");
} } Output:
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
. 7|Page
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.
29, 30, 52, 63, 27, 19, 54, 87
b) Compare 30 and 52. Since 30 < 52, no swapping is done.
c) Compare 52 and 63. Since 52 < 63, no swapping is done.
d) Compare 63 and 27. Since 63 > 27, swapping is done. 29, 30, 52, 27, 63, 19, 54, 87
e) Compare 63 and 19. Since 63 > 19, swapping is done. 29, 30, 52, 27, 19, 63, 54, 87
f) Compare 63 and 54. Since 63 > 54, swapping is done.
29, 30, 52, 27, 19, 54, 63, 87
Observe that after the end of the second pass, the second largest element is placed at
the second highest index of the array. All the other elements are still unsorted.
Pass 3:
a) Compare 29 and 30. Since 29 < 30, no swapping is done.
b) Compare 30 and 52. Since 30 < 52, no swapping is done.
c) Compare 52 and 27. Since 52 > 27, swapping is done. 29, 30, 27, 52, 19, 54, 63, 87
d) Compare 52 and 19. Since 52 > 19, swapping is done. 29, 30, 27, 19, 52, 54, 63, 87
e) Compare 52 and 54. Since 52 < 54, no swapping is done.
Observe that after the end of the third pass, the third largest element is placed at the
third highest index of the array. All the other elements are still unsorted.
Pass 4:
a) Compare 29 and 30. Since 29 < 30, no swapping is done.
b) Compare 30 and 27. Since 30 > 27, swapping is done. 29, 27, 30, 19, 52, 54, 63, 87
c) Compare 30 and 19. Since 30 > 19, swapping is done. 29, 27, 19, 30, 52, 54, 63, 87
d) Compare 30 and 52. Since 30 < 52, no swapping is done.
Observe that after the end of the fourth pass, the fourth largest element is placed at the
fourth highest index of the array. All the other elements are still unsorted.
Pass 5:
a) Compare 29 and 27. Since 29 > 27, swapping is done.
27, 29, 19, 30, 52, 54, 63, 87
b) Compare 29 and 19. Since 29 > 19, swapping is done. 27, 19, 29, 30, 52, 54, 63, 87
c) Compare 29 and 30. Since 29 < 30, no swapping is done.
Observe that after the end of the fifth pass, the fifth largest element is placed at the
fifth highest index of the array. All the other elements are still unsorted.
. 8|Page
Pass 6:
. 9|Page
a[i]=[Link]();
}
display(a);
bsort(a);
display(a);
}
}
Output:
2. Selection Sort
Selection sort is an algorithm that selects the smallest element from an unsorted list in
each iteration and places that element at the beginning of the unsorted list. This sorting
algorithm is an in-place comparison-based algorithm in which the list is divided into two
parts, the sorted part at the left end and the unsorted part at the right end. Selection sort
performs worst than insertion sort algorithm better than bubble sort.
Example, Consider the data elements: 5, 2, 1, 3, 6, 4
Selection sort works as follows:
First find the smallest value in the array and place it in the first position.
Then, find the second smallest value in the array and place it in the second position.
Repeat this procedure until the entire array is sorted.
Example: Consider the data elements: 5, 2, 1, 3, 6, 4
Pass 1:
In this special case, the next smallest element is in the second position already.
Swapping the element with itself keeps it in the same position.
. 10 | P a g e
After the next smallest element is in the second position, we continue as above for the
next smallest element.
Pass 3:
Next search for the next smallest element from the fourth element.
Pass 4:
Next search for the next smallest element from the fifth element
Pass 5:
. 11 | P a g e
{
//change key position
key=j;
}
}
if(i!=key)
{
//swapping
int t=a[key];
a[key]=a[i];
a[i]=t;
}
}
}
public static void main(String arg[])
{
int a[],i,j,n;
Scanner in=new Scanner([Link]);
[Link]("Enter size of Array:");
n=[Link]();
a=new int[n];
//read element into array
[Link]("Enter elements into array:");
for(i=0;i<n;i++)
{
[Link]("Enter %d Element",i);
a[i]=[Link]();
}
display(a);
ssort(a);
display(a);
}
}
Output:
. 12 | P a g e
3. Insertion Sort
Insertion sort is a technique, which inserts an element at an appropriate location by
comparing each element with the corresponding elements present at its left and
accordingly moves rest of the given array.
Insertion sort is a very simple sorting algorithm in which the sorted array is built one
element at a time.
The main idea behind insertion sort is that it inserts each item into its proper place in
the final list. To save memory, most implementations of the insertion sort algorithm
work by moving the current data element past the already sorted values and
repeatedly interchanging it with the preceding value until it is in its correct place.
Insertion sort is less efficient as compared to other more advanced algorithms such as
quick sort, heap sort, and merge sort.
Example , Arrange the data elements 5, 2, 1, 3, 6, 4 into ascending order.
Pass 1:
Consider the first element. For only one element no sort is required, because it is the
trivial case. A[1] by itself is trivial sorted. Hence start with second element and
compare it with first element and put into the correct place.
Pass 2:
Since second element is less than first element, insert it in first position. The array
now changes like,
Pass 3: Next take the third element and insert into its proper position in the first three
positions.
Since the third element is less than both first and second elements, insert it in the first
position and move the other two elements into next positions in the same order. The
array now changes like,
Pass 4: Similarly, pick the fourth element and insert into its proper place in the positions
from first to fourth.
Pass 5: Similarly, pick the fifth element and insert into correct place between the positions
first and fifth.
. 13 | P a g e
Here, the fifth element is already in the sorted position. The array is now,
Pass 6: Similarly, pick the last element and insert into its proper place in the positions from
first to sixth.
Since the correct position for the last element is fourth position, insert it into that
position and move the greater elements down to the list. Now, the array looks like,
. 14 | P a g e
To partition the data elements, a pivot element is to be selected such that all the items in
the lower-part are less than the pivot and all those in the upper part greater than it. In this
method, the list is divided into two, based on the element called pivot element. Usually, the
first element is considered to be the pivot element. The process is reapplied to each of these
partitions. This process proceeds till we get the sorted list of elements.
Procedure:
[Link] the process.
2. Read the array elements.
3. Select the first element as the pivot element.
4. Initialize i and j to the first and last of the array elements.
5. Increment i, until a[i] > pivot, stop.
6. Decrement j, until a[j] < pivot, stop
7. If j > i or i < j then interchange a[i] and a[j]
8. Repeat steps 5, 6, and 7 until j < i or i > j
9. If (j < i) then interchange pivot element with a[j]
10. Apply the partition method to the array elements
11. Stop the process
In the partition phase, we have to move the elements less than or equal to pivot
towards the left and those greater than or equal toward the right.
If i < j then swap a[i] and a[j] and repeat the process.
. 15 | P a g e
Since i <= j, swap a[i] and a[j] and repeat the process.
At this stage the pivot 5 is in its proper place. i.e., elements left to it are less than or
equal to 5 and elements to its right are greater than or equal to 5. The quick sort
process can be applied to each of these sub-arrays until all elements are in sorted
order.
. 16 | P a g e
// Program for implementation of QuickSort
class QuickSort
{
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
if (arr[j] <= pivot) // If current element is smaller than or equal to pivot
{
i++;
int temp = arr[i]; // swap arr[i] and arr[j]
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1]; // swap arr[i+1] and arr[high] (or pivot)
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now at right place */
int pi = partition(arr, low, high);
sort(arr, low, pi-1); // Recursively sort elements before partition and after partition
sort(arr, pi+1, high);
}
}
static void printArray(int arr[])
{
int n = [Link];
for (int i=0; i<n; ++i)
[Link](arr[i]+" ");
[Link]();
}
public static void main(String args[]) // Driver program
{
. 17 | P a g e
int arr[] = {10, 7, 8, 9, 1, 5};
int n = [Link];
QuickSort ob = new QuickSort();
[Link](arr, 0, n-1);
[Link]("sorted array");
printArray(arr);
}
}
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
. 18 | P a g e
{
public static void main(String arg[])
{
int a[],n,i,key,pos=0;
boolean b=false;
Scanner in=new Scanner([Link]);
[Link]("Enter size of array:");
n=[Link]();
a=new int[n]; //creating array
//read elements into array
for(i=0;i<n;i++)
{
[Link]("Enter %d element:",i);
a[i]=[Link]();
}
[Link]("Enter Key:");
key=[Link]();
//linear search starts
for(i=0;i<n;i++)
{
if(key==a[i])
{
b=true;
pos=i;
break;
}
}
if(b==true)
[Link](" The element found at :"+pos);
else
[Link](" The element not found");
}
}
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:
a) If ( A[Mid] = = Search element) then search is successful.
b) If A[Mid] < Search element, then Search element will be present in the right
segment of the array. So, the value of Low will be changed as High = Mid Pos – 1
and again calculated the middle element position.
c) If A[Mid] > Search element, then Search element will be present in the left segment of
the array. So, the value of High will be changed as Low = Mid Pos + 1 and again
calculated the middle element position.
. 19 | P a g e
Finally, if Search element is not present in the array, then eventually, High will be less
than Low. When this happens, the algorithm will terminate and the search will be
unsuccessful.
Working of Binary Search :
For a binary search to work, it is mandatory for the target array to be sorted.
For example, Consider an order list L = { 12, 21,34, 38, 45, 49, 67, 69, 78, 79, 82, 87, 93,
97, 99 }.
Let us search for the search element = 21 in the order list L. Initially, Low = 1, and High = 15
and calculate the middle element position.
Middle element position = ( Low + High ) / 2
= (1 + 15)/2 = 8
. 20 | P a g e
Example Program [Link]
import [Link].*;
class BinearySearch
{
public static void main(String args[])
{
int n,a[],item,first,last,middle;
//reading [Link] elements
Scanner in = new Scanner([Link]);
[Link]("Enter the number of elements:");
n=[Link]();
a=new int[n];
//read elements into array
[Link]("Enter elements into array:");
for(int i=0;i<n;i++)
a[i]=[Link]();
first=0;
last=n-1;
middle=(first+last)/2;
[Link]("Enter element to search:");
item=[Link]();
//search process
while(first<=last)
{
if(a[middle]==item)
{
[Link]("Item found at"+middle);
break;
}
else if(a[middle]<item)
{
first=middle+1;
}
else
{
last=middle-1;
}
middle=(first+last)/2;
}
if(first>last)
{
[Link]("Item not found");
}
}
}
. 21 | P a g e
Methods of Arrays class:
Sorting – The class has defined several overloaded methods for sorting arrays of
different types.
The sort() has the following overloaded methods.
i) public static void sort (int[] array)
ii) public static void sort(int[] array, int startIndex, endIndex) - This method sorts
the specified subset of the array of type int from startIndex to endIndex.
Searching(Binary search) –There are two versions of overloaded binary search methods that
are defined in the Array class.
1. public static int binarySearch(int [], int Key) –similar overloaded methods are
defined for other types such as byte, short, double etc; here the key is the value
to be searched, and it returns the position of the element where a match is
found.
2. public static int binarySearch(double [], int startIndex, int endIndex, double
Key) – This will search key in between startIndex and endIndex.
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)
Filling -This method is used to fill the entire array with the specified value as shown in the
following syntax.
public static void fill(byte[], byte value) –fills entire array with value.
public static void fill(byte[], int s_index, e_index, byte value) –fills the
elements from s_index to e_index, but e_index will not be included.
Copying –The following method copies the array into new array of specified length. If the
specified length is smaller than the original array length, then the remaining elements are cut-
off.
public static byte[] copyOf (byte[] original, int length)
public static char[] copyOfRange(char[] original, int s_index,int e_index)
toString() method
The method header is given as public static String toString (int [] array)
The method returns a string representation of the array elements.
hashCode() method
This method returns content-based hashCode of the array.
public static int hashCode(float [] array) – it returns an integer corresponding
the array given as argument.
deepToString() method
This method is used to convert the multidimensional array into string.
public static String deepToString(object [] array)
Example Program for Arrays Class
import [Link];
//sorting the elements
class ClassArrayFill
{
public static void main(String arg[])
{
int[] a={5,7,2,1,8,6,8,9};
int[] b={1,2,3};
float[] c={12.3f,4.5f,2.1f,6.54f,9.2f};
[Link]("Arrays a and b are equal :"+[Link](a,b)); //equals test
. 22 | P a g e
[Link](c,1,3,25.3f); //filling the array
[Link]("Contents of array C are:");
for(float x:c)
[Link](x+"\t");
[Link]();
[Link](a); //Sorting the array
for(char x:a)
[Link](x+"\t");
[Link]()
String s=[Link](a); //toString
[Link](s);
int arr2[]=[Link](b,[Link]); //copying
[Link]("Arr2 is :");
for(int x:arr2)
[Link](x+"\t");
[Link]("The hashcode for array ‘a’ is:"+[Link](a)); //hash code
}
}
14. Two-Dimensional Arrays
An Array may hold arrays as its elements. If the elements of an array are one-
dimensional arrays, then it is called Two-dimensional array. In Java, 2-D array is treated as
array of arrays. Some of the examples for 2-D arrays are : Matrices, and Sales details in 4
quarters etc; A 2-D array is created as follow: int mat[][]=new int[3][5]; Here, mat is the
name of the 2-D array, contains 3 arrays, where each array contains 5 elements.
int [][] mat={{1,2,3,4,5},{4,5,6,7,8},{10,11,12,13,14,15}};
Example, Defining and Displaying 2-D Array - Operations on Arrays
import [Link];
import [Link].*;
class MatTest
{
public static void main(String arg[])
{
int[][] A,B;
int r,c,i,j;
Scanner in=new Scanner([Link]);
[Link]("Enter rows and columns:");
r=[Link]();
c=[Link]();
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++)
{
[Link]("Enter A[%d][%d] element:",i,j);
A[i][j]=[Link]();
}
}
for(i=0;i<r;i++) //reading elements into matrix B
{
. 23 | P a g e
for(j=0;j<c;j++)
{
[Link]("Enter B[%d][%d] element:",i,j);
B[i][j]=[Link]();
}
}
[Link]("Matrix A is:"); //display arrays A and B
[Link]([Link](A));
[Link]("Matrix B is:");
[Link]([Link](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];
}
}
[Link]("Matrix C is:");
[Link]([Link](C));
} }
Matrix Multiplication
// Check if multiplication is Possible
if (row2 != col1) {
[Link](
"\nMultiplication Not Possible");
}
else{
// Matrix to store the result. The product matrix will be of size row1 x col2
int C[][] = new int[r][c];
for (i = 0; i < r; i++) { // Multiply the two matrices
for (j = 0; j < c; j++) {
for (k = 0; k < r; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
15. Arrays of Varying Lengths
In Java, a two-dimensional array is treated as an array whose elements are one dimensional
arrays, which may have different sizes, that is, different number of elements. This is not
possible in C or C ++. A two-dimensional array may be declared asint a2D [][] = new int [3
][]; The arrays may as well be declared as int array [][] = {{5, 7, 8 },{10, 11 }, {4, 3, 2, 7,5
}};
. 24 | P a g e
Example Program:
. 25 | P a g e
The difference between Vectors and Arrays is, Vectors are dynamically allocated,
where Arrays are static.
The Vector class is defined in [Link] package.
Vectors stores the pointers to the objects and not the objects themselves.
Vector Constructors
The Vector class has the following constructors:
Vector vec=new Vector() – Creates a default vector with initial size as 10
Vector(int size) - Creates a Vector whose initial capacity is specified by size.
Vector(int size, int incr) –Creates a Vector with initial capacity as size, and
increment of element is specified by incr. Here, the increment is the number of
elements added in each reallocation cycle.
Advantages
Vectors are dynamically allocated
Size of the vectors can be changed as and when required.
They can store dynamic list of objects.
The objects can be added or deleted from the vectors.
Important methods of Vector Class
void add(int index, Object element) –Inserts the element at specified position.
void addElement(Object element) –adds the element at the end of the vector, and
increases its size by one.
void clear() –removes all the elements from the vector.
int capacity() –returns the current capacity of the vector.
int size() –returns the number of elements currently in the Vector.
Object firstElement() -returns the first element from the vector
Object lastElement() – returns the last element from the Vector
Object get(int index) –returns the element at specified index.
Object remove(int index) –removes the element at specified index.
Example Program [Link]
import [Link].*;
class VecTest
{
public static void main(String arg[])
{
Vector vec=new Vector(); //create vector
[Link]("The capacity of Vector is:"+[Link]());
[Link](40);
[Link](50);
[Link]("The current size of the vector is:"+[Link]());
Enumeration e=[Link]();
while([Link]())
{
[Link]([Link]()+"\t");
}
[Link]("Remove element at index1:"+[Link](1)); //deleting element
e=[Link]();
while([Link]())
{
[Link]([Link]()+"\t");
}
} }
. 26 | P a g e
18. Introduction to Inheritance
Inheritance is the backbone of object-oriented programming (OOP). It is the mechanism
by which a class can acquire properties and methods of another class. Using inheritance, an
already tested and debugged class program can be reused for some other application. This
class is often termed as ‘base class’ or ‘Super class’. The other class that is created in this
application will inherit the fields and methods of the base class, and implements its own code.
The following terminology is used in this context.
Super class This is the existing class from which another class, that is, the subclass is
generally derived. In Java, several derived classes can have the same super class.
Subclass A class that is derived from another class is called subclass. In Java, a
subclass can have only one super class. This restriction is not present in C++, which
supports several base classes for the derived class.
Benefits of Inheritance
It allows the reuse of already developed and debugged class program without any
modification.
The super class is more general in its scope, where as the sub class is more
specialized. It allows a number of subclasses to fulfil the needs of several subgroups.
A large program may be divided into suitable classes and subclasses that may be
developed by separate teams of programmers.
The process of inheritance may or may not be stopped with one derived class. In fact,
another class, may be derived from the previously derived class. For example, class B
is derived from class A and class C is derived from class B.
19. Process of Inheritance
Inheritance means deriving some characteristics from something that is generic. In the
context of Java, it implies deriving a new class from an existing old class, that is, the super
class. A super class describes general characteristics of a class of objects. A subset of these
objects may have characteristics different from others. There are two ways of dealing with
this problem. First, make a separate class for the subset to include all the characteristics.
Second, to have another class that inherits the existing class, extend this class to include the
special characteristics. The keyword extends is used by the sub class to inherit the properties
of super class.
The syntax of the inheritance will be as follow:
Where B is derived class which is inheriting the properties, and class A is the super class
from which properties are acquired.
. 27 | P a g e
i) Single Inheritance
In Single Inheritance one class extends another class (one class only). A subclass
inherits the properties of one super class.
. 28 | P a g e
Figure) Multiple Inheritance
In the above diagram, Class C extends Class A and Class B. A and B are the super
classes and C is a subclass.
iii). Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as
the derived class also acts as the base class for other classes.
. 29 | P a g e
void product()
{
[Link]("The product is:"+(i*j));
}
}
class MultilevelInheritance
{
public static void main(String arg[])
{
C c=new C();
[Link](20,6);
[Link]();
[Link]();
[Link]();
}
}
. 30 | P a g e
}
}
class D extends A
{
void displayD()
{ [Link](".... Sub Class D");
}
}
public class HierarchicalInheritance
{ output:
public static void main(String[] args)
{
B b1 = new B();
[Link]();
[Link]();
C c1 = new C();
[Link]();
[Link]();
D d1 = new D();
[Link]();
[Link]();
} }
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.
. 31 | P a g e
The syntax of different types of inheritance:
. 32 | P a g e
Example program for Object class:
class ObjectTest extends Object
{
void display()
{
[Link]("Demo on Object class");
}
public static void main(String arg[])
{
ObjectTest t=new ObjectTest();
A a=new A();
A b=a;
String s=[Link]();
[Link](s);
[Link]("HasCode is :"+[Link]());
[Link]("Objects a and b are same:"+[Link](b));
[Link]();
} }
22. Inhibiting (preventing) Inheritance of Class using Final
A class may be prevented from being inherited by other classes by declaring it using
the keyword ‘final’. When a class is declared with final keyword, it is called a final class. A
final class cannot be extended(inherited).The keyword is used in the following situations. If a
class definition is complete and if it is not required to be further sub-classed, it can be
declared as final. A class declared as final cannot be inherited further. Class variables or
instance variables are declared as final to make them as constants. When the keyword is used
before the super class method name, it prevents the method overriding.
//Example program to Illustrate the final class.
final class A
{
void dispA()
{
[Link]("Method of class A");
}
}
class B extends A //here A cannot be inherited
{
void dispB()
{
[Link]("Method of class B");
}
}
class FinalTest
{
public static void main(String arg[])
{
B b=new B();
[Link]();
[Link]();
}
}
. 33 | P a g e
23. Access Control and Inheritance
A derived class access to the members of a super class may be modified by access specifiers.
There are three access specifiers, that is, public, protected, and private. The syntax of
specifying access specifier is as follow:
Access-specifier type member_identifier;
Access Specifiers Access
No access specifier Access is permitted to any other class within the same package
public Access is permitted to any class in any package.
protected Access is permitted to any sub class in any package, also
within the same package.
private Access is permitted only to the members of the same class.
Examples:
private int i; // i is a private variable
public int j; // j is a public variable
protected int k; // k is a protected variable
int x; // x is a default access modifier variable
Java addresses five categories of visibility for class members:
Sl No Class member Private Default Protected Public
Member Member Member Member
. 34 | P a g e
[Link]("n_pub = " + n_pub);
}
}
class Derived extends Protection
{
Derived()
{
[Link]("derived constructor");
[Link]("n = " + n);
// [Link]("n_pri = "+ n_pri); // class only
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
}
}
. 35 | P a g e
[Link](" *** Name: "+name);
[Link](" *** Age:"+age);
[Link](" *** Empid:"+empid);
}
}
class Employee extends Person { // create a sub class
String job; // instance variables
float salary;
Employee(String eno,String n,int a, String job,float salary) // Employee is a sub class
constructor method;
{
super(a,n,eno); //calling the super class constructor method
[Link](); //calling the super class display() method
[Link]("CSE BRANCH CODE: "+[Link]); //calling the super classz
variable
[Link]=job; //local variables are hiding instance variables. So we have use this .
[Link]=salary;
}
void displayEmployeeDetails() {
displayPersonDetails(); // calling the super class method
[Link](" *** Job:"+job);
[Link](" *** Salary Rs:"+salary);
}
} //end of subclass
public class SuperExample {
public static void main(String args[]) {
Employee emp=new Employee("SACET180","Karth",25,"Software",90000);
[Link]();
}
}
Output:
. 36 | P a g e
While implementing inheritance in a Java program, every class has its own
constructor. Therefore the execution of the constructors starts after the object initialization. It
follows a certain sequence according to the class hierarchy. There can be different orders of
execution depending on the type of inheritance. In multilevel inheritance, all the upper class
constructors are executed when an instance of bottom most child class is created.
Example , // Demonstrate on Constructor method and inheritance
class A
{
A()
{
[Link]("Class A method");
}
}
class B extends A
{
B()
{
[Link]("Class B method");
}
}
class C extends B
{
C()
{
[Link]("Class C method");
} }
class ABC
{
public static void main(String args[])
{
[Link]("Order of constructor execution in Multilevel Inheritance");
C c1=new C();
}
}
. 37 | P a g e
Why Overridden Methods?
overridden methods allow Java to support run-time polymorphism. Overridden methods are
another way that Java implements the “one interface, multiple methods” aspect of
polymorphism. By combining inheritance with overridden methods, a superclass can define
the general form of the methods that will be used by all of its subclasses.
// A Java program to illustrate Method Overriding using hierarchical inheritance
class Shape {
void draw()
{
[Link]("Drawing...");
}
}
class Rectangle extends Shape
{ Output:
void draw()
{
[Link]("Drawing Rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
[Link]("Drawing Circle...");
} }
class Triangle extends Shape {
void draw()
{
[Link]("Drawing Triangle...");
}
}
public class RuntimePolymorphism
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
[Link]();
s=new Circle();
[Link]();
s=new Triangle();
[Link]();
} }
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.
. 38 | P a g e
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 [Link]
class Vehicle {
final void display()
{
[Link]("Vehicle Details");
}
}
class Car extends Vehicle{
void display()
{
[Link]("Car Details");
}
}
class StatBinding {
public static void main(String arg[])
{
Car c=new Car();
[Link]();
}
}
Output:
D:\CSE>javac [Link]
[Link]: error: display() in Car cannot override display() in Vehicle
void display()
^
overridden method is final
1 error
Example program for Dynamic Binding [Link]
class Vehicle {
void display()
{
[Link]("Vehicle Details");
}
}
class Car extends Vehicle {
void display()
{
[Link]("Car Details");
}
}
class DynamicBinding {
public static void main(String arg[])
{
Vehicle c=new Car();
[Link]();
}}
. 39 | P a g e
28. Abstract Classes
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Any class that contains one or more abstract methods must also be
declared abstract. To declare a class abstract, you simply use the abstract keyword in front of
the class keyword at the beginning of the class declaration. There can be no objects of an
abstract class. That is, an abstract class cannot be directly instantiated with the new operator.
Such objects would be useless, because an abstract class is not fully defined. You cannot
declare abstract constructors, or abstract static methods.
Abstract class can have abstract and non-abstract methods. Abstract class doesn’t
support multiple inheritance. Any subclass of an abstract class must either implement all of
the abstract methods in the superclass, or be declared abstract itself.
To declare an abstract class, use this general form:
abstract class Classname
{
Variables declaration;
Methods declaration;
}
To declare an abstract method, use this general form: abstract type name(parameter-list);
Example program for Abstract class:
import [Link];
abstract class Shapes {
abstract void findTriangle(double b, double h);
abstract void findRectangle(double l, double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}
class FindArea extends Shapes {
void findTriangle(double b, double h)
{
double area = (b*h)/2;
[Link]("Area of Triangle: "+area); Output:
}
void findRectangle(double l, double b)
{
double area = l*b;
[Link]("Area of Rectangle: "+area);
}
void findSquare(double s)
{
double area = s*s;
[Link]("Area of Square: "+area);
}
void findCircle(double r)
{
double PI =3.14;
double area = PI*r*r;
[Link]("Area of Circle: "+area);
}
}
. 40 | P a g e
public class Areas {
public static void main(String args[])
{
double l, b, h, r, s;
FindArea area = new FindArea();
Scanner get = new Scanner([Link]);
[Link]("\nEnter Base & Vertical Height of Triangle: ");
b = [Link]();
h = [Link]();
[Link](b, h);
[Link]("\nEnter Length & Breadth of Rectangle: ");
l = [Link]();
b = [Link]();
[Link](l, b);
[Link]("\nEnter Side of a Square: ");
s = [Link]();
[Link](s);
[Link]("\nEnter Radius of Circle: ");
r = [Link]();
[Link](r);
}
}
. 41 | P a g e
30. Introduction Interfaces
Interface is an abstract way of defining the structure of a class. It is a collection of
abstract methods. An interface is declared by using the interface keyword. A class
implements an interface, thereby inheriting the abstract methods of the interface.
A class uses the implements keyword to implement an interface and it appears in the
class declaration. An interface is implicitly abstract. You do not need to use
the abstract keyword while declaring an interface. Each method in an interface is also
implicitly abstract, so the abstract keyword is not needed.
. 42 | P a g e
32. Declaration of Interface
Declaration of an interface starts with the access modifier followed by keyword
interface.
It is in turn followed by its name or identifier that is followed by a block of
statements;
These statements contain declarations of variables and abstract methods.
The variables defined in interfaces are implicitly public, static, and final.
They are initialized at the time of declaration.
The methods declared in an interface are public, and abstract by default
Syntax for defining an Interface
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
... ……………………
return-type method-nameN(parameter-list);
type final-varnameN = value;
}.
Example
public interface Data
{
double PI=3.14; // final fields
void area(int r); //abstract methods
}
Members of Interface:
The members are declared in the body of the interface.
The members inherited from any super interface that it extends.
The methods declared in the interface are implicitly public abstract member methods.
The field variables defined in interfaces are implicitly public, static, and final.
The field variables declared in an interface must be initialized; otherwise, compile-
type error occurs.
Since Java SE8, static and default methods with full definition can also be members
of interface.
33. Implementation of Interface
Once an interface has been defined, one or more classes can implement that interface.
Declaration of class that implements an interface
Syntax for implementing Interfaces:
class classname implements interfacename
{
// class-body
}
. 43 | P a g e
For example, implements Multiple Inheritance using Interfaces:
Multiple Inheritance is one of the inheritance type in Java where one class extending
more than one class. Java does not support multiple inheritance. Multiple inheritance
can be achieved using the concept of interfaces in java.
Syntax:
interface Interface1 {
//Interface1 body
}
interface Interface2 {
//Interface2 body
}
class subclassname implements Interface1, Interface2
{
// class-body
}
Example Program for Multiple Inheritance using Interfaces
import [Link];
interface Interface1
{
void add(int x ,int y);
void average(double x, double y , double z );
}
interface Interface2
{
void mul(double p , double q);
}
class Test implements Interface1, Interface2
{
public void add(int x, int y)
{
int sum=x+y;
[Link]("SUM :"+sum);
}
public void average(double a, double b, double c)
{
double avg=(a+b+c)/3;
[Link]("AVERAGE:"+avg);
}
public void mul(double p, double q)
{
double m=p*q;
[Link]("MULTIPLICATION:"+m);
}
}
public class MultipleInheritanceDemo
{
public static void main(String args[])
{
Test obj = new Test();
Scanner in = new Scanner([Link]);
. 44 | P a g e
[Link]("***INTERFACE1 DATA***"); Output:
[Link]("Enter x value: ");
int x = [Link]();
[Link]("Enter y value: ");
int y= [Link]();
[Link](x,y);
[Link]("Enter a value: ");
double a = [Link]();
[Link]("Enter b value: ");
double b = [Link]();
[Link]("Enter c value: ");
double c = [Link]();
[Link](a,b,c);
[Link]("***INTERFACE2 DATA***");
[Link]("Enter p value: ");
double p = [Link]();
[Link]("Enter q value: ");
double q = [Link]();
[Link](p,q);
}
}
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
{
. 45 | P a g e
void add(int a,int b);
}
class MultiInterfaceImpliment implements InterfaceA, InterfaceB
{
public void show() // InterfaceA method
{
[Link](“Hello! this is InterfaseA method");
}
public void add(int x,int y) // InterfaceB method
{
[Link]("Sum is :"+(x+y));
}
void sub(int x,int y) // class method
{
[Link]("subtraction is:"+(x-y));
}
}
class MultiInterfaceTest
{
public static void main(String arg[])
{
// creating interface references and assigning class object
InterfaceA i1=new MultiInterfaceImpliment ();
[Link](); // invoking the InterfaceA method
InterfaceB i2=new MultiInterfaceImpliment (); //here i2 is interface reference object
[Link](9,3); // invoking the InterfaceB method
MultiInterfaceImpliment m1=new MultiInterfaceImpliment();
[Link](9,3); //sub() is the method of implementing class
}
}
Stub Methods :
If a class implements an interface, it has to define all its abstract methods; if we fail to
do so, then it will make the implementing class an abstract class. In several cases, we do not
need to define all the methods because we need only a few of these. In order to meet the
requirement, we define stub methods for the methods we do not need. A stub method does not
do anything; however, it fulfils the requirement.
// Illustration of definitions of stub methods
interface AreaVolume {
double surfaceAreaSphere (double radius);
double volumeShpere (double radius);
void setValue (double side);
} // end of interface
public class StubMethod {
double surfaceAreaSphere (double radius) //Definition of stub method for surfaceAreaSphere
{ return 0; }
void setvalue (double side) {}//Definition of stub method for setValue
double volumeSphere (double radius) // definition of method that is implemented
{return 4.0*[Link]* [Link](radius, 3)/3 ;}
public static void main(String[] args) { // main method
StubMethod stm = new StubMethod();
. 46 | P a g e
[Link](“Volume of sphere of radius 10 = %.2f \n”, [Link](10.0));
}} Output:Volume of sphere of radius 10 = 4188.79
. 47 | P a g e
double PI=3.14; Output:
return PI*r*r;
}
public void show()
{
[Link]("Nested interfaces Demo");
}
}
class NestedTest {
public static void main(String arg[])
{
A a=new A();
[Link]("Area of Circle:"+[Link](2));
[Link]();
}}
. 48 | P a g e
class InheritanceOfInterface output:
{
public static void main(String arg[])
{
Circle c1=new Circle();
[Link]();
}
}
. 49 | P a g e
Example 2 , // Illustration of inheritance of interfaces by using default method
interface InfaceA {
public void showA();
default public void display()
{
[Link](“Good morning to everyone”);
}
}
interface InfaceB extends InfaceA {
public void showB();
default public void display()
{
[Link](“Good bye to everyone”);
}
class DefaultMethodB implements InfaceB {
public static void main(String args[])
{
public void showA()
{
[Link](“It is Interface A”);
}
public void showB()
{
[Link](“It is Interface B”);
}
DefaultMethodB d = new DefaultMethodB();
[Link]();
[Link](); //display() method is accessed for the interface InfaceA.
[Link]();
}
}
. 50 | P a g e
38. Static Methods in Interface
The Java version 8 allows full definition of static methods in interfaces. A static method
is a class method. For calling a static method, one does not need an object of class. It can
simply be called with class name as class_name.method_name(); Static methods are called
with Interface name as [Link](). A class that implements an interface also
inherits all its static methods. The inherited method is also a class method, and therefore, the
method can simply be called by using class name as illustrated.
Example, // Illustration of static method in interface
interface InFace1 // defining an interface
{
int number =1000;
static void compute (int num) // static method defined
{
Output
int cube = num * num * num ;
Cube root of 1000 = 10.0
[Link]( “Cube of” + num + “ = ” + cube );
Cube of 10 = 1000
}
}
public class StaticMethod implements InFace1 // implementing an interface
{
public static void main(String[] args) {
StaticMethod sm = new StaticMethod(); // creating object
//The Java [Link]() method returns the cube root of the specified number. //Here, cbrt() is
a static method. Using number defined in interface
[Link](“Cube root of 1000 = ” + [Link](number));
[Link](10); //static method is called with interface name
}
}
. 51 | P a g e
Function: The Function interface has an abstract method apply which takes argument of type
T and returns a result of type R. Its prototype is
public interface Function
{
public R apply(T t);
}
Example1, //Illustration of uses of functional interfaces Function and BinaryOperator
import [Link];
import [Link];
public class BiOperator
{
public static void main(String args[])
{
Function <Double, Double>logrithm = Math::log;
// method reference assigned to Function
[Link]( “log of 10 to the base e = ” + [Link](10.0));
// apply() method performs the operation on the given arguments and returns the function
result.// method reference assigned to BinaryOperator
BinaryOperator<Integer> minimum = Math::min;
[Link] (“Minimum of 20 and 46 is ” + [Link](20, 46));
} Output: log of 10 to the base e = 2.302585092994046
} Minimum of 20 and 46 is 20
. 52 | P a g e
Example2, //Illustration of application of predicates in filtering arrays
import [Link];
public class PredicateEx {
public static void main(String[] args) { // main class
//isEqual() is used to compare strings with string “Chirala” to test if they are equal.
Predicate<String>str = [Link]("Chirala"); output:
// using Predicate to test for "Chirala"
[Link]([Link]("Chirala"));
String [] names={"Bapatla", "Ongole" ,"Chirala"};
for(int i =0; i<[Link]; i++) // for loop
if ([Link] (names[i]))
[Link](names[i]);
for(String s: names) // filtering the array
if ()
[Link](s +" ");
}}
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 [Link];
class FunTest{
static void disp(double t)
{
[Link](t+"\t");
}
public static void main(String arg[]) {
Consumer<Double>consumer=(Double d)->{disp(d);};
[Link](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 [Link] 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 [Link];
class MyNumber
{ int getNumber()
. 53 | P a g e
{
return (int) ([Link]()*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=[Link]();//supplies an object as argument
[Link]("The new number is:"+[Link]());
}
}
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
{
[Link]("Floating point Sum is :"+(x+y));
}
}
class Y extends X
{
@Override
void add(int x, int y) // integers as paramters
{
[Link]("Integer Sum is :"+(x+y));
}
}
class AnnoTest
{
public static void main(String arg[])
. 54 | P a g e
{
Y y=new Y();
[Link](2,3.4);
}
}
. 55 | P a g e
Marker Annotation - An annotation that has no method, is called marker
annotation. For example: @interface MyAnnotation { }
Single-Method Annotation - An annotation that has one method, is called
single-value annotation. For example:
@interface MyAnnotation
{
int value();
}
Multi-Method Annotation -An annotation that has more than one method, is
called Multi-Value annotation. For example:
@interface MyAnnotation
{
int value1();
String value2();
String value3();
}
Example Program
import [Link].*;
import [Link].*;
@Retention([Link])
@Target([Link])
@interface MyAnnotation //definition of annotation
{
int value();
}
//Applying annotation
class Hello
{
@MyAnnotation(value=10)
public void sayHello()
{
[Link]("hello annotation");
}
}
//Accessing annotation
class TestCustomAnnotation1
{
public static void main(String args[])throws Exception
{
Hello h=new Hello();
Method m=[Link]().getMethod("sayHello");
[Link]("Method name is:"+[Link]());
MyAnnotation manno=[Link]([Link]);
[Link]("value is: "+[Link]());
}
}
. 56 | P a g e
ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
FAQs
Subject : JAVA PROGRAMMING Year/Sem: II [Link] – II Sem
Academic Year: 2022-23 Regulation: R20
UNIT-3
1. a) Discuss briefly about declaration of arrays, initialization of arrays and accessing elements
of array with examples.
b) Write a JAVA program to sort a given list of elements using insertion sort. Explain with
examples.
2. a) Explain about class Array and its methods. How can we implement dynamic array with
Vector?
b) Write a java program to illustrate various Vector operations.
3. a) List the types of Inheritances in Java. Discuss briefly about Access Control in inheritance.
b) What is method overriding? Illustrate the concept of method overriding with an
example.
c ) What do understand by the super keyword? Write the use of super keyword.
4. a) Define Static and Dynamic binding. Write a java program to illustrate dynamic method
dispatch.
b) Write briefly about abstract class. Give an example illustrating use of abstract class
5. a) What is interface? Write briefly about types of interfaces. How does it supports multiple
inheritance in java?
b) Write two Java Programs to illustrate the use of default methods and static methods in
interfaces.
c) Write a java program to create anonymous objects using the Interface.
6. a)Explain briefly about Functional Interface. Write a java program applying Functional
Interfaces Consumer<T> and Supplier<T>.
b) Write short notes on Java Annotations.
7. a) Is it possible to implement multiple inheritances in Java? Justify your answer.
b) Develop a Java program to perform Binary search.
8. a) Demonstrate the Nested Interfaces using an example program.
b) Develop a program to perform matrices multiplication.
9. a)Discuss the advantage of the Method overriding.
b) Develop a program to apply merge sort on array elements.
10.a) Compare the features of Array with Vector.
b) Demonstrate dynamic method dispatch with an example program.
11.a) Discuss the advantage of the Super keyword with a Java program.
b) Develop a Java program to read students’ six subject marks and computes the
aggregate (%).
12.a) Demonstrate multi-level inheritance with an example program.
b) Develop a program to declare and access the three-dimensional arrays.
13.a) Illustrate types of Inheritance with a suitable diagram.
b) Discuss the advantages of the Interface.
14.a) Develop a program to compute the inverse of a given matrix.
b) Demonstrate multiple Inheritance with an example Java program.
15. a) What is an interface? What are the similarities between interfaces and classes?
b) Explain the member access mechanism in the inheritance with an example.
16. a) Explain the procedure to call super class members with an example.
b) How can you extend one interface by the other interface? Discuss
17.a) Explain the concept of Inhibiting Inheritance of Class using final with a suitable example.
b) Write a program to demonstrate the use of arrays as vectors.
c) Explain the concept of method overloading with an example.
. 57 | P a g e