Unit 3 Notes
Unit 3 Notes
Syllabus
Example: If you need to store the marks of five students, you can use an array instead of
five separate variables.
Examples:
int[] numbers = {10, 20, 30, 40, 50}; // Array initialized with values
Unit : 3 Page : 3. 1
int[] numbers;
numbers = new int[]{1, 2, 3, 4, 5}; // Initializing values separately
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Output:
Example:
If a deep copy (an actual copy of contents) is required, you can manually copy elements or
use the Arrays.copyOf() method.
Unit : 3 Page : 3. 3
Example of Deep Copy:
Output:
10 20 30 40 50
For dynamic resizing with more flexibility, consider using ArrayList instead of arrays.
8. Sorting of Arrays
The Arrays class in Java provides a convenient sort method to arrange array elements in
ascending order.
Unit : 3 Page : 3. 4
Example Program: Sorting an Array
import java.util.Arrays;
Output:
import java.util.Arrays;
if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
Output:
Unit : 3 Page : 3. 5
Element found at index: 2
Example of Arrays.fill :
Compile-Time Initialization:
The array is initialized at the time of declaration, with predefined rows and columns.
Run-Time Initialization:
The array is created with specified rows and columns, and values are assigned during
execution.
Example:
Unit : 3 Page : 3. 6
public class Main
{
public static void main(String[] args)
{
// Compile-time initialization
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Run-time initialization
int[][] table = new int[2][3];
table[0][0] = 10;
table[0][1] = 20;
table[0][2] = 30;
table[1][0] = 40;
table[1][1] = 50;
table[1][2] = 60;
// Iteration
System.out.println("Elements in matrix:");
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Elements in table:");
for (int i = 0; i < table.length; i++)
{
for (int j = 0; j < table[i].length; j++)
{
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
Explanation:
Unit : 3 Page : 3. 7
Iteration: Nested for loops are used to iterate over rows and columns.
Compile-Time Initialization:
Run-Time Initialization:
The array is defined with specific dimensions, and values are assigned later.
Example:
// Run-time initialization
int[][][] box = new int[2][2][3];
box[0][0][0] = 13;
box[0][0][1] = 14;
box[0][0][2] = 15;
box[0][1][0] = 16;
box[0][1][1] = 17;
box[0][1][2] = 18;
box[1][0][0] = 19;
box[1][0][1] = 20;
Unit : 3 Page : 3. 8
box[1][0][2] = 21;
box[1][1][0] = 22;
box[1][1][1] = 23;
box[1][1][2] = 24;
// Iteration
System.out.println("Elements in cube:");
for (int i = 0; i < cube.length; i++)
{
for (int j = 0; j < cube[i].length; j++)
{
for (int k = 0; k < cube[i][j].length; k++)
{
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
System.out.println("Elements in box:");
for (int i = 0; i < box.length; i++)
{
for (int j = 0; j < box[i].length; j++)
{
for (int k = 0; k < box[i][j].length; k++)
{
System.out.print(box[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Explanation:
Program:
Expected Output:
Bubble Sort repeatedly steps through the array, compares adjacent elements, and
swaps them if they are in the wrong order.
This process continues until the entire array is sorted.
Program:
Unit : 3 Page : 3. 11
public class BubbleSort
{
public static void main(String[] args)
{
int[] arr = {5, 2, 9, 1, 5, 6}; // Array to be sorted
int n = arr.length;
The outer loop iterates through the array, with each pass moving the largest unsorted
element to its correct position.
The inner loop compares adjacent elements and swaps them if they are in the wrong
order.
Unit : 3 Page : 3. 12
arr[j + 1] = temp;
}
}
}
Expected Output:
Sorted Array:
1 2 5 5 6 9
This Bubble Sort program iterates through the array, performing swaps to arrange the
numbers in ascending order. Each pass ensures that the largest unsorted element "bubbles
up" to its correct position.
Unit : 3 Page : 3. 13
Encapsulation
Encapsulation restricts access to certain details of an object, allowing only necessary parts
to be exposed. This is usually achieved by setting fields as private and providing public
getter and setter methods to access or modify the data.
class Person
{
private String name; // private variable for encapsulation
// Setter method
public void setName(String name)
{
this.name = name;
}
// Getter method
public String getName()
{
return name;
}
}
Explanation:
Abstraction
Abstraction focuses on exposing only the essential features and hiding the implementation
details. This is usually achieved using abstract classes or interfaces in Java.
Unit : 3 Page : 3. 14
Example Program for Abstraction:
// Regular method
public void eat()
{
System.out.println("Animal is eating");
}
}
Explanation:
The Animal class is abstract, containing an abstract method sound and a regular
method eat .
The Dog class extends Animal and provides an implementation for sound .
When we create an instance of Dog , we can call both sound (abstract) and eat
(regular) methods.
Polymorphism
Polymorphism allows methods to perform different tasks based on the object that invokes
them. There are two main types in Java:
Unit : 3 Page : 3. 15
1. Compile-time Polymorphism (Method Overloading)
2. Run-time Polymorphism (Method Overriding)
Compile-time Polymorphism:
Method overloading allows multiple methods with the same name but different parameters in
the same class.
class Calculator
{
public int add(int a, int b)
{
return a + b;
}
Explanation:
The Calculator class has two add methods with different parameters, demonstrating
method overloading.
Run-time Polymorphism:
class Animal
{
public void sound()
{
System.out.println("Animal sound");
}
Unit : 3 Page : 3. 16
}
Explanation:
Inheritance in Java
Inheritance is one of the key features of Object-Oriented Programming (OOP) that allows
one class to inherit properties (Variables) and behaviors (methods) from another class. It
promotes code reusability and establishes a relationship between classes. The base class is
also called as parent class or super class. The derived class is also called as Sub class or
Child class.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
Unit : 3 Page : 3. 17
1. Single Inheritance
In single inheritance, a class inherits from only one superclass.
Example 1:
class Animal
{
String name;
void eat()
{
System.out.println(name + " is eating");
}
}
class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
d.name = "Buddy";
d.eat(); // Inherited from Animal
d.bark(); // Method of Dog
}
}
Example 2:
class Vehicle
{
int speed;
void start()
{
System.out.println("Vehicle started");
}
}
Unit : 3 Page : 3. 18
{
void drive()
{
System.out.println("Car is driving at " + speed + " km/h");
}
}
class Test
{
public static void main(String[] args)
{
Car c = new Car();
c.speed = 60;
c.start(); // Inherited from Vehicle
c.drive(); // Method of Car
}
}
2. Multilevel Inheritance
In multilevel inheritance, a class is derived from a class that is already derived from another
class, creating a chain.
Example 1:
class Animal
{
void sleep()
{
System.out.println("Animal is sleeping");
}
}
Unit : 3 Page : 3. 19
}
}
class Test
{
public static void main(String[] args)
{
Puppy p = new Puppy();
p.sleep(); // Inherited from Animal
p.bark(); // Inherited from Dog
p.play(); // Method of Puppy
}
}
Example 2:
class Person
{
String name;
void walk()
{
System.out.println(name + " is walking");
}
}
void work()
{
System.out.println(name + " is working with ID: " + empId);
}
}
class Test
{
public static void main(String[] args)
{
Manager m = new Manager();
Unit : 3 Page : 3. 20
m.name = "John";
m.empId = 1234;
m.walk(); // Inherited from Person
m.work(); // Inherited from Employee
m.manage(); // Method of Manager
}
}
3. Hierarchical Inheritance
In hierarchical inheritance, more than one class inherits from a single superclass.
Example 1:
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}
class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Method of Dog
Unit : 3 Page : 3. 21
Cat c = new Cat();
c.eat(); // Inherited from Animal
c.meow(); // Method of Cat
}
}
Example 2:
class Shape
{
void draw()
{
System.out.println("Drawing shape");
}
}
class Test
{
public static void main(String[] args)
{
Circle cir = new Circle();
cir.draw(); // Inherited from Shape
cir.area(); // Method of Circle
Unit : 3 Page : 3. 22
Hybrid Inheritance (Combination of Any 2 Inheritance)
We can simulate hybrid inheritance by combining multiple types of inheritance:
/
BC
/
D
Example:
class A
{
void methodA()
{
System.out.println("Method A from Class A");
}
}
class B extends A
{
void methodB()
{
System.out.println("Method B from Class B");
}
}
class C extends A
{
void methodC()
{
System.out.println("Method C from Class C");
}
}
class D extends B
{
void methodD()
{
System.out.println("Method D from Class D");
}
Unit : 3 Page : 3. 23
}
class Test
{
public static void main(String[] args)
{
D objD = new D();
objD.methodA(); // Inherited from Class A (Single Inheritance)
objD.methodB(); // Inherited from Class B (Multilevel Inheritance)
objD.methodD(); // Method of Class D
Explanation:
Class A is the parent class and contains methodA() .
Class B extends Class A (Single Inheritance) and adds methodB() .
Class C also extends Class A (Hierarchical Inheritance) and adds methodC() .
Class D extends Class B (Multilevel Inheritance) and adds methodD() .
In this example, Class D inherits properties from Class B (which in turn inherits from Class
A), thus demonstrating multilevel inheritance. Class C independently inherits from Class A,
showcasing hierarchical inheritance.
By restricting multiple inheritance, Java ensures that the code remains clear and easy to ma
intain.
Interfaces in Java, however, can be used to achieve a form of multiple inheritance. So while t
he
language itself doesn’t allow it for classes, you still have the flexibility to use multiple interfac
es.
Unit : 3 Page : 3. 24
super Keyword
The super keyword in Java is used within a subclass to refer to members (variables or
methods) of its superclass. It helps:
class Animal
{
String color = "Brown";
Unit : 3 Page : 3. 25
Dog dog = new Dog();
dog.displayColors(); // Display colors from both Dog and Animal
classes
dog.sound(); // Calls overridden method in Dog
}
}
Explanation:
Expected Output:
Method Overriding
Method overriding in Java allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. Overriding helps in runtime polymorphism,
enabling behavior specific to the subclass when a superclass reference points to a subclass
object.
The method in the subclass must have the same name, return type, and parameters as
in the superclass.
Only instance methods (non-static) can be overridden.
Access modifiers can be more permissive in the subclass but not more restrictive.
class Animal
{
public void sound()
{
System.out.println("Animal makes a sound");
}
}
Unit : 3 Page : 3. 26
class Cat extends Animal
{
@Override
public void sound() // Overriding the sound method
{
System.out.println("Cat meows");
}
}
Explanation:
The Cat class overrides the sound method from Animal to provide a specific
implementation.
When myCat.sound() is called, it executes the overridden method in Cat ,
demonstrating polymorphism.
Expected Output:
Here's an overview of abstract classes in Java, covering what they are, why they're used,
and how to implement them with examples.
Unit : 3 Page : 3. 27
An abstract class in Java is a class that cannot be instantiated directly. It is defined with the
abstract keyword and is meant to be extended by other classes that provide specific
implementations of its methods. Abstract classes can contain both abstract methods
(without a body) and concrete methods (with an implementation).
The main purpose of an abstract class is to serve as a base class from which other classes
inherit. It provides a blueprint for subclasses, defining common attributes and behaviors that
subclasses can either use as-is or override to customize.
Syntax:
Example:
In this example, Shape is an abstract class with an abstract method draw() . Any class that
extends Shape must provide an implementation for the draw() method.
For instance, if you have different shapes (Circle, Rectangle) that share properties like
color and behavior like draw() , you can define these in an abstract class.
Unit : 3 Page : 3. 28
Example of Abstract Class with Abstract and Concrete Methods:
// Concrete method
public void eat() {
System.out.println("This animal eats food.");
}
}
Output:
Dog barks.
This animal eats food.
In this example:
Unit : 3 Page : 3. 29
Can contain abstract methods: Abstract classes can have abstract methods, which
subclasses must implement.
Can contain concrete methods: Unlike interfaces, abstract classes can also contain
methods with full implementations.
Can have constructors: Abstract classes can have constructors, which are used when
a subclass is instantiated.
Can have member variables: Abstract classes can declare fields (variables) that can
be inherited by subclasses.
Summary
An abstract class serves as a template for other classes, allowing subclasses to
inherit common functionality while defining their own specific behaviors.
Abstract methods in an abstract class are meant to be implemented by subclasses,
whereas concrete methods can be used as-is.
Abstract classes provide a way to group related classes, sharing common code while
enforcing certain behaviors across subclasses.
This overview should help you understand the basics of abstract classes in Java. Let me
know if you’d like more examples or details on this topic!
Interface in Java
1. Introduction to Interfaces
An interface in Java is a reference type, similar to a class, that contains only abstract
methods (methods without bodies) by default. Interfaces define a contract that classes can
implement, ensuring that they provide specific methods. This helps in achieving abstraction
and multiple inheritance in Java, as classes can implement multiple interfaces but can only
inherit from a single class.
Syntax:
interface InterfaceName
{
// abstract methods
}
Example:
interface Animal
{
Unit : 3 Page : 3. 30
void eat();
void sleep();
}
In this example, any class that implements the Animal interface must define eat and
sleep methods.
2. Declaration of Interface
Interfaces are declared using the interface keyword, and by default, all methods in an
interface are public and abstract. Interfaces can also contain constants (final variables).
interface Vehicle
{
int MAX_SPEED = 120; // Constant
void start(); // Abstract method
void stop();
}
3. Implementation of Interface
A class implements an interface using the implements keyword. The class must provide
definitions for all the abstract methods declared in the interface.
interface Vehicle
{
void start();
void stop();
}
Unit : 3 Page : 3. 31
public void start()
{
System.out.println("Car is starting.");
}
Output:
Car is starting.
Car is stopping.
Here, the Car class provides definitions for start() and stop() methods from the
Vehicle interface.
4. Multiple Interfaces
Java does not support multiple inheritance with classes, but a class can implement multiple
interfaces. This allows a class to inherit abstract methods from multiple sources.
interface Drivable
{
void drive();
}
interface Flyable
{
void fly();
}
Output:
In this example, FlyingCar implements both Drivable and Flyable interfaces, showing
how a class can combine multiple behaviors.
5. Nested Interfaces
A nested interface is an interface declared within another interface or class. It can be
public, private, or protected. Nested interfaces are useful for grouping related interfaces
together and for inner classes.
class OuterClass
{
interface InnerInterface
{
void display();
}
}
Output:
6. Inheritance of Interfaces
Just like classes, interfaces can inherit other interfaces using the extends keyword. An
interface can extend multiple other interfaces, which allows a combination of multiple
behaviors.
interface Printable
{
void print();
}
interface Scannable
{
void scan();
}
Output:
Printing document.
Scanning document.
Copying document.
Here, MultifunctionDevice inherits from both Printable and Scannable , and Machine
implements all the methods.
Unit : 3 Page : 3. 35
interface InterfaceName
{
default void methodName()
{
// default implementation
}
}
Example:
interface Camera
{
void takePhoto();
Output:
Taking photo.
Recording video in HD.
In this example, recordVideo is a default method in the Camera interface. The Smartphone
class does not override it, so the default implementation is used.
Unit : 3 Page : 3. 36
Unit : 3 Page : 3. 37