Java UNIT - 3 Material
Java UNIT - 3 Material
Unit - 3
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
GATES-CSE(DS|CY) Page 1
Object Oriented Programming Through Java UNIT-3
Single Dimensional Array :
Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }
15. }
Output:
10
20
70
40
50
GATES-CSE(DS|CY) Page 2
Object Oriented Programming Through Java UNIT-3
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array have, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use the length property to specify
how many times the loop should run.
The following example outputs all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to loop through elements in arrays
Syntax
for (type variable : arrayname) {
...
}
GATES-CSE(DS|CY) Page 3
Object Oriented Programming Through Java UNIT-3
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
The example above can be read like this: for each String element (called i - as in index) in cars,
print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-each method is easier to
write, it does not require a counter (using the length property), and it is more readable.
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
GATES-CSE(DS|CY) Page 4
Object Oriented Programming Through Java UNIT-3
}
}
}
Arrays vs Vector
In Java, arrays and vectors are both used to store collections of elements, but they have different
characteristics and functionalities. Arrays are a basic and fixed-size data structure, while Vector is
a part of the Java Collections Framework and provides a dynamic array implementation with
additional features.
Vector is a part of the java.util package and is a dynamic array that can grow or shrink in size. It
provides several useful methods like adding, removing, and accessing elements, and it is
synchronized, making it thread-safe.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Creating a Vector of integers
Vector<Integer> numbers = new Vector<>();
// Adding elements to the Vector
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Modifying an element
numbers.set(2, 10);
System.out.println("Modified element at index 2: " + numbers.get(2));
GATES-CSE(DS|CY) Page 5
Object Oriented Programming Through Java UNIT-3
// Removing an element
numbers.remove(1);
System.out.println("Vector after removing element at index 1: " + numbers);
}
}
GATES-CSE(DS|CY) Page 6
Object Oriented Programming Through Java UNIT-3
Inheritance
GATES-CSE(DS|CY) Page 7
Object Oriented Programming Through Java UNIT-3
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. }}
Output:
16. black
17. 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();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Output:
GATES-CSE(DS|CY) Page 8
Object Oriented Programming Through Java UNIT-3
17. eating...
18. 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. }}
Output:
14. animal is created
15. dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
GATES-CSE(DS|CY) Page 9
Object Oriented Programming Through Java UNIT-3
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Output:
13. animal is created
14. dog is created
It is common that a class is derived from another derived class. The class student serves as a base
class for the derived class marks, which in turn serves as a base class for the derived class
percentage. The class marks is known as intermediates base class since it provides a link for the
inheritance between student and percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits
all of the features found in all of its super classes. In this case, percentage inherits all aspects of
marks and student.
To understand the flow of program read all comments of program.
GATES-CSE(DS|CY) Page 10
Object Oriented Programming Through Java UNIT-3
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
GATES-CSE(DS|CY) Page 11
Object Oriented Programming Through Java UNIT-3
GATES-CSE(DS|CY) Page 12
Object Oriented Programming Through Java UNIT-3
In simpler terms, Static binding means when the type of object which is invoking the method is
determined at compile time by the compiler. While Dynamic binding means when the type of object
which is invoking the method is determined at run time by the compiler.
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.
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
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.
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.
GATES-CSE(DS|CY) Page 13
Object Oriented Programming Through Java UNIT-3
O/p:
running safely
GATES-CSE(DS|CY) Page 14
Object Oriented Programming Through Java UNIT-3
// base class
abstract class Shape
{
private double width;
GATES-CSE(DS|CY) Page 15
Object Oriented Programming Through Java UNIT-3
// getHeight method is declared as final
// so any class extending Shape
// can not override it
public final double getHeight()
{
return height;
}
GATES-CSE(DS|CY) Page 16
Object Oriented Programming Through Java UNIT-3
//derived class two
class Square extends Shape
{
// Rectangle class parameterized constructor
public Square(double side)
{
// calling Shape class constructor
super(side, side);
}
// getArea method is overridden and declared as
// final so any class extending
// Square cann't override it
@Override
final double getArea()
{
return this.getHeight() * this.getWidth();
}
// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);
GATES-CSE(DS|CY) Page 17
Object Oriented Programming Through Java UNIT-3
// getting width and height of s2
System.out.println("width of s2 : "+ s2.getWidth());
System.out.println("height of s2 : "+ s2.getHeight());
//getting area of s1
System.out.println("area of s1 : "+ s1.getArea());
//getting area of s2
System.out.println("area of s2 : "+ s2.getArea());
}
}
Output:
width of s1 : 10.0
height of s1 : 20.0
width of s2 : 10.0
height of s2 : 10.0
area of s1 : 200.0
area of s2 : 100.0
When a class is declared as final then it cannot be subclassed i.e. no any other class can extend it.
This is particularly useful, for example, when creating an immutable class like the
predefined String class. The following fragment illustrates final keyword with a class:
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Note :
• Declaring a class as final implicitly declares all of its methods as final, too.
GATES-CSE(DS|CY) Page 18
Object Oriented Programming Through Java UNIT-3
• It is illegal to declare a class as both abstract and final since an abstract class is incomplete
by itself and relies upon its subclasses to provide complete implementations. For more on
abstract classes, refer abstract classes in java
Interface
Interface
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.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
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.
GATES-CSE(DS|CY) Page 19
Object Oriented Programming Through Java UNIT-3
6. }
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
GATES-CSE(DS|CY) Page 20
Object Oriented Programming Through Java UNIT-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. }
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone
else. The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
1. //Interface declaration: by first user
2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawabl
e()
16. d.draw();
17. }}
GATES-CSE(DS|CY) Page 21
Object Oriented Programming Through Java UNIT-3
Output: drawing circle
Multiple inheritance in Java by interface :
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output: Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's
see an example:
File: TestInterfaceDefault.java
1. interface Drawable{
GATES-CSE(DS|CY) Page 22
Object Oriented Programming Through Java UNIT-3
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}
Output:
drawing rectangle
default method
GATES-CSE(DS|CY) Page 23
Object Oriented Programming Through Java UNIT-3
27
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final
non-static variables. variables.
4) Abstract class can provide the implementation of Interface can't provide the
interface. implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.
6) An abstract classcan extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.
8) A Javaabstract classcan have class members like Members of a Java interface are public by
private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
GATES-CSE(DS|CY) Page 24
Object Oriented Programming Through Java UNIT-3
Exceptions in Java
GATES-CSE(DS|CY) Page 25