Apznzabrhwleihg81eirvirzpf-5y7m5ynf73ynoqedmsjf4 Nfvlifwhcoccdwddxqyigmuqotvl8mysxuzqzsfogijh2l Bx 3rssopzd5in4yxdtb0gbvbrxuuypbyz5lw36d Fp3bqti7zm5nhwmwqi4iffc5cg6iaz1yh7p07sxbnzmxvh2taiznvpkifnw60ib856awstbjbwh6y
Apznzabrhwleihg81eirvirzpf-5y7m5ynf73ynoqedmsjf4 Nfvlifwhcoccdwddxqyigmuqotvl8mysxuzqzsfogijh2l Bx 3rssopzd5in4yxdtb0gbvbrxuuypbyz5lw36d Fp3bqti7zm5nhwmwqi4iffc5cg6iaz1yh7p07sxbnzmxvh2taiznvpkifnw60ib856awstbjbwh6y
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:
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.
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.
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
{
a[i]=s.nextInt();
System.out.print(a[i]+",");
}
}
}
Output
Enter the elements into 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
This allocates a 4 by 4 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.
import java.util.Scanner;
class Testarray2
{
int m, n, i, j;
Scanner s=new Scanner(System.in);
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
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,
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.
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
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.
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.
InitializeDynamicArray.java
21. }
22. }
23. } Output:
Elements of Array are: 34 90 12 22 9 27
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.
Syntax:
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.
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:
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));
In the following example, we have initialized an array of integer type and sort the array in
ascending order.
SortArrayExample2.java
32. 3
33. 6
34. 20
35. 34
36. 34
37. 55
38. 78
39. 90
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:
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());
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.
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]
In the following example, we have initialized an integer array and perform sorting in descending
order.
SortArrayExample6.java
Output:
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. }
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:
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,
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];
}
}
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.
SN Method Description
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.
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.
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.
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.
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.
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
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.
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.
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.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
SN Constructor Description
3) vector(int initialCapacity, int It constructs an empty vector with the specified initial
capacityIncrement) capacity and capacity increment.
E> c) collection c.
Output:
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).
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.
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 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.
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
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
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...
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. }
Output:
weeping...
barking...
eating...
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
16. }}
Output:
meowing...
eating...
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
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.
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.
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 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.
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();
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.
public
default
protected
private
public
The member with public modifiers can be accessed by any classes. The public methods, variables or
class have the widest scope.
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";
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
}
}
Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
private Yes No No No
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
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.
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();
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.
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
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
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);
20. e1.display();
21. }}
Test it Now
Output:
1 ankit 45000
class A
void m1()
class B extends A
// overriding m1()
void m1()
class C extends A
// overriding m1()
void m1()
// Driver class
class Dispatch
// 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();
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.
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.
running safely
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.
o It can have final methods which will force the subclass not to change the body of the method.
running safely
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.
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
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.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.
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();
9. obj.print();
10. }
11. }
Test it Now
Output:
Hello
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.
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 {
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.
Java8Tester.java
public class Java8Tester {
interface Vehicle {
interface FourWheeler {
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.
There are several built-in annotations in Java. Some annotations are applied to Java code and
some to other annotations.
o @Override
o @SuppressWarnings
o @Deprecated
o @Target
o @Retention
o @Inherited
o @Documented
@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
@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. }
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:
At Runtime:
hello n
1. @interface MyAnnotation{}
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{}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
1. @interface MyAnnotation{
2. int value();
3. }
1. @interface MyAnnotation{
2. int value() default 0;
3. }
1. @MyAnnotation(value=10)
3) Multi-Value Annotation
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. }
1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }
1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
@Target
@Target tag is used to specify at which type, the annotation is used.
FIELD fields
METHOD methods
CONSTRUCTOR constructors
PARAMETER parameter
1. @Target(ElementType.TYPE)
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.
RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM . It is
included in the class file.
1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }
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.
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.