0% found this document useful (0 votes)
31 views60 pages

Apznzabrhwleihg81eirvirzpf-5y7m5ynf73ynoqedmsjf4 Nfvlifwhcoccdwddxqyigmuqotvl8mysxuzqzsfogijh2l Bx 3rssopzd5in4yxdtb0gbvbrxuuypbyz5lw36d Fp3bqti7zm5nhwmwqi4iffc5cg6iaz1yh7p07sxbnzmxvh2taiznvpkifnw60ib856awstbjbwh6y

The document provides an overview of arrays in Java, including their definition, advantages, disadvantages, and types (single-dimensional and multi-dimensional). It discusses dynamic arrays and their features, such as resizing and memory management, along with examples of array initialization, element addition, deletion, and sorting methods. Additionally, it explains the use of the Arrays class for sorting arrays in ascending order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views60 pages

Apznzabrhwleihg81eirvirzpf-5y7m5ynf73ynoqedmsjf4 Nfvlifwhcoccdwddxqyigmuqotvl8mysxuzqzsfogijh2l Bx 3rssopzd5in4yxdtb0gbvbrxuuypbyz5lw36d Fp3bqti7zm5nhwmwqi4iffc5cg6iaz1yh7p07sxbnzmxvh2taiznvpkifnw60ib856awstbjbwh6y

The document provides an overview of arrays in Java, including their definition, advantages, disadvantages, and types (single-dimensional and multi-dimensional). It discusses dynamic arrays and their features, such as resizing and memory management, along with examples of array initialization, element addition, deletion, and sorting methods. Additionally, it explains the use of the Arrays class for sorting arrays in ascending order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

JAVA PROGRAMMING-R20

Unit-3
Introduction to Arrays
o An Array is a collection of elements that share the same type and name.
o The elements from the array can be accessed by the index.
o All array indices start at zero.
o You can access a specific element in the array by specifying its index within
square brackets.

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.

Disadvantages
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.

Types of Array
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array
To create an array, we must first create the array variable of the desired type. The general form
of the One Dimensional array is as follows:

type array-var[] = new type[size];

o Here type declares the base type of the array. This base type determine what type
of elements that the array will hold.
o array-var is the array variable that is linked to the array.
o size specifies the number of elements stored in the array
o new to allocate memory for an array. The elements in the array allocated by new
will automatically be initialized to zero.

Example: String months[] = new int[12];


Here

 type is String, the variable name is months. All the elements in the months are Strings.
Since, the base type is String.

 This example allocates 12-element array of Strings and links them to months. The
elements in the array allocated by new will automatically be initialized to null.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 1


JAVA PROGRAMMING-R20

months

Index 0 1 2 3 4 5 6 7 8 9 10 11

Element null null null null null null null null null null null null

For example, this statement assigns the value “February” to the second element of
months. months[1] = “February”;

Index 0 1 2 3 4 5 6 7 8 9 10 11

Element null February null null null null null null null null null null

Example Program: Write a Java Program to read elements into array and display them?
ArrayTest.java
import java.io.*;
import java.util.*;

class ArrayTest

{
public static void main(String args[])

{
Scanner s=new Scanner(System.in);

//declaring and allocating memory to array and all the elements are set
zero int a[] = new int[5];
//read the elements into array

System.out.println("Enter the elements into Array:");


for(int i=0;i<5;i++)

{
a[i]=s.nextInt();

//displaying the elements


System.out.println("The elements of Array:");
for(int i=0;i<n;i++)
{
Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 2
JAVA PROGRAMMING-R20

System.out.print(a[i]+",");
}
}
}
Output
Enter the elements into Array :12 45 56 78 30

The elements of Array: 12,45,56,78,30

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For example,
the following declares a two dimensional array variable called twoD

int twoD[][] = new int[4][4];

This allocates a 4 by 4 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.

Right Index Determines the Columns

[0,0] [0,1] [0,2] [0,3]


[3 ,0 ] [3 ,1 ] [3 ,2 ] [3 ,3 ]

[1,0] [1,1] [1,2] [1,3]

[2,0] [2,1] [2,2] [2,3]

Example Program for Matrix Addition


import java.io.*;

import java.util.Scanner;

class Testarray2
{

public static void main(String args[])


{

int m, n, i, j;
Scanner s=new Scanner(System.in);

System.out.println("Enter the no. of rows and columns of matrix");


m = s.nextInt());
n = s.nextInt());
Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 3
JAVA PROGRAMMING-R20

int m1[][] = new int[m][n];


int m2[][] = new int[m][n];

int result[][] = new int[m][n];


System.out.println("Enter the elements of first
matrix:"); for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
m1[i][j] = s.nextInt();
System.out.println("Enter the elements of second matrix:");
for ( i = 0 ; i < m ; i++ )

for ( j = 0 ; j < n ; j++ )


m2[i][j] = s.nextInt();

System.out.println("Sum of entered matrices:");


for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
result[i][j] = m1[i][j] + m2[i][j];
System.out.print( result[i][j]+"\t");
}

System.out.println();
}
}
}
Output
Enter the elements of first matrix: 1 2 3 4
Enter the elements of second matrix: 1 2 3 4
Sum of entered matrices: 2 4
6 8

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:

type[ ] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable. This
alternative declaration form offers convenience when declaring several arrays at the same time.
For example,

int[] nums, nums2, nums3; // create three arrays


creates three array variables of type int. It is the same as writing int nums[], nums2[], nums3[]; //
create three arrays.

Dynamic Array in Java


Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 4
JAVA PROGRAMMING-R20

An array is a fixed size, homogeneous data structure. The limitation of arrays is that they're fixed
in size. It means that we must specify the number of elements while declaring the array. Here a
question arises that what if we want to insert an element and there is no more space is left for the
new element? Here, the concept of dynamic array comes into existence. It expends the size of the
array dynamically.
In this section, we will understand what is a dynamic array, features of the dynamic array, how to
resize a dynamic array, and how to implement dynamic array in Java.

What is a dynamic array?


The dynamic array is a variable size list data structure. It grows automatically when we try to
insert an element if there is no more space left for the new element. It allows us to add and
remove elements. It allocates memory at run time using the heap. It can change its size during
run time.

In Java, Array List is a resizable implementation. It implements the List interface and provides
all methods related to the list operations. The strength of the dynamic array is:

o Quick lookup
o Variable size
o Cache-friendly

Working of Dynamic Array


In the dynamic array, the elements are stored contiguously from the starting of the array and the
remaining space remains unused. We can add the elements until the reserved spaced is
completely consumed. When the reserved space is consumed and required to add some elements.
In such a case, the fixed-sized array needs to be increased in size. Note that before appending the
element, we allocate a bigger array, copy the elements from the array, and return the newly
created array.

Another way to add an element is that first, create a function that creates a new array of double
size, copies all the elements from the old array, and returns the new array. Similarly, we can also
shrink the size of the dynamic array.

Size vs. Capacity


The initialization of a dynamic array creates a fixed-size array. In the following figure, the array
implementation has 10 indices. We have added five elements to the array. Now, the underlying
array has a length of five. Therefore, the length of the dynamic array size is 5 and its capacity is
10. The dynamic array keeps track of the endpoint.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 5


JAVA PROGRAMMING-R20

Features of Dynamic Array


In Java, the dynamic array has three key features: Add element, delete an element, and resize an
array.

Add Element in a Dynamic Array


In the dynamic array, we can create a fixed-size array if we required to add some more elements
in the array. Usually, it creates a new array of double size. After that, it copies all the elements to
the newly created array. We use the following approach:

Delete an Element from a Dynamic Array


If we want to remove an element from the array at the specified index, we use
the removeAt(i) method. The method parses the index number of that element which we want to
delete. After deleting the element, it shifts the remaining elements (elements that are right to the
deleted element) to the left from the specified index number. We also use the remove() method
that deletes an element from the end of the array. After shifting the elements, it stores 0 at the
palace of the last element. Let's understand it through an example, as we have shown in the
following figure.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 6


JAVA PROGRAMMING-R20

Resizing a Dynamic Array in Java


We need to resize an array in two scenarios if:
o The array uses extra memory than required.
o The array occupies all the memory and we need to add elements.

In the first case, we use the srinkSize() method to resize the array. It reduces the size of the array.
It free up the extra or unused memory. In the second case, we use the growSize() method to
resize the array. It increases the size of the array.

It is an expensive operation because it requires a bigger array and copies all the elements from
the previous array after that return the new array.

uppose in the above array, it is required to add six more elements and, in the array, no more
memory is left to store elements. In such cases, we grow the array using the growSize() method.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 7


JAVA PROGRAMMING-R20

Initialize a Dynamic Array


The initialization of the dynamic array is the same as the static array. Consider the following
Java program that initializes a dynamic array.

InitializeDynamicArray.java

1. public class InitializeDynamicArray


2. {
3. public static void main(String[] args)
4. {
5. //declaring array
6. int array[];
7. //initialize an array
8. array= new int[6];
9. //adding elements to the array
10. array[0] = 34;
11. array[1] = 90;
12. array[2] = 12;
13. array[3] = 22;
14. array[4] = 9;
15. array[5] = 27;
16. System.out.print("Elements of Array are: ");
17. //iteraton over the array
18. for(int i=0; i< array.length ; i++)
19. {
20. System.out.print(array[i] +" ");

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 8


JAVA PROGRAMMING-R20

21. }
22. }
23. } Output:
Elements of Array are: 34 90 12 22 9 27

How to Sort an Array in Java


The sorting is a way to arrange elements of a list or array in a certain order. The order may be in
ascending or descending order. The numerical and lexicographical (alphabetical) order is a
widely used order.

In this section, we will learn how to sort array in Java in ascending and descending order
using the sort() method and without using the sort() method. Along with this, we will also
learn how to sort subarray in Java.

Sort Array in Ascending Order


The ascending order arranges the elements in the lowest to highest order. It is also known
as natural order or numerical order. We can perform sorting in the following ways:
o Using the sort() Method
o Without using the method

o Using the for Loop


o Using the User Defined Method

Using the sort() Method


In Java, Arrays is the class defined in the java.util package that provides sort() method to sort an
array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity
is O(n log(n)). It is a static method that parses an array as a parameter and does not return
anything. We can invoke it directly using the class name. It accepts an array of type int, float,
double, long, char, byte.

Syntax:

1. public static void sort(int[] a)

Where a is an array to be short.

Note: Like the Arrays class, the Collections class also provides the sort() method to sort the array.
But there is a difference between them. The sort() method of the Arrays class works for primitive type
while the sort() method of the Collections class works for objects Collections, such as LinkedList,
ArrayList, etc.

Let's sort an array using the sort() method of the Arrays class.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 9


JAVA PROGRAMMING-R20

In the following program, we have defined an array of type integer. After that, we have invoked
the sort() method of the Arrays class and parses the array to be sort. For printing the sorted array,
we have used for loop.

SortArrayExample1.java

1. import java.util.Arrays;
2. public class SortArrayExample1
3. {
4. public static void main(String[] args)
5. {
6. //defining an array of integer type
7. int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
8. //invoking sort() method of the Arrays class
9. Arrays.sort(array);
10. System.out.println("Elements of array sorted in ascending order: ");
11. //prints array using the for loop
12. for (int i = 0; i < array.length; i++)
13. {
14. System.out.println(array[i]);
15. }
16. }
17. }

Output:

Array elements in ascending order:


5
12
22
23
34
67
90
109

In the above program, we can also use the toSting() method of the Arrays class to print the array,
as shown in the following statement. It returns a string representation of the specified array.

1. System.out.printf(Arrays.toString(array));

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 10


JAVA PROGRAMMING-R20

Without Using the Method


Using the for Loop

In the following example, we have initialized an array of integer type and sort the array in
ascending order.

SortArrayExample2.java

1. public class SortArrayExample2


2. {
3. public static void main(String[] args)
4. {
5. //creating an instance of an array
6. int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};
7. System.out.println("Array elements after sorting:");
8. //sorting logic
9. for (int i = 0; i < arr.length; i++)
10. {
11. for (int j = i + 1; j < arr.length; j++)
12. {
13. int tmp = 0;
14. if (arr[i] > arr[j])
15. {
16. tmp = arr[i];
17. arr[i] = arr[j];
18. arr[j] = tmp;
19. }
20. }
21. //prints the sorted element of the array
22. System.out.println(arr[i]);
23. }
24. }
25. }
26. Output:
27. Array elements after sorting:
28. -65
29. -4
30. -1
31. 1

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 11


JAVA PROGRAMMING-R20

32. 3
33. 6
34. 20
35. 34
36. 34
37. 55
38. 78
39. 90

Sort Array in Descending Order


The descending order arranges the elements in the highest to lowest order. We can perform
sorting in the following ways:

o Using the reverseOrder() Method


o Without using the method
o Using the for Loop
o Using the User Defined Method

Using the reverseOrder() Method


Java Collections class provides the reverseOrder() method to sort the array in reverse-
lexicographic order. It is a static method, so we can invoke it directly by using the class name. It
does not parse any parameter. It returns a comparator that imposes the reverse of the natural
ordering (ascending order).

It means that the array sorts elements in the ascending order by using the sort() method, after that
the reverseOrder() method reverses the natural ordering, and we get the sorted array in
descending order.

Syntax:

1. public static <T> Comparator<T> reverseOrder()

Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder()
method in the following way:

1. Arrays.sort(a, Collections.reverseOrder());

Let's sorts an array in the descending order.

In the following program, a point to be noticed that we have defined an array as Integer.
Because the reverseOrder() method does not work for the primitive data type.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 12


JAVA PROGRAMMING-R20

SortArrayExample4.java

1. import java.util.Arrays;
2. import java.util.Collections;
3. public class SortArrayExample4
4. {
5. public static void main(String[] args)
6. {
7. Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};
8. // sorts array[] in descending order
9. Arrays.sort(array, Collections.reverseOrder());
10. System.out.println("Array elements in descending order: " +Arrays.toString(array));
11. }
12. }

Output:

Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9]

Let's see another program that sorts array elements in alphabetical order.

SortArrayExample5.java

1. import java.util.Arrays;
2. import java.util.Collections;
3. public class SortArrayExample5
4. {
5. public static void main(String[] args)
6. {
7. String [] strarray = {"Mango", "Apple", "Grapes", "Papaya", "Pineapple", "Banana", "Orange"};
8. // sorts array[] in descending order
9. Arrays.sort(strarray, Collections.reverseOrder());
10. System.out.println("Array elements in descending order: " +Arrays.toString(strarray));
11. }
12. }

Output:

Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple]

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 13


JAVA PROGRAMMING-R20

Without Using the Method


Using the for Loop

In the following example, we have initialized an integer array and perform sorting in descending
order.

SortArrayExample6.java

1. public class SortArrayExample6


2. {
3. public static void main(String[] args)
4. {
5. int temp;
6. //initializing an array
7. int a[]={12,5,56,-2,32,2,-26,9,43,94,-78};
8. for (int i = 0; i < a.length; i++)
9. {
10. for (int j = i + 1; j < a.length; j++)
11. {
12. if (a[i] < a[j])
13. {
14. temp = a[i];
15. a[i] = a[j];
16. a[j] = temp;
17. }
18. }
19. }
20. System.out.println("Array elements in descending order:");
21. //accessing element of the array
22. for (int i = 0; i <=a.length - 1; i++)
23. {
24. System.out.println(a[i]);
25. }
26. }
27. }

Output:

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 14


JAVA PROGRAMMING-R20

Array elements in descending order:


94
56
43
32
12
9
5
2
-2
-26
-78

Using the User Defined Method

SortArrayExample7.java

1. import java.util.Scanner;
2. public class SortArrayExample7
3. {
4. public static void main(String[] args)
5. {
6. int n, temp;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number of elements: ");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter the elements of the array: ");
12. for (int i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. for (int i = 0; i < n; i++)
17. {
18. for (int j = i + 1; j < n; j++)
19. {
20. if (a[i] < a[j])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 15


JAVA PROGRAMMING-R20

26. }
27. }
28. System.out.println("Array elements in descending order:");
29. for (int i = 0; i < n - 1; i++)
30. {
31. System.out.println(a[i]);
32. }
33. System.out.print(a[n - 1]);
34. }
35. }

Output:

Enter the number of elements: 7


Enter the elements of the array:
12
5
56
-2
32
2
-26
Array elements in descending order:
56
32
12
5
2
-2
-26

Arrays class in Java


The Arrays class in java.util package is a part of the Java Collection Framework. This class
provides static methods to dynamically create and access Java arrays. It consists of only static
methods and the methods of Object class. The methods of this class can be used by the class
name itself.
Class Hierarchy:
java.lang.Object
↳ java.util.Arrays
Class Declaration:
public class Arrays
extends Object
Syntax to use Array:
Arrays.<function name>;

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 16


JAVA PROGRAMMING-R20

Need for the Java-Arrays Class:


There are often times when loops are used to do some tasks on an array like:

 Fill an array with a particular value.


 Sort an Arrays.
 Search in an Arrays.
 And many more.
Arrays class provides several static methods that can be used to perform these tasks
directly without the use of loops.
Methods in Java Array:
The Arrays class of the java.util package contains several static methods that can be
used to fill, sort, search, etc in arrays. These are:
1. static <T> List<T> asList(T… a): This method returns a fixed-size list backed by
the specified Arrays.
// Java program to demonstrate
// Arrays.asList() method
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
// To convert the elements as List
System.out.println("Integer Array as List: "
+ Arrays.asList(intArr));
}
}

Output:
2. Integer Array as List: [[I@232204a1]
Arrays Of Arrays with Varying Length in Java
when we created arrays of arrays (i.e. two-dimensional array), the arrays in the array were
of same length i.e. each row had the same number of elements. As each array in a
multidimensional array is a separate array so it can have different number of elements.
Such arrays are known as non-rectangular arrays or ragged arrays.

In order to create a two-dimensional ragged array, you have to first declare and instantiate
the array by specifying only the number of elements in the first dimension and leaving the
second dimension empty. For example: Consider the statement,

int [] [] table = new int [3] [];


This statement declares an array object table of type int [] [] which references an array of 3
elements, each of which holds a reference to a one-dimensional array. With this statement,

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 17


JAVA PROGRAMMING-R20

although three one-dimensional arrays have been declared but the number of elements in
each one dimensional array is still undefined. So you can define these arrays individually
as follows,
tab1e[0] = new int[l];
table [1] = new int[2];
table [2] = new int[3];
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.
Non-Rectangular array table
Like you can initialize arrays of arrays, similarly, the ragged arrays can also be initialized.
For example : The statement,
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.

You can access the elements of the ragged array just as before with the index pair but now
the range of the index for each subarray is different.

Now let us consider a program to find the minimum and maximum in a ragged array
//program that find maximum and minimum in ragged array
public class MaxMin
{
public static void main(String [] args)
{
int[] [] table= { {15,10} ,{5,12,34},{3,32,17,44}};
int i, j,max,min;
max = min = table [0] [0];
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];
}

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 18


JAVA PROGRAMMING-R20

}
System.out.println("Maximum Element is : "+max);
System.out.println("Minimum Element is : "+min);
}
}
Variable length (Dynamic) Arrays in Java

Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-
number of elements in it as there is no size limit. It is a part of Java Collection framework since
Java 1.2. It is found in the java.util package and implements the List interface, so we can use all
the methods of List interface here.It is recommended to use the Vector class in the thread-safe
implementation only. If you don't need to use the thread-safe implementation, you should use the
ArrayList, the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails
and throws the ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector class Declaration

SN Method Description

1) add() It is used to append the specified element in the given vector.

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.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 19


JAVA PROGRAMMING-R20

7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specified
collection.

9) copyInto() It is used to copy the components of the vector into the specified array.

10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.

13) equals() It is used to compare the specified object with the vector for equality.

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.

16) get() It is used to get an element at the specified position in the vector.

17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

19) insertElementAt() It is used to insert the specified object as a component in the given vector at the
specified index.

20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper sequence.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 20


JAVA PROGRAMMING-R20

22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.

25) remove() It is used to remove the specified element from the vector. If the vector does not
contain the element, it is unchanged.

26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.

27) removeAllElements() It is used to remove all elements from the vector and set the size of the vector to
zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.

29) removeElementAt() It is used to delete the component at the specified index.

30) removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.

31) removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.

33) retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.

34) set() It is used to replace the element at the specified position in the vector with the
specified element.

35) setElementAt() It is used to set the component at the specified index of the vector to the
specified object.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 21


JAVA PROGRAMMING-R20

36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the specified
Comparator.

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in
the list.

40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive,
and toIndex, exclusive.

41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.

42) toString() It is used to get a string representation of the vector.

43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.

1. public class Vector<E>


2. extends Object<E>
3. implements List<E>, Cloneable, Serializable

SN Constructor Description

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial


capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified initial
capacityIncrement) capacity and capacity increment.

4) Vector( Collection<? extends It constructs a vector that contains the elements of a

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 22


JAVA PROGRAMMING-R20

E> c) collection c.

Java Vector Constructors


Vector class supports four types of constructors. These are given below:

Java Vector Methods


The following are the list of Vector class methods:

Java Vector Example


1. import java.util.*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Adding elements using addElement() method of Vector
12. vec.addElement("Rat");
13. vec.addElement("Cat");
14. vec.addElement("Deer");
15.
16. System.out.println("Elements are: "+vec);
17. }
18. }

Output:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 23


JAVA PROGRAMMING-R20

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o 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.
o 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.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 24


JAVA PROGRAMMING-R20

Java Inheritance Example


ava Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
0Output
Programmer salary is:40000.0
Bonus of programmer is:10000

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 25


JAVA PROGRAMMING-R20

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 26


JAVA PROGRAMMING-R20

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 27


JAVA PROGRAMMING-R20

7. class BabyDog extends Dog{


8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 28


JAVA PROGRAMMING-R20

16. }}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error

Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 29


JAVA PROGRAMMING-R20

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 30


JAVA PROGRAMMING-R20

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 timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll()
method).

public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds and
nanos)throws InterruptedException nanoseconds, until another thread notifies (invokes notify() or
notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage
collected.

Using final keyword with inheritance in Java


Java | using final with inheritance: In this tutorial, we are going to learn how to use final keyword
with inheritance in java?
Submitted by Preeti Jain, on June 03, 2019

final keyword with inheritance in java


 The final keyword is final that is we cannot change.
 We can use final keywords for variables, methods, and class.
 If we use the final keyword for the inheritance that is if we declare any method with
the final keyword in the base class so the implementation of the final method will be the
same as in derived class.
 We can declare the final method in any subclass for which we want that if any other class
extends this subclass.

Case 1: Declare final variable with inheritance


// Declaring Parent class
class Parent {
/* Creation of final variable pa of string type i.e
Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 31
JAVA PROGRAMMING-R20

the value of this variable is fixed throughout all


the derived classes or not overidden*/
final String pa = "Hello , We are in parent class variable";
}
// Declaring Child class by extending Parent class
class Child extends Parent {
/* Creation of variable ch of string type i.e
the value of this variable is not fixed throughout all
the derived classes or overidden*/
String ch = "Hello , We are in child class variable";
}

class Test {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a variable pa by parent object
System.out.println(p.pa);
// Creation of Child class object
Child c = new Child();

// Calling a variable ch by Child object


System.out.println(c.ch);
// Calling a variable pa by Child object
System.out.println(c.pa);
}
}

Output

D:\Programs>javac Test.java
D:\Programs>java Test
Hello , We are in parent class variable
Hello , We are in child class variable
Hello , We are in parent class variable
Access Modifiers

Access modifiers are simply a keyword in Java that provides accessibility of a class and its member.
They set the access level to methods, variable, classes and constructors.

Types of access modifier


There are 4 types of access modifiers available in Java.

 public
 default

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 32


JAVA PROGRAMMING-R20

 protected
 private
public
The member with public modifiers can be accessed by any classes. The public methods, variables or
class have the widest scope.

Example: Sample program for public access modifier


public static void main(String args[])
{
// code
}
default
When we do not mention any access modifier, it is treated as default. It is accessible only within
same package.

Example: Sample program for default access modifier


int a = 25;
String str = "Java";
boolean m1()
{
return true;
}

protected
The protected modifier is used within same package. It lies between public and default access
modifier. It can be accessed outside the package but through inheritance only.
A class cannot be protected.
Example: Sample program for protected access modifier
class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 33


JAVA PROGRAMMING-R20

public void display()


{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}
}

Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking

private
The private methods, variables and constructor are not accessible to any other class. It is the most
restrictive access modifier. A class except a nested class cannot be private.
Example: Sample program for private access modifier

public class PrivateDemo


{
private int a = 101;
private String s = "TutorialRide";
public void show()
{
System.out.println("Private int a = "+a+"\nString s = "+s);
}
public static void main(String args[])
{
PrivateDemo pd = new PrivateDemo();
pd.show();
System.out.println(pd.a+" "+pd.s);

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 34


JAVA PROGRAMMING-R20

}
}

Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide

Table for Access Modifier

Access modifier In class In package Outside package by subclass Outside package

public Yes Yes Yes No

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance


variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 35


JAVA PROGRAMMING-R20

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Test it Now

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 36


JAVA PROGRAMMING-R20

9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it NowOutput:
eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now

Output:

animal is created

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 37


JAVA PROGRAMMING-R20

dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.

1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 38


JAVA PROGRAMMING-R20

20. e1.display();
21. }}
Test it Now

Output:

1 ankit 45000

Dynamic Method Dispatch or Runtime Polymorphism in Java


Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the type
of the object being referred to at the time the call occurs. Thus, this determination is made
at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when


different types of objects are referred to through a superclass reference variable, different
versions of the method are executed. Here is an example that illustrates dynamic method
dispatch:

class A

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 39


JAVA PROGRAMMING-R20

void m1()

System.out.println("Inside A's m1 method");

class B extends A

// overriding m1()

void m1()

System.out.println("Inside B's m1 method");

class C extends A

// overriding m1()

void m1()

System.out.println("Inside C's m1 method");

// Driver class

class Dispatch

public static void main(String args[])


Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 40
JAVA PROGRAMMING-R20

// object of type A

A a = new A();

a.m1();

// object of type B

A b = new B();

b.m1();

// object of type C

b = new C();

b.m1();

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 41


JAVA PROGRAMMING-R20

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

Features of Java - Javatpoint

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Example of abstract class

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 42


JAVA PROGRAMMING-R20

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now

running safely

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 43


JAVA PROGRAMMING-R20

o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now

running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 44


JAVA PROGRAMMING-R20

A factory method is a method that returns the instance of the class. We will learn about the factory
method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
15. s.draw();
16. }
17. }
Test it Now

drawing circle

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 45


JAVA PROGRAMMING-R20

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Difference between JDK, JRE, and JVM

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Java 8 Interface Improvement


Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 46


JAVA PROGRAMMING-R20

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 47


JAVA PROGRAMMING-R20

9. obj.print();
10. }
11. }
Test it Now

Output:

Hello

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java programmer.

o Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
o Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface


1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }

Syntax of nested interface which is declared within the class


1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }

Example of nested interface which is declared within the interface


In this example, we are going to learn how to declare the nested interface and how we can access it.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 48


JAVA PROGRAMMING-R20

1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7. class TestNestedInterface1 implements Showable.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. Showable.Message message=new TestNestedInterface1();//upcasting here
12. message.msg();
13. }
14. }
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface Showable because it c
accessed directly. It is just like almirah inside the room, we cannot access the almirah directly because we must enter the ro
In collection frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. acc
Map.Entry.

a new concept of default method implementation in interfaces. This capability is added for
backward compatibility so that old interfaces can be used to leverage the lambda expression
capability of Java 8.
For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus,
adding such method will simply break the collection framework implementations. Java 8
introduces default method so that List/Collection interface can have a default implementation of
forEach method, and the class implementing these interfaces need not implement the same.

Syntax
public interface vehicle {

default void print() {


System.out.println("I am a vehicle!");
}
}

Multiple Defaults
With default functions in interfaces, there is a possibility that a class is implementing two
interfaces with same default methods. The following code explains how this ambiguity can be
resolved.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 49


JAVA PROGRAMMING-R20

public interface vehicle {

default void print() {


System.out.println("I am a vehicle!");
}
}

public interface fourWheeler {

default void print() {


System.out.println("I am a four wheeler!");
}
}
First solution is to create an own method that overrides the default implementation.
public class car implements vehicle, fourWheeler {

public void print() {


System.out.println("I am a four wheeler car vehicle!");
}
}
Second solution is to call the default method of the specified interface using super.
public class car implements vehicle, fourWheeler {

public void print() {


vehicle.super.print();
}
}

Static Default Methods


An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {

default void print() {


System.out.println("I am a vehicle!");
}

static void blowHorn() {


System.out.println("Blowing horn!!!");
}
}

Default Method Example


Create the following Java program using any editor of your choice in, say, C:\> JAVA.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 50


JAVA PROGRAMMING-R20

Java8Tester.java
public class Java8Tester {

public static void main(String args[]) {


Vehicle vehicle = new Car();
vehicle.print();
}
}

interface Vehicle {

default void print() {


System.out.println("I am a vehicle!");
}

static void blowHorn() {


System.out.println("Blowing horn!!!");
}
}

interface FourWheeler {

default void print() {


System.out.println("I am a four wheeler!");
}
}

class Car implements Vehicle, FourWheeler {

public void print() {


Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}

Verify the Result


Compile the class using javac compiler as follows -
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows -
C:\JAVA>java Java8Tester
It should produce the following output -
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!
Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 51
JAVA PROGRAMMING-R20

Java Functional Interfaces


An Interface that contains exactly one abstract method is known as functional interface. It can
have any number of default, static methods but can contain only one abstract method. It can also
declare methods of object class.

Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is
a new feature in Java, which helps to achieve functional programming approach.

Example 1
1. @FunctionalInterface
2. interface sayable{
3. void say(String msg);
4. }
5. public class FunctionalInterfaceExample implements sayable{
6. public void say(String msg){
7. System.out.println(msg);
8. }
9. public static void main(String[] args) {
10. FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
11. fie.say("Hello there");
12. }
13. }

Output:

Hello there

Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods
or fields to indicate some additional information which can be used by java compiler and JVM.

Annotations in Java are used to provide additional information, so it is an alternative option for
XML and Java marker interfaces.

First, we will learn some built-in annotations then we will move on creating and using custom
annotations.

Built-In Java Annotations

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 52


JAVA PROGRAMMING-R20

There are several built-in annotations in Java. Some annotations are applied to Java code and
some to other annotations.

Built-In Java Annotations used in Java code

o @Override
o @SuppressWarnings
o @Deprecated

Built-In Java Annotations used in other annotations

o @Target
o @Retention
o @Inherited
o @Documented

Understanding Built-In Annotations


Let's understand the built-in annotations first.

@Override
@Override annotation assures that the subclass method is overriding the parent class method. If
it is not so, compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){System.out.println("eating foods");}//should be eatSomething
8. }
9.
10. class TestAnnotation1{
Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 53
JAVA PROGRAMMING-R20

11. public static void main(String args[]){


12. Animal a=new Dog();
13. a.eatSomething();
14. }}
Test it Now
Output:Comple Time Erro
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
1. import java.util.*;
2. class TestAnnotation2{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5. ArrayList list=new ArrayList();
6. list.add("sonoo");
7. list.add("vimal");
8. list.add("ratan");
9.
10. for(Object obj:list)
11. System.out.println(obj);
12.
13. }}
Test it Now
Now no warning at compile time.

If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at


compile time because we are using non-generic collection.

@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.
1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 54


JAVA PROGRAMMING-R20

7.
8. class TestAnnotation3{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}
Test it Now

At Compile Time:

Note: Test.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

At Runtime:

hello n

Java Custom Annotations


Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:

1. @interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature

There are few points that should be remembered by the programmer.

1. Method should not have any throws clauses


2. Method should return one of the following: primitive data types, String, Class, enum or
array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 55


JAVA PROGRAMMING-R20

Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation

1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:

1. @interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:

1. @interface MyAnnotation{
2. int value();
3. }

We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value() default 0;
3. }

How to apply Single-Value Annotation

Let's see the code to apply the single value annotation.

1. @MyAnnotation(value=10)

The value can be anything.

3) Multi-Value Annotation

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 56


JAVA PROGRAMMING-R20

An annotation that has more than one method, is called Multi-Value annotation. For example:

1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }

We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }

How to apply Multi-Value Annotation

Let's see the code to apply the multi-value annotation.

1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations used in custom annotations in java


o @Target
o @Retention
o @Inherited
o @Documented

@Target
@Target tag is used to specify at which type, the annotation is used.

The java.lang.annotation.ElementType enum declares many constants to specify the type of


element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 57


JAVA PROGRAMMING-R20

Element Types Where the annotation can be applied

TYPE class, interface or enumeration

FIELD fields

METHOD methods

CONSTRUCTOR constructors

LOCAL_VARIABLE local variables

ANNOTATION_TYPE annotation type

PARAMETER parameter

Example to specify annoation for a class

1. @Target(ElementType.TYPE)
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

Example to specify annotation for a class, methods or fields

1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

@Retention
@Retention annotation is used to specify to what level annotation will be available.

RetentionPolicy Availability

RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will not be
available in the compiled class.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 58


JAVA PROGRAMMING-R20

RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM . It is
included in the class file.

RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .

Example to specify the RetentionPolicy

1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }

Example of custom annotation: creating, applying and accessing


annotation
Let's see the simple example of creating, applying and accessing annotation.

File: Test.java

1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11. //Applying annotation
12. class Hello{
13. @MyAnnotation(value=10)
14. public void sayHello(){System.out.println("hello annotation");}
15. }
16.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 59


JAVA PROGRAMMING-R20

17. //Accessing annotation


18. class TestCustomAnnotation1{
19. public static void main(String args[])throws Exception{
20.
21. Hello h=new Hello();
22. Method m=h.getClass().getMethod("sayHello");
23.
24. MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
25. System.out.println("value is: "+manno.value());
26. }}
Test it Now
Output:value is: 10

How built-in annotaions are used in real scenario?

In real scenario, java programmer only need to apply annotation. He/She doesn't need to create
and access annotation. Creating and Accessing annotation is performed by the implementation
provider. On behalf of the annotation, java compiler or JVM performs some additional
operations.

@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.

1. @Inherited
2. @interface ForEveryone { }//Now it will be available to subclass also
3.
4. @interface ForEveryone { }
5. class Superclass{}
6.
7. class Subclass extends Superclass{}

@Documented
The @Documented Marks the annotation for inclusion in the documentation.

Mr Gandi Netaji Asst. Prof in Dept. of IT VIEW 60

You might also like