0% found this document useful (0 votes)
9 views39 pages

Java Arrays: Declaration, Access, and Operations

This document provides comprehensive notes on Java, focusing on arrays and inheritance. It covers topics such as array declaration, initialization, memory storage, accessing elements, and various operations on arrays. Additionally, it discusses inheritance concepts, including types of relationships, method overriding, and the use of abstract classes and interfaces.

Uploaded by

supriyan2508
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)
9 views39 pages

Java Arrays: Declaration, Access, and Operations

This document provides comprehensive notes on Java, focusing on arrays and inheritance. It covers topics such as array declaration, initialization, memory storage, accessing elements, and various operations on arrays. Additionally, it discusses inheritance concepts, including types of relationships, method overriding, and the use of abstract classes and interfaces.

Uploaded by

supriyan2508
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

Java Notes

Your Name
Department of Computer Science
October 21, 2025

Contents

1 Introduction to Arrays in JAVA 4


1.1 Declaration of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Initialization of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Declaration and Initialization in One Step . . . . . . . . . . . . . 4
1.2.2 Declaration Followed by Initialization . . . . . . . . . . . . . . . . 4

2 Storage of Array in Computer Memory 5


2.1 Memory Layout of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Contiguous Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Indexing and Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 Accessing Elements of Arrays in Java 6


3.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 Determination of Array Size . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.4 Iterating through array elements using for-each loop . . . . . . . . . . . . 7

4 Operations on Array Elements 8


4.1 Insertion of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2 Deletion of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.3 Merging of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5 Assigning one Array to another Array 10


5.1 Scenario-1: Using variable assignment . . . . . . . . . . . . . . . . . . . . 10
5.2 To prevent side effects (Better ways to copy the array): . . . . . . . . . . 10
5.3 Create a new array and copy each element by iterating. . . . . . . . . . 10
5.4 Using Clone() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6 Dynamic change of array size in Java 12

7 Sorting of Arrays 13
7.1 Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.2 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.3 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1
Your Name / Class Java Notes

8 Search for Values in Arrays 14


8.1 Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.2 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

9 Array Class 15
9.1 Methods in java Array class . . . . . . . . . . . . . . . . . . . . . . . . . 15

10 2D Arrays in Java 15
10.1 Declaring and Initialsing a 2D Array . . . . . . . . . . . . . . . . . . . . 16
10.2 Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.3 Iterating through a 2D Array . . . . . . . . . . . . . . . . . . . . . . . . 16

11 Arrays of Varying Length 16

12 Three Dimensional Arrays 17

13 Arrays as Vectors 18
13.1 convert an array to a vector . . . . . . . . . . . . . . . . . . . . . . . . . 18

14 Introduction to Inheritance 20
14.1 Benefits of using inheritance in Java . . . . . . . . . . . . . . . . . . . . . 20
14.2 Key Terminologies Used in Java Inheritance . . . . . . . . . . . . . . . . 20

15 Process of Inheritance 21
15.1 Types of Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
15.1.1 Is-A Relationship in Java . . . . . . . . . . . . . . . . . . . . . . . 21
15.1.2 Has-A-Relation in Java . . . . . . . . . . . . . . . . . . . . . . . . 21
15.2 Has-A-Relation in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
15.2.1 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.2.2 Aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
15.3 How to Decide which Type of Relation We Need . . . . . . . . . . . . . . 22

16 Super 22
16.1 Code to demonstrate the order of constructor calls with a parameterized
constructor in the sub class. . . . . . . . . . . . . . . . . . . . . . . . . . 23
16.2 Code to demonstrate the use of Super method when both super class and
sub class has parameterized constructors. . . . . . . . . . . . . . . . . . . 24
16.3 Code for demonstrating order of constructor calls and the use of Super
method in Multi level inheritance. . . . . . . . . . . . . . . . . . . . . . . 25

17 Inhibiting Inheritance of Class Using Final 26


17.1 Inhibiting inheritance through final class . . . . . . . . . . . . . . . . . . 27
17.2 Prventing method overriding using final . . . . . . . . . . . . . . . . . . . 27

18 Access Control and Inheritance 27

19 Universal Super Class-Object Class 28

20 Constructor Method and Inheritance 28

Page 2
Your Name / Class Java Notes

21 Method overriding 28

22 Dynamic Method Dispatch 29

23 Abstract class 30

24 Interfaces 32
24.1 Multiple Interfaces in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 32
24.2 Nested Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
24.3 Inheritance of Interfaces in Java . . . . . . . . . . . . . . . . . . . . . . . 35
24.4 Default Methods in Interface . . . . . . . . . . . . . . . . . . . . . . . . . 36
24.5 Static Methods in Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . 37
24.6 Difference between method overloading and overriding . . . . . . . . . . . 38
24.7 Difference between class and interface . . . . . . . . . . . . . . . . . . . . 38
24.8 Difference between Abstract class and interface . . . . . . . . . . . . . . 38

Page 3
Your Name / Class Java Notes

1 Introduction to Arrays in JAVA


• A **Java array** is an object which contains elements of a similar data type.

• The elements of an array are stored in a **contiguous memory location**.

• It is a data structure where we store similar elements (a fixed set of elements).

• Array in Java is **index-based**, the first element is at index-0, the second at


index-1, and so on.

1.1 Declaration of Arrays


To declare an array in Java, you specify the type of the elements it will hold, followed by
square brackets [].

Examples:

Listing 1: Array Declarations


// D e c l a r i n g an a r r a y o f i n t e g e r s
i n t [ ] numbers ;
// D e c l a r i n g an a r r a y o f s t r i n g s
S t r i n g [ ] names ;
// D e c l a r i n g an a r r a y o f d o u b l e s
do ub le [ ] p r i c e s ;

1.2 Initialization of Arrays


Initialization involves creating the actual array and optionally assigning values to it.

1.2.1 Declaration and Initialization in One Step


You can declare and initialize an array in a single statement using curly braces {} to
specify the initial values:
1 // Array of integers with initial values
2 int [] numbers = {1 , 2 , 3 , 4 , 5};
3 // Array of strings with initial values
4 String [] names = { " Bobby " , " Charan " , " Alekhya " };
5 // Array of doubles with initial values
6 double [] prices = {40.5 , 27.75 , 30.0};
Listing 2: Declaration and Initialization

1.2.2 Declaration Followed by Initialization


You can declare an array first and then initialize it separately using the new keyword and
specifying the size of the array.

Page 4
Your Name / Class Java Notes

1 // Declaration
2 int [] numbers ;
3

4 // Initialization with size


5 numbers = new int [5]; // Creates an array with 5 elements , all
initialized to 0
6

7 // You can also initialize elements individually


8 numbers [0] = 1;
9 numbers [1] = 2;
10 numbers [2] = 3;
11 numbers [3] = 4;
12 numbers [4] = 5;
Listing 3: Declaration and Separate Initialization

2 Storage of Array in Computer Memory


2.1 Memory Layout of Arrays
In Java, arrays are objects. When an array is created, memory is allocated for an **array
object** which holds the **reference** to the actual array data.

• **Reference:** The reference variable of the array holds the address of the array
object in memory.
• **Array Object:** Contains metadata (like length) and the actual array data.
• **Array Data:** The data elements are held in **contiguous memory locations**.
For instance, an int[] stores each integer in 4 bytes consecutively.
• Since arrays are reference types (created using new), they are stored in the **heap
area**.

Example

1 int [] numbers = new int [5];


2 // ’ numbers ’ holds the reference to the array object \\( in the
Stack area , pointing to the Heap area ) .

2.2 Contiguous Memory Allocation


When an array is created, the Java runtime allocates a contiguous block of memory for
the array elements.

2.3 Indexing and Access


Arrays in Java use **zero-based indexing**. The memory addresses of array elements
can be computed efficiently based on the base address and element size.

Page 5
Your Name / Class Java Notes

Figure 1: Array Memory Allocation

Formula:
The memory address of an element at index i can be calculated as:

Address of element i = Base address + (i × size of element)

For example, if the base address of the array is 0x1000 and each integer occupies 4
bytes, the address of the element at index 2 would be:

Address of element 2 = 0x1000 + (2 × 4) = 0x1008

3 Accessing Elements of Arrays in Java


An array element is accessed using the array name followed by the index enclosed in
square brackets.

3.1 Syntax

arrayRefVar [ i n d e x ] ;
The index is an integer literal or an expression that evaluates to an integer. The index
of the last element is always one less than the number of elements ([Link] - 1).

3.2 Example Program

Listing 4: Array Elements Access


import j a v a . u t i l . Scanner ; // program u s e s Scanner c l a s s

p u b l i c c l a s s ArrayElements {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
i n t [ ] numArray = new i n t [ 5 ] ;
int i ;

Page 6
Your Name / Class Java Notes

Scanner i n p u t = new Scanner ( System . i n ) ;


System . out . p r i n t ( ” Enter t h e 5 Array Elements : ” ) ;

f o r ( i = 0 ; i < 5 ; i ++) {
numArray [ i ] = i n p u t . n e x t I n t ( ) ; // Read number
}

f o r ( i = 0 ; i < numArray . l e n g t h ; i ++) {


System . out . p r i n t l n ( ” Array element [ ” + i + ” ] : ” + numArray [ i ] )
}
}
}

3.3 Determination of Array Size


To determine the size of a Java array, query its **length property**.
1 int [] exampleArray = {1 , 2 , 3 , 4 , 5};
2 int exampleArraySize = exampleArray . length ;
3 System . out . print ( " This Java array size is : " + exampleArraySize ) ;
4 // Output : This Java array size is : 5

Note: The array length in Java is a **property**, not a method.

3.4 Iterating through array elements using for-each loop


The for-each loop is a convenient way to iterate through elements of arrays.

Example 2: Sum of Array Elements

1 // Calculate the sum of all elements of an array


2 class Main {
3 public static void main ( String [] args ) {
4 // an array of numbers
5 int [] numbers = {3 , 4 , 5 , 5 , 0 , 12};
6 int sum = 0;
7

8 // iterating through each element of the array


9 for ( int number : numbers ) {
10 sum += number ;
11 }
12

13 System . out . println ( " Sum = " + sum ) ;


14 }
15 }
16 // Output : Sum = 29

Page 7
Your Name / Class Java Notes

4 Operations on Array Elements


In array, we can perform the various operation.

• Insertion in an Array

• Deletion in an Array

• Traversing of an Array

• Merging of an Array

4.1 Insertion of an Array


1 import java . util . Scanner ;
2 public class Main
3 {
4 public static void main ( String [] args )
5 {
6 int size , insert , poss ;
7 // creation of the array
8 int [] arr = new int [50];
9 // declare scanner class
10 Scanner sc = new Scanner ( System . in ) ;
11 System . out . print ( " enter array size " ) ;
12 size = sc . nextInt () ;
13 System . out . println ( " enter array elements " ) ;
14 for ( int i =0; i < size ; i ++)
15 arr [ i ]= sc . nextInt () ;
16 System . out . println ( " the array before insertion " ) ;
17 for ( int i =0; i < size ; i ++)
18 System . out . print ( arr [ i ]+ " " ) ;
19 System . out . println () ;
20 System . out . print ( " enter element to be insert " ) ;
21 insert = sc . nextInt () ;
22 System . out . print ( " enter the position " ) ;
23 poss = sc . nextInt () ;
24 for ( int i = size ;i > poss -1; i - -)
25 arr [ i ]= arr [i -1];
26 arr [ poss -1]= insert ;
27 System . out . println ( " element successfully inserted " ) ;
28 System . out . println ( " the array after insertion " ) ;
29 for ( int i =0; i <= size ; i ++)
30 System . out . print ( arr [ i ]+ " " ) ;
31

32 }
33 }

Page 8
Your Name / Class Java Notes

4.2 Deletion of an Array


1 import java . util .*;
2

3 public class DeleteByIndex {


4 public static void main ( String [] args ) {
5 int [] arr = {10 , 20 , 30 , 40 , 50};
6 int index = 2; // delete element at index 2
7

8 // Shift elements to the left


9 for ( int i = index ; i < arr . length - 1; i ++) {
10 arr [ i ] = arr [ i + 1];
11 }
12

13 // Print updated array ( length reduced by 1)


14 System . out . print ( " Array after deletion : " ) ;
15 for ( int i = 0; i < arr . length - 1; i ++) {
16 System . out . print ( arr [ i ] + " " ) ;
17 }
18 }
19 }

4.3 Merging of an Array


1 # include < stdio .h >
2

3 int main () {
4 int arr1 [10] , arr2 [10] , merged [20];
5 int n1 , n2 , i , j , k ;
6

7 printf ( " Enter number of elements in first array : " ) ;


8 scanf ( " % d " , & n1 ) ;
9 printf ( " Enter elements of first array :\ n " ) ;
10 for ( i = 0; i < n1 ; i ++)
11 scanf ( " % d " , & arr1 [ i ]) ;
12

13 printf ( " Enter number of elements in second array : " ) ;


14 scanf ( " % d " , & n2 ) ;
15 printf ( " Enter elements of second array :\ n " ) ;
16 for ( j = 0; j < n2 ; j ++)
17 scanf ( " % d " , & arr2 [ j ]) ;
18

19 // Merging both arrays


20 for ( i = 0; i < n1 ; i ++)
21 merged [ i ] = arr1 [ i ];
22

23 for ( j = 0; j < n2 ; j ++)


24 merged [ n1 + j ] = arr2 [ j ];
25

26 // Display merged array

Page 9
Your Name / Class Java Notes

27 printf ( " \ nMerged array : " ) ;


28 for ( k = 0; k < n1 + n2 ; k ++)
29 printf ( " % d " , merged [ k ]) ;
30

31 return 0;
32 }

5 Assigning one Array to another Array


5.1 Scenario-1: Using variable assignment
This method has side effects as both array variables reference the **same object** in
memory. Changes to one array reflect on the other.
1 // Scenario 1: Copy array using assignment
2 int [] a = {1 , 2 , 3};
3 int [] b = a ;
4 // test side effect
5 b [0]++;
6 // Array a : [2 , 2 , 3]
7 // Array b : [2 , 2 , 3]

5.2 To prevent side effects (Better ways to copy the array):


• **Scenario-2: Create a new array and copy each element by iterating.**

• **Scenario-3: Use the clone() method** of the array. This creates a new array of
the same size with a shallow copy of elements.

• **Scenario-4: Use [Link]() method.

5.3 Create a new array and copy each element by iterating.


1 // Java program to demonstrate copying
2 // copying an array by assigning
3 // elements one by one
4 public class copy {
5

6 public static void main ( String [] args ) {


7

8 int a [] = { 1 , 8 , 3 };
9

10 // Create an array b [] of same size as a []


11 int b [] = new int [ a . length ];
12

13 // Copying elements of a [] to b []
14 for ( int i = 0; i < a . length ; i ++)
15 b [ i ] = a [ i ];
16

Page 10
Your Name / Class Java Notes

17 // Changing b [] to verify that


18 // b [] is different from a []
19 b [0]++;
20

21 System . out . println ( " " ) ;


22

23 for ( int i = 0; i < a . length ; i ++)


24 System . out . print ( a [ i ] + " " ) ;
25

26 System . out . println ( " " ) ;


27

28 for ( int i = 0; i < b . length ; i ++)


29 System . out . print ( b [ i ] + " " ) ;
30 }
31 }

5.4 Using Clone()


1 class copy {
2 public static void main ( String args [])
3 {
4 int intArray [] = { 1 , 2 , 3 };
5

6 int cloneArray [] = intArray . clone () ;


7

8 // will print false as shallow copy is created


9 System . out . println ( intArray == cloneArray ) ;
10

11 for ( int i = 0; i < cloneArray . length ; i ++) {


12 System . out . print ( cloneArray [ i ] + " " ) ;
13 }
14 }
15 }
16 Output :
17 false \\
18 1 2 3

Syntax of [Link]():

v o i d a r r a y c o p y ( Object s r c , i n t srcPos ,
Object de st , i n t destPos , i n t l e n g t h )

• src: The source array.

• srcPos: The starting position in the source array.

• dest: The destination array.

• destPos: The starting position in the destination array.

Page 11
Your Name / Class Java Notes

• length: The number of elements to be copied.

1 // Java program to demonstrate array


2 // copy using System . arraycopy ()
3 public class Sample {
4

5 public static void main ( String [] args ) {


6

7 int a [] = { 1 , 8 , 3 };
8

9 // Creating an array b [] of same size as a []


10 int b [] = new int [ a . length ];
11

12 // Copying elements of a [] to b []
13 System . arraycopy (a , 0 , b , 0 , 3) ;
14

15 // Changing b [] to verify that


16 // b [] is different from a []
17 b [0]++;
18

19 System . out . println ( " " ) ;


20

21 for ( int i = 0; i < a . length ; i ++)


22 System . out . print ( a [ i ] + " " ) ;
23

24 System . out . println ( " " ) ;


25

26 for ( int i = 0; i < b . length ; i ++)


27 System . out . print ( b [ i ] + " " ) ;
28 }
29 }
30 Output :
31 1 8 3
32 2 8 3

6 Dynamic change of array size in Java


In Java, the array size is **fixed** when it is created. To ”resize” an array, you must
create a new array with the desired size and copy the contents of the old array into it.

Example using [Link]():

1 import java . util . Arrays ;


2 class HelloWorld {
3 public static void main ( String args () ) {
4 int [] oldArray = {1 , 2 , 3};
5 int [] newArray = new int [6];
6 System . arraycopy ( oldArray , 0 , newArray , 0 , 3) ;
7 oldArray = null ; // Delete the old array

Page 12
Your Name / Class Java Notes

8 System . out . println ( Arrays . toString ( newArray ) ) ;


9 }
10 }
11 // Output : [1 , 2 , 3 , 0 , 0 , 0]

7 Sorting of Arrays
7.1 Bubble Sort
Bubble Sort is a comparison-based sorting algorithm where each element is compared
with the next and swapped if they are not in the correct order.
• **Time Complexity**: O(N 2 )
• **Space Complexity**: O(1)

Algorithm for Bubble Sort in Java


1. Repeat for i = 0 to n − 1:
2. For j = 0 to n − i − 1:
3. if (arr[j] > arr[j + 1]):
4. swap(arr[j], arr[j + 1])

7.2 Selection Sort


Selection sort selects the smallest element from an unsorted list in each iteration and
places that element at the beginning of the unsorted list.

Selection Sort Algorithm


1. selectionSort(array, size)
2. for i from 0 to size - 1 do
3. set i as the index of the current minimum
4. for j from i + 1 to size - 1 do
5. if array[j] < array[current minimum]
6. set j as the new current minimum index
7. if current minimum is not i
8. swap array[i] with array[current minimum]

7.3 Insertion Sort


Insertion Sort selects a key in each iteration (starting from the second element), shifts all
greater elements before it toward their right, and places the key in the proper position.

Page 13
Your Name / Class Java Notes

Insertion Sort Algorithm


1. Iterate for index 1 to n − 1 of the list.

2. Compare the key (element at current index) with the preceding element.

3. If the key is smaller, compare it to other preceding elements. Shift greater elements
one position to their right to make space.

4. Store the key in the proper position.

8 Search for Values in Arrays


8.1 Linear Search
Linear search is a sequential searching algorithm that checks every element of the list
from one end until the desired element is found.

Algorithm

1 LinearSearch ( array , key )


2 for each item in the array
3 if item == value
4 return its index
5 return -1

8.2 Binary Search


Binary Search is a searching algorithm for finding an element’s position in a **sorted
array**. It works by repeatedly dividing the search interval in half.

Algorithm (Recursive)

1 binarySearch ( arr , x , low , high )


2 if low > high
3 return False
4 else
5 mid = ( low + high ) / 2
6 if x == arr [ mid ]
7 return mid
8 else if x > arr [ mid ] // x is on the right side
9 return binarySearch ( arr , x , mid + 1 , high )
10 else // x is on the left side
11 return binarySearch ( arr , x , low , mid - 1)

Page 14
Your Name / Class Java Notes

9 Array Class
• The Arrays class in [Link] 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.
• This class contains various methods for manipulating arrays (such as sorting and
searching).
• The methods of this class can be used by the class name itself.

9.1 Methods in java Array class


1 public static void main ( String [] args )
2 {
3 // Get the Array
4 int intArr [] = { 10 , 20 , 15 , 22 , 35 };
5 // To convert the elements as List
6 System . out . println ( " Integer Array as List : " + Arrays .
asList ( intArr ) ) ;
7 // Output : Integer Array as List : [[ I@19469ea2 ]
8 Arrays . sort ( intArr ) ; // Output :10 ,15 ,20 ,22 ,35
9 // Binary Search
10 int intKey = 22;
11 System . out . println ( intKey + " found at index = "
12 + Arrays . binarySearch ( intArr , intKey ) ) ; // 22 found at
index = 3
13 // equals
14 int intArr1 [] = { 10 , 15 , 22 };
15 System . out . println ( " Integer Arrays on comparison : " + Arrays .
equals ( intArr , intArr1 ) ) ; // false
16 // fill
17 Arrays . fill ( intArr , 22) ;
18 System . out . println ( " Integer Array on filling : "
19 + Arrays . toString ( intArr ) ) ;
20 // output : 22 22 22 22 22
21 // hashcode
22 System . out . println ( " Integer Array : "
23 + Arrays . hashCode ( intArr ) ) ;
24 // output : Integer Array : 38475313
25 }

10 2D Arrays in Java
A 2D array in Java is an array of arrays. Think of it like a table with rows and columns,
where each cell holds a value. It’s like a grid or matrix that can store data in a more
organized way.

Page 15
Your Name / Class Java Notes

10.1 Declaring and Initialsing a 2D Array


1 // Declaring a 2 D array
2 int [][] matrix ;
3

4 // Initializing a 2 D array with a size of 3 x3


5 matrix = new int [3][3];
6

7 // Declaring and initializing a 2 D array in one step


8 int [][] matrix = {
9 {1 , 2 , 3} ,
10 {4 , 5 , 6} ,
11 {7 , 8 , 9}
12 };

10.2 Accessing Elements


1 int value = matrix [1][2]; // Accesses the element at the
second row and third column
2 System . out . println ( value ) ; // Outputs : 6

10.3 Iterating through a 2D Array


1 for ( int i = 0; i < matrix . length ; i ++) { // Loop through rows
2 for ( int j = 0; j < matrix [ i ]. length ; j ++) { // Loop through
columns
3 System . out . print ( matrix [ i ][ j ] + " " ) ;
4 }
5 System . out . println () ; // New line after each row
6 }

11 Arrays of Varying Length


A jagged array in Java is an array of arrays, where each element of the array can be a
different size. This is in contrast to a traditional multidimensional array, where all of the
inner arrays must have the same size.

2 package j av a p ro g r am m i ng d e mo ;
3 import java . util . Scanner ;
4 public class javalabclass {
5 public static void main ( String args [])
6 {
7 int jaggedArr [][] = new int [4][];
8

9 jaggedArr [0] = new int [5];

Page 16
Your Name / Class Java Notes

10 jaggedArr [1] = new int [2];


11 jaggedArr [2] = new int [4];
12 jaggedArr [3] = new int [2];
13

14 // filling values
15 for ( int i =0; i < jaggedArr . length ; i ++)
16 {
17 for ( int j =0; j < jaggedArr [ i ]. length ; j ++)
18 {
19 jaggedArr [ i ][ j ] = i +1;
20 }
21 }
22

23 // printing
24 for ( int m []: jaggedArr )
25 {
26 for ( int k : m )
27 {
28 System . out . print ( k + " " ) ;
29 }
30 System . out . println () ;
31 }
32 }
33 }
34

35 Output
36 1 1 1 1 1
37 2 2
38 3 3 3 3
39 4 4

12 Three Dimensional Arrays


3-D arrays are referred to as multi-dimensional arrays. Multi-dimensional arrays are de-
fined as an “array of arrays” that store data in a tabular form.

An array list of data elements makes a 1-D (one-dimensional) array. An array of 1-D
arrays makes a 2-D (two-dimensional) array. Similarly, an array of 2-D arrays makes a
3-D ( three-dimensional) array.

1 int arr [4][5][8]


2 // declares an 3 - D integer array

This array can store a total of 4 X 5 X 8 = 160 elements.

1 class HelloWorld {
2 public static void main ( String args [] ) {
3

4 int [][][] arr = {

Page 17
Your Name / Class Java Notes

5 { {0 ,1 ,2} , {2 ,3 ,4} , {6 ,7 ,1} } ,


6 { {6 ,7 , 1} , {8 ,9 , 2} , {9 ,14 , 22} }
7 };
8 // accessing single value i . e 0
9 System . out . println ( arr [0][0][0]) ;
10

11 // output each element ’s value by iterating through the array


12

13 for ( int i = 0; i < 2; ++ i )


14 {
15 for ( int j = 0; j < 3; ++ j )
16 {
17 for ( int k = 0; k < 3; ++ k )
18 {
19

20 System . out . println ( " Element at arr [ " + i + "


][ " + j
21 + " ][ " + k + " ] = " + arr [ i ][ j ][ k ]) ;
22

23 }
24 }
25 }
26 }
27 }

13 Arrays as Vectors
• Vector class implements a growable array of objects. It is compatible with Java
collections.

• Vector implements a dynamic array–means it can grow or shrink as required.

• It contains components that can be accessed using an integer index like an array.

1 Vector < Type > vector = new Vector < >() ;

13.1 convert an array to a vector


There are 3 ways

• Using [Link] method

• Using [Link]() method

• Using loop

Page 18
Your Name / Class Java Notes

1 import java . util .*;


2 public class array_to_vector {
3 public static void main ( String [] args )
4 {
5 String [] arr = { " Hi , Hello " , pvpsit };
6 Vector < String > v = new Vector < String >() ;
7

8 Collections . addAll (v , arr ) ;


9 System . out . println ( " The vector is " ) ;
10

11 System . out . println ( v ) ;


12 }
13 }
Listing 5: using addAll

2 import java . util .*;


3

4 public class array_to_vector {


5

6 public static void main ( String [] args )


7 {
8

9 String [] arr = { hi , hello , pvpsit };


10

11 Vector < String > v = new Vector < String >( Arrays . asList ( arr ) ) ;
12

13 System . out . println ( " The vector is " ) ;


14

15 System . out . println ( v ) ;


16 }
17 }
Listing 6: asList

2 import java . util .*;


3 public class array_to_vector {
4 public static void main ( String [] args )
5 {
6

7 String [] arr = { " I " , " love " ," java " };
8

9 Vector < String > v = new Vector < String >() ;


10

11 for ( int i = 0; i < arr . length ; i ++)


12 v . addElement ( arr [ i ]) ;
13 System . out . println ( " The vector is " ) ;
14 System . out . println ( v ) ;
15 }
16 }

Page 19
Your Name / Class Java Notes

Listing 7: forloop

14 Introduction to Inheritance
• Inheritance in Java is a mechanism in object-oriented programming (OOP) that
allows you to create new classes based on existing classes. The existing class is
known as the **parent class** or **superclass**, and the new class is known as the
**child class** or **subclass**.

• Inheritance allows you to reuse the code and behavior of the parent class in the
child class. This can save you time and effort when writing your code, and it can
also make your code more readable and maintainable.

14.1 Benefits of using inheritance in Java


There are several benefits to using inheritance in Java, including:

• Code reuse: Inheritance allows you to reuse the code and behavior of the parent
class in the child class. This can save you time and effort when writing your code.

• Readability and maintainability: Inheritance can make your code more readable
and maintainable by making it clear what code is inherited from the parent class
and what code is new in the child class.

• Polymorphism: Inheritance allows you to implement polymorphism, which is the


ability of objects of different types to respond to the same method in different ways.

14.2 Key Terminologies Used in Java Inheritance


• Class: Class is a set of objects that share common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template
or blueprint or prototype from which objects are created.

• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).

• Sub Class/Child Class: The class that inherits the other class is known as a sub-
class(or a derived class, extended class or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.

• Extends Keyword: This keyword is used to inherit properties from a superclass.

Page 20
Your Name / Class Java Notes

15 Process of Inheritance
15.1 Types of Relationships
15.1.1 Is-A Relationship in Java
• The is-a relationship, also known as the inheritance relationship, represents a type of
relationship between two classes where one class is a specialized version of another.

• It implies that a subclass is a specific type of its superclass.

• For example, a Potato is a Vegetable, a Bus is a Vehicle, a Bulb is an ElectronicDe-


vice, Dog is an Animal and so on.

• One of the properties of inheritance is that inheritance is unidirectional in nature.


Like we can say that a house is a building. But not all buildings are houses.

• The is-a relationship is implemented in Java using the extends keyword.

1 class SuperClass {
2 void methodSuper () {
3 System . out . println ( " I am a super class method " ) ;
4 }
5 }
6

7 // Inheriting SuperClass to SubClass


8 class SubClass extends SuperClass {
9 void methodSubclass () {
10 System . out . println ( " I am a sub class method " ) ;
11 }
12 }
13 class Main {
14 public static void main ( String args []) {
15 SubClass obj = new SubClass () ;
16 obj . methodSubClass () ;
17 obj . methodSuper () ;
18 }
19 }
Listing 8: Is a Relationship

15.1.2 Has-A-Relation in Java

15.2 Has-A-Relation in Java


• Suppose we declare two different classes in Java. Between those two classes, there
can be two types of relationships. This relationship can be either an Is-A relation-
ship or a Has-A relationship.

• Is-A relationship is achieved by inheritance, and Has-A-relationship can be achieved


using composition or aggregation.

Page 21
Your Name / Class Java Notes

15.2.1 Composition
• Composition is a strong association between two classes

• The lifetime of the contained child object depends on parent object

• Scenario-Employee has a dependent

15.2.2 Aggregation
• Aggregation is a weaker form of association

• The lifetime of child object is not dependent on parent object

15.3 How to Decide which Type of Relation We Need


• Suppose there is a Jeep and its name is ”Mahindra Thar”. Then we say that
”Mahindra Thar is a Jeep”. ”Mahindra Thar has a jeep” this sentence does not
make any sense. The relationship totally depends upon the phrase we used.

• ”Mahindra Thar” has an Engine, or ”Mahindra Thar” has an AC makes sense


rather than ”Mahindra Thar” is an engine or ”Mahindra Thar” is an AC.

• So, if your problem with a phrase containing ”.... is a . . . .” words, you should you
Is-a a relationship or else use Has-a relationship.

16 Super
• The ‘super‘ keyword in Java is used to refer to the superclass (parent) object. It is
used to call superclass methods, and to access the superclass constructor.

• The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name. For example,
if the ‘Animal‘ class has an ‘eat()‘ method, and the ‘Dog‘ class inherits from the

Page 22
Your Name / Class Java Notes

‘Animal‘ class, the ‘Dog‘ class will also have an ‘eat()‘ method. However, the ‘Dog‘
class’s ‘eat()‘ method may implement different behavior than the ‘Animal‘ class’s
‘eat()‘ method.

• To call the Animal class’s eat() method from the Dog class, you can use the ‘super‘
keyword. For example, the following code shows how to call the ‘Animal‘ class’s
‘eat()‘ method from the ‘Dog‘ class:

1 public class Animal {


2 public void eat () {
3 System . out . println ( " The animal is eating . " ) ;
4 }
5 }
6 public class Dog extends Animal {
7 @Override
8 public void eat () {
9 super . eat () ;
10 System . out . println ( " The dog is eating . " ) ;
11 }
12 }
Listing 9: calling superclass method

16.1 Code to demonstrate the order of constructor calls with a


parameterized constructor in the sub class.
1 package javalabdemo ;
2 import java . util . Scanner ;
3

4 public class javalabclass


5 {
6 public static void main ( String args [])
7 {
8 faculty xyz = new faculty ( " 123 " ) ;
9 xyz . display_details () ;
10 xyz . display_faculty () ;
11 }
12 }
13

14 class person
15 {
16 protected String name ;
17 protected String address ;
18

19 public person () {
20 System . out . println ( " super class constructor called " ) ;
21 this . name = " xyz " ;
22 this . address = " pvpsit " ;
23 }
24

Page 23
Your Name / Class Java Notes

25 public void display_details () {


26 System . out . println ( this . name + this . address ) ;
27 }
28 }
29

30 class faculty extends person


31 {
32 protected String empid ;
33

34 public faculty ( String empid ) {


35 System . out . println ( " subclass constructor called " ) ;
36 this . empid = empid ;
37 }
38

39 public void display_faculty ()


40 {
41 System . out . println ( this . empid ) ;
42 }
43

44 }
Listing 10: parameterised constructor

16.2 Code to demonstrate the use of Super method when both


super class and sub class has parameterized constructors.
1

2 package javalabdemo ;
3 public class javalabclass
4 {
5 public static void main ( String args [])
6 {
7 faculty xyz = new faculty ( " xyz " ," pvpsit " ," 123 " ) ;
8 xyz . display_details () ;
9 xyz . display_faculty () ;
10 }
11 }
12

13 class person
14 {
15 protected String name ;
16 protected String address ;
17

18 public person ( String name , String address ) {


19 System . out . println ( " super class constructor called " ) ;
20 this . name = name ;
21 this . address = address ;
22 }
23

24 public void display_details () {

Page 24
Your Name / Class Java Notes

25 System . out . println ( this . name + this . address ) ;


26 }
27 }
28

29 class faculty extends person


30 {
31 protected String empid ;
32

33 public faculty ( String name , String address , String empid ) {


34 super ( name , address ) ;
35 System . out . println ( " subclass constructor called " ) ;
36 this . empid = empid ;
37 }
38

39 public void display_faculty ()


40 {
41 System . out . println ( this . empid ) ;
42 }
43

44 }
Listing 11: super

16.3 Code for demonstrating order of constructor calls and the


use of Super method in Multi level inheritance.
1 package javalabdemo ;
2 public class javalabclass
3 {
4 public static void main ( String args [])
5 {
6 professor satish = new professor ( " satish " ," vellore " ," 123 " ,"
116 " ) ;
7 satish . display_details () ;
8 satish . display_faculty () ;
9 satish . di splay_ profes sor () ;
10 }
11 }
12

13 class person
14 {
15 protected String name ;
16 protected String address ;
17

18 public person ( String name , String address ) {


19 System . out . println ( " super class constructor called " ) ;
20 this . name = name ;
21 this . address = address ;
22 }
23

Page 25
Your Name / Class Java Notes

24 public void display_details () {


25 System . out . println ( this . name + this . address ) ;
26 }
27 }
28

29 class faculty extends person


30 {
31 protected String empid ;
32

33 public faculty ( String name , String address , String empid ) {


34 super ( name , address ) ;
35 System . out . println ( " subclass constructor called " ) ;
36 this . empid = empid ;
37 }
38

39 public void display_faculty ()


40 {
41 System . out . println ( this . empid ) ;
42 }
43

44 }
45

46 class professor extends faculty


47 {
48 protected String cabinno ;
49

50 public professor ( String name , String address , String empid ,


String cabinno ) {
51 super ( name , address , empid ) ;
52 this . cabinno = cabinno ;
53 }
54

55 public void di splay_ profes sor () {


56 System . out . println ( this . cabinno ) ;
57 }
58 }
Listing 12: Is a Relationship

17 Inhibiting Inheritance of Class Using Final


What Does final Mean in Java?

• The final keyword is a modifier that can be applied to:

• Variables → value cannot be changed once assigned.

• Methods → cannot be overridden by subclasses.

• Classes → cannot be extended (i.e., no subclassing allowed)

Page 26
Your Name / Class Java Notes

17.1 Inhibiting inheritance through final class


When a class is declared as final, it cannot be subclassed. This is useful when you want
to prevent other developers from altering the behavior of your class through inheritance.

1 final class Vehicle {


2 void display () {
3 System . out . println ( " This is a vehicle . " ) ;
4 }
5 }
6

7 // This will cause a compile - time error


8 class Car extends Vehicle {
9 // ERROR : Cannot inherit from final class
10 }
Listing 13: final class

17.2 Prventing method overriding using final


if you want a method to be inherited but not overridden, declare it as final.
1 class Animal {
2 final void sound () {
3 System . out . println ( " Animal makes sound " ) ;
4 }
5 }
6

7 class Dog extends Animal {


8 // This will cause a compile - time error
9 // void sound () { System . out . println (" Dog barks ") ; }
10 }
Listing 14: final method

18 Access Control and Inheritance


When a subclass inherits from a superclass, it inherits all members, but:

• Private members are not accessible directly. (Still exist in memory, but cannot be
accessed.)

• Default (package-private) members are accessible only if subclass is in the same


package.

• Protected members are accessible in subclass, even if subclass is in a different pack-


age (but only through inheritance, not via object reference).

• Public members are accessible everywhere.

Page 27
Your Name / Class Java Notes

19 Universal Super Class-Object Class


• The [Link] class is the root or superclass of the class hierarchy, it belongs
to the [Link] package. All predefined classes and user-defined classes are direct
or indirect subclasses of the Object class.

• If a class does not extend any other class then it is a direct child class of the Java
Object class and if it extends another class then it is indirectly derived.

• There are 11 common properties that every Java class must implement. But it
would be difficult for developers to repeat the same boilerplate code in each class.
The Object class implements all these 11 properties through 11 methods, making
Java programming a little simpler,

20 Constructor Method and Inheritance


• When a class inherits from another class:

• Constructors are not inherited (they are not members of the class).

• But the parent constructor is always called (directly or indirectly) when creating
an object of the child class.

• The call to the parent constructor happens through super().

1 class Animal {
2 Animal () {
3 System . out . println ( " Animal constructor called " ) ;
4 }
5 }
6 class Dog extends Animal {
7 Dog () {
8 super () ;
9 // Calls Animal () constructor \\
10 ( implicitly added if not written )
11 System . out . println ( " Dog constructor called " ) ;
12 }
13 }
14 public class Main {
15 public static void main ( String [] args ) {
16 Dog d = new Dog () ;
17 }}
Listing 15: call to parent constructor

21 Method overriding
If the same method is defined in both the superclass and the subclass, then the method
of the subclass class overrides the method of the superclass. This is known as method

Page 28
Your Name / Class Java Notes

overriding.
Method Overriding

• The method in the subclass must have the same name, return type, and parameters
as the method in the superclass.

• It allows a subclass to provide a specific implementation for a method that is already


defined in its superclass.

• We cannot override the method that is declared as final.

22 Dynamic Method Dispatch


Dynamic Method Dispatch is a way in Java to decide which version of a method to call
at runtime (when the program is running

It works like this:

• You have a superclass with a method.

• A subclass overrides that method (writes its own version).

• You create a reference of the superclass but store a subclass object in it.

• When you call the method, Java looks at the actual object type (not the reference
type) and calls the correct version of the method

1 . class A
2 {
3 void m1 ()
4 {
5 System . out . println ( " Inside A ’s m1 method " ) ;
6 }
7 }
8

9 class B extends A
10 {
11 // overriding m1 ()
12 void m1 ()
13 {
14 System . out . println ( " Inside B ’s m1 method " ) ;
15 }
16 }
17

18 class C extends A
19 {
20 // overriding m1 ()
21 void m1 ()
22 {

Page 29
Your Name / Class Java Notes

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


24 }
25 }
26

27 // Driver class
28 class Dispatch
29 {
30 public static void main ( String args [])
31 {
32 // object of type A
33 A a = new A () ;
34

35 // object of type B
36 B b = new B () ;
37

38 // object of type C
39 C c = new C () ;
40

41 // obtain a reference of type A


42 A ref ;
43

44 // ref refers to an A object


45 ref = a ;
46

47 // calling A ’s version of m1 ()
48 ref . m1 () ;
49

50 // now ref refers to a B object


51 ref = b ;
52

53 // calling B ’s version of m1 ()
54 ref . m1 () ;
55

56 // now ref refers to a C object


57 ref = c ;
58

59 // calling C ’s version of m1 ()
60 ref . m1 () ;
61 }
62 }
Listing 16: Dynamic Method Dispatch

23 Abstract class
Abstract classes in Java are classes that cannot be instantiated directly. They must be
extended by other classes, which are known as subclasses. Abstract classes can contain
both abstract and non-abstract methods. Abstract methods are methods that do not
have an implementation in the abstract class. Subclasses must provide their own imple-
mentations for abstract methods.

Page 30
Your Name / Class Java Notes

Abstract classes are used to provide a common functionality for a group of related
classes. For example, you could create an abstract class called ‘Animal‘ that contains ab-
stract methods such as ‘eat()‘ and ‘sleep()‘. Then, you could create subclasses of ‘Animal‘
such as ‘Dog‘, ‘Cat‘, and ‘Bird‘. Each subclass would provide its own implementation for
the abstract methods in the ‘Animal‘ class.
Use abstract classes to provide a common functionality for a group of related classes.
Be careful not to overuse abstract classes, as this can make your code difficult to read
and maintain.
Document the reasons for using abstract classes in your code.

1 package j av a p ro g r am m i ng d e mo ;
2 public class javalabclass {
3

4 public static void main ( String [] args ) {


5 // cannot instantiate an abstract class
6 // constructors are allowed for an abstract class
7 // final methods are allowed
8 square s = new square (2) ;
9 s . calculate_area () ;
10 s . display_area () ;
11 square . test () ;
12 }
13 }
14

15 // an abstract class is given below


16 abstract class shape
17 {
18 float area ;
19 public shape () {
20 this . area =0.0 F ;
21 }
22 // abstract method declaration
23 abstract public void calculate_area () ;
24 public static void test ()
25 {
26 System . out . println ( " hello from static method " ) ;
27 }
28 public final void display_area ()
29 {
30 System . out . println ( area ) ;
31 }
32 }
33

34 // extending the abstract class .


35 class square extends shape
36 {
37 int side ;
38 public square ( int side ) {
39 this . side = side ;

Page 31
Your Name / Class Java Notes

40 }
41 // implementing the abstract method
42 // its mandatory to provide the implementation of the
43 // abstract methods inherited .
44 public void calculate_area () {
45 this . area = side * side ;
46 }
47 }
Listing 17: Abstract class

24 Interfaces
• An interface in Java is a reference type that defines a set of methods without
providing any implementations.

• Interfaces are used to achieve abstraction and polymorphism in Java.

• Abstraction allows you to focus on the behavior of a class without worrying about
its implementation.

• Polymorphism allows you to treat different objects as if they were of the same type,
as long as they implement the same interface.

• Interface contain only abstract methods. The methods are abstract and public by
default.

• Interface cannot be instantiated.

• Interface do not have a constructor.

• Interface can contain only static and final variables that are public.

• A class should implement all the methods in an interface.

• A class can implement many interfaces.

24.1 Multiple Interfaces in Java


• In Java, a class can implement multiple interfaces.

• This is Java’s way of achieving multiple inheritance (since Java does not allow a
class to inherit from more than one class).

1 // Declare the interfaces


2 interface Walkable {
3 void walk () ;
4 }
5

6 interface Swimmable {
7 void swim () ;

Page 32
Your Name / Class Java Notes

Figure 2: Interface

8 }
9

10 // Implement the interfaces in a class


11 class Duck implements Walkable , Swimmable {
12 public void walk ()
13 {
14 System . out . println ( " Duck is walking . " ) ;
15 }
16

17 public void swim ()


18 {
19 System . out . println ( " Duck is swimming . " ) ;
20 }
21 }
22

23 // Use the class to call the methods from the interfaces


24 class Main {
25 public static void main ( String [] args )
26 {
27 Duck duck = new Duck () ;
28 duck . walk () ;
29 duck . swim () ;
30 }
31 }
Listing 18: Multiple Interfaces

Page 33
Your Name / Class Java Notes

24.2 Nested Interfaces


• A nested interface is an interface declared inside a class or another [Link] Java,
a Nested Interface is an interface declared inside a class or another interface. In
Java, nested interfaces can be declared with the public, protected, package-private
(default) or private access specifiers.

• A nested interface inside a class can be public, protected, package-private (default)


or private.

• A nested interface inside another interface is implicitly public static.

• A top-level interface (not nested) can only be public or package-private (default);


it cannot be protected or private.

1 import java . util .*;


2

3 // Nested Interface - Interface


4 interface Parent {
5 interface Test {
6 void show () ;
7 }
8 }
9

10 class Child implements Parent . Test {


11 public void show () {
12 System . out . println ( " show method of interface " ) ;
13 }
14 }
15 // Main Class
16 class Main
17 {
18 public static void main ( String [] args )
19 {
20 Parent . Test obj ;
21 Child t = new Child () ;
22 obj = t ;
23 obj . show () ;
24 }
25 }
Listing 19: Interface inside another interface

1 public class Sample {


2

3 // Nested interface
4 public interface NestedInterface {
5 public void nestedMethod () ;
6 }
7

8 public static void main ( String [] args )


9 {

Page 34
Your Name / Class Java Notes

10 // Implement nested interface


11 NestedInterface nested = new NestedInterface () {
12 public void nestedMethod ()
13 {
14 System . out . println (
15 " Hello from nested interface ! " ) ;
16 }
17 };
18

19 // Call nested interface method


20 nested . nestedMethod () ;
21 }
22 }
Listing 20: Nested Interface inside the class

24.3 Inheritance of Interfaces in Java


Java, interfaces can inherit from other interfaces using the extends keyword. This is
called interface inheritance.

Key points:

• A sub-interface inherits all abstract methods from the parent interface.

• Any class that implements the child interface must provide implementations for all
methods of both parent and child interfaces.

• Unlike classes, interfaces can extend multiple interfaces (so one interface can inherit
from many)

1 interface InterfaceA {
2

3 void name () ;
4 }
5

6 interface InterfaceB extends InterfaceA {


7

8 void institute () ;
9 }
10

11 class Sample implements InterfaceB {


12

13 public void name () {


14

15 System . out . println ( " Rohit " ) ;


16 }
17

18 public void institute () {


19

20 System . out . println ( " PVPSIT " ) ;

Page 35
Your Name / Class Java Notes

21 }
22

23 public static void main ( String [] args ) {


24

25 Sample s = new Sample () ;


26 s . name () ;
27 s . institute () ;
28 }
29 }
Listing 21: Inheritance in Interfaces

24.4 Default Methods in Interface


By default, all methods in interfaces are abstract (no body).
But since Java 8, we can define default methods in interfaces, which have a method body.

Key Points

• Declared using the default keyword.

• Provide a default implementation for classes that implement the interface.

• A class can override the default method if it wants to provide its own implementa-
tion.

• Used mainly to add new functionality to interfaces without breaking existing code.

1 interface TestInterface
2 {
3 // abstract method
4 public void square ( int a ) ;
5

6 // default method
7 default void show ()
8 {
9 System . out . println ( " Default Method Executed " ) ;
10 }
11 }
12

13 class TestClass implements TestInterface


14 {
15 // implementation of square abstract method
16 public void square ( int a )
17 {
18 System . out . println ( a * a ) ;
19 }
20

21 public static void main ( String args [])


22 {

Page 36
Your Name / Class Java Notes

23 TestClass d = new TestClass () ;


24 d . square (4) ;
25

26 // default method executed


27 d . show () ;
28 }
29 }
Listing 22: Default Method in an Interface

24.5 Static Methods in Interfaces


• Declared with the static keyword inside an interface.

• Contain a complete definition and cannot be overridden.

• Called using the interface name only (e.g., [Link]()).

• The scope of the static method is limited to the interface in which it is defined.

1 interface NewInterface {
2

3 // static method
4 static void hello ()
5 {
6 System . out . println ( " Hello , New Static Method Here " ) ;
7 }
8

9 // Public and abstract method of Interface


10 void overrideMethod ( String str ) ;
11 }
12 // Implementation Class
13 public class InterfaceDemo implements NewInterface {
14

15 public static void main ( String [] args )


16 {
17 InterfaceDemo interfaceDemo = new InterfaceDemo () ;
18

19 // Calling the static method of interface


20 NewInterface . hello () ;
21

22 // Calling the abstract method of interface


23 interfaceDemo . overrideMethod ( " Hello , Override Method here
");
24 }
25 // Implementing interface method
26

27 @Override
28 public void overrideMethod ( String str )
29 {
30 System . out . println ( str ) ;

Page 37
Your Name / Class Java Notes

31 }
32 }
Listing 23: static method in an interface

24.6 Difference between method overloading and overriding

24.7 Difference between class and interface


24.8 Difference between Abstract class and interface

Page 38
Your Name / Class Java Notes

Page 39

You might also like