Arrays Unit 3
Arrays Unit 3
Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the string
type that can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.
..
Java Arrays initialization
Note:
• Array indices always start from 0. That is, the first element of an array is at index 0.
• If the size of an array is n, then the last element of the array will be at index n-1.
// create an array
int[] age = {12, 4, 5};
2. Accessing Elements
To access or modify an element, use the row and column indices:
array[row][column] = value;
int value = array[row][column];
Example:
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2},
UNIT -3
{3, 4},
{5, 6}
};
2. Accessing Elements
To access or modify an element, specify the indices for depth, row, and column:
array[depth][row][column] = value;
int value = array[depth][row][column];
Example:
public class Main {
public static void main(String[] args) {
int[ ][ ][ ] array = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
// Modify an element
array[0][1][2] = 99;
System.out.println(array[0][1][2]); // Output: 99
}
}
UNIT -3
Java ArrayList
In Java, we use the ArrayList class to implement the functionality of resizable-arrays.
It implements the List interface of the collections framework .
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we can
create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();
Here, Type indicates the type of an arraylist. For example,
// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();
Output
ArrayList: [Java, Python, Swift]
In the above example, we have created an ArrayList named languages.
Here, we have used the add() method to add elements to the arraylist. We will learn more about
the add() method later in this tutorial.
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
languages.add("C");
languages.add("Python");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, C, Python]
In the above example, we have created an ArrayList named languages. Here, we have used
the add() method to add elements to languages.
2. Access ArrayList Elements
To access an element from the arraylist, we use the get() method of the ArrayList class. For
example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// add elements in the arraylist
animals.add("Cat");
animals.add("Dog");
UNIT -3
animals.add("Cow");
System.out.println("ArrayList: " + animals);
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");
animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
UNIT -3
Output
Vector: [Dog, Horse, Cat]
New Vector: [Crocodile, Dog, Horse, Cat]
Access Vector Elements
• get(index) - returns an element specified by the index
• iterator() - returns an iterator object to sequentially access vector elements
For example,
import java.util.Iterator;
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);
// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Output
Element at index 2: Cat
Vector: Dog, Horse, Cat,
UNIT -3
// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);
// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output
Initial Vector: [Dog, Horse, Cat]
Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []
UNIT -3
Inheritance
Inheritance is a mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class.
Inheritance creates a new class from an existing class. Any new class that we create from an existing
class is called a derived class, and an existing class is called a base class.
Concept and Types of inheritance
The inheritance relationship enables a derived class to inherit features from its base class. A derived
class can add new features of its own. Therefore rather than creating completely new classes from
scratch, we can take advantage of inheritance and reduce software complexity.
• Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class that inherits the other class. It is also called a
derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism that 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.
Types of inheritance :
• Single Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
Syntax
UNIT -3
class XYZ extends ABC
{
// block of code
}
1. Single Inheritance
It is the inheritance hierarchy wherein one derived class inherits from one base class.
Ex :
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}
Output :
I am green!
I am a Bird
2. Multiple Inheritance
UNIT -3
It is the inheritance hierarchy wherein one derived class inherits from multiple base classes.
Example :
class A {
void testMethod() {
System.out.println("I am from class A");
}
}
class B {
void testMethod() {
System.out.println("I am from class B");
}
}
// Not possible to inherit classes this way, But for understanding, let us suppose
class C extends A, B {
void newMethod() {
System.out.println("I am from subclass");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
obj.testMethod();
// Ambiguity here as it's present in both A and B class
}
}
3. Hierarchical Inheritance
It is the inheritance hierarchy wherein multiple derived classes inherit from one base class.
class Bird {
UNIT -3
void fly() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
System.out.println("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.whatColourAmI();
par.fly();
4. Multilevel Inheritance
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
System.out.println("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
obj.whatCanISing();
obj.whatColourAmI();
obj.fly();
}
}
Output :
UNIT -3
I can sing Opera!
I am green!
I am a Bird
5. Hybrid Inheritance
It is the inheritance hierarchy that reflects any legal combination of the other four types of
inheritance
Dynamic Method Dispatch in Java
Dynamic Method Dispatch in Java is the process by which a call to an overridden method is
resolved at runtime (during the code execution). The concept of method overriding is the way to
attain runtime polymorphism in Java. During the code execution, JVM decides which
implementation of the same method should be called.
What is Runtime Polymorphism in Java?
Dynamic Method Dispatch is another name for Runtime polymorphism in Java which originates
with the concept of method overriding. In this case, the call to an overridden method will be
resolved at the time of code execution (runtime) rather than the compile time.
The basis of dynamic method dispatch in Java starts with Inheritance where two or more classes
exhibit a parent-child relationship. Now, there might be several versions of the same method in the
parent as well as child classes or you can also call them superclass and subclasses.
It seems puzzling as to which version of the same method will be called. However, Java Virtual
Machine (JVM) easily perceives the same during runtime based on the type of object being
referred to.
In Java, the object creation occurs in part 2 with the new operator assigned to any class which
denotes the type of object that will be created, and part 1 represents the reference variable. In the
figure given above, the object created will be an instance of class A.
But remember that runtime polymorphism depends on the type of object being created (as in part 2)
and not the reference variable (part 1).
UNIT -3
When different classes that follow inheritance have the same method with the same name,
parameters, and/or return type, it is known as method overriding.
Here, the reference variable is referring to the object of class B. The reference variable belongs to
the superclass or parent class while the object is made up of the subclass or child class. It is also
known as upcasting.
The subclasses exhibit an IS-A relationship with the parent class. For example, there can be a class
MobileOS. Since both Android as well as iOS are mobile operating systems, they are the subclasses
of MobileOS. So in terms of the IS-A relationship, we can say that Android "IS A" MobileOS and
iOS "IS A" MobileOS.
The concept of upcasting can be seen in this example. Whether we create the object
of Android or iOS, the reference variable is of the superclass in both cases, i.e., MobileOS.
Method Overriding
As mentioned earlier, when you can find the same method with the same signature (method name,
parameters, and return type) in inherited classes, it leads to method overriding. The
implementation of the class, i.e., the body of the class might differ in the overridden methods.
Therefore, the inherited classes having the same method with varied implementations make up an
example of runtime polymorphism.
Advantages
• Runtime polymorphism in Java allows the superclass to define as well as share its own
method and also allows the sub-classes to define their own implementation.
• The subclasses have the privilege to use the same method as their parent or define their
specific implementation for the same method wherever necessary. Therefore, in one way, it
supports code reusability when using the same method and implementation.
• It allows method overriding which is the basis for runtime polymorphism in Java.
UNIT -3
Example of Java Runtime Polymorphism
Here, we'll consider the same example that has been described above.
import java.io.*;
//Creating a parent class
class MobileOS
//virtual method
void display()
{
System.out.println("We are talking about mobile operating systems.");
}
}
//Main class
class Main {
//calling main method
public static void main (String[] args) {
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.
o Java Interface also represents the IS-A relationship.
o It cannot be instantiated just like the abstract class.
o Since Java 8, we can have default and static methods in an interface.
o 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:
interface <interface_name>{
// Interface 2
interface Mammal {
void walk(); // Abstract method
}
UNIT -3