UNIT – 4
Introduction to Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
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,
and 2nd element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces.
We can store primitive values or objects in an array in Java. Like C/C++, we can also
create single dimensional or multi-dimensional arrays in Java. Moreover, Java provides
the feature of anonymous arrays which is not available in C/C++.
Advantages -
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages -
Size Limit: We can store only the 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 which
grows automatically.
Example:
Types of Array in java: There are two types of array.
1. Single Dimensional Array
2. Multi-Dimensional Array
1|Page By [Link] (Technical Trainer)
Single Dimensional Array in Java:
Single Dimensional Array in Java is basically a linear array that allows its user to store
multiple values of the same data type.
It's a collection of data that stores elements of the same type in a sequentially allocated
space in memory.
Syntax to Declare Single Dimensional Array in Java:
//declaration
datatype[] var;
datatype []var;
datatype var[];
//instantiation
var = new datatype[size];
//declaration, instantiation and initialization
datatype var[] = {value1,value2,value3};
Example - Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
//illustrate how to declare, instantiate, initialize and traverse the array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50; //traversing array
for(int i=0;i<[Link];i++) //length is the property of array
[Link](a[i]);
}
}
Multi-Dimensional Array in Java:
To store tabular data we use multidimensional Array. In such case, data is stored in row
and column based index (also known as matrix form).
Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the
row number and ‘j’ is the column number.
1|Page By [Link] (Technical Trainer)
Syntax to Declare Multidimensional Array in Java
//declaration
datatype[][] var;
datatype [][] var;
datatype var[][];
datatype []var[];
//instantiation
var = new datatype[rowsize][columnsize];
//declaration, instantiation and initialization
datatype var[] = { value1, value2, value3 };
Example - Program to read and print 2-D Array Elements.
class Testarray1{
public static void main(String args[]) {
int arr[][]={{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
2|Page By [Link] (Technical Trainer)
Declaration and Initialization of Arrays
- Declaration: Declaring an array means specifying the data type of its elements and
giving it a name.
int[] myArray; // Declares an array of integers
- Initialization: Initializing an array means allocating memory for it and optionally
assigning values to its elements.
myArray = new int[5]; // Initializes the array to hold 5 integers
- Declaration and initialization together
int[] myArray = {10, 20, 30, 40, 50}; // An array with 5 elements
- You can also initialize an array by specifying the size:
String[] names = new String[3]; // An array of 3 Strings
Storage of Array in Computer Memory
Arrays in Java are stored in contiguous memory locations. This means that the elements
of the array are stored one after another in the memory.
The address of the first element is known as the base address. The memory location of
any other element in the array can be calculated using the base address and the size of
the data type.
For example, if `int[] myArray = new int[5];` is stored starting at memory location
`1000`, and each integer takes 4 bytes of memory, the elements will be stored as follows:
▪ `myArray[0]` at `100`
▪ `myArray[1]` at `104`
▪ `myArray[2]` at `108`, and so on.
3|Page By [Link] (Technical Trainer)
Accessing Elements of Arrays
Array elements are accessed using their index, which starts from `0` and goes up to
`len-1`.
You can access or modify any element in the array by specifying its index.
Example:
public class ArrayExample {
public static void main(String[] args) {
// Array Declaration and Initialization
int[] myArray = {10, 20, 30, 40, 50};
// Accessing elements
[Link]("Element at index 0: " + myArray[0]); // Outputs: 10
[Link]("Element at index 4: " + myArray[4]); // Outputs: 50
// Modifying elements
myArray[2] = 35; // Changes the third element to 35
// Accessing and printing the modified element
[Link]("Modified element at index 2: " + myArray[2]); // Outputs: 35
}}
Operations on Array Elements:
You can perform various operations on array elements, such as addition, subtraction,
multiplication, etc.
Example:
public class ArrayOperations {
public static void main(String[] args) {
// Array Declaration and Initialization
int[] numbers = {5, 10, 15, 20, 25};
4|Page By [Link] (Technical Trainer)
// Adding elements
int sum = numbers[0] + numbers[1];
[Link]("Sum: " + sum); // Outputs: 15
// Multiplying elements
numbers[2] *= 2; // Multiplies the third element by 2
[Link]("New value at index 2: " + numbers[2]); // Outputs: 30
} }
Assigning Array to another Array
In Java, when you assign one array to another, you're not copying the elements, but
rather the reference to the original array.
This means that changes to one array will reflect in the other.
Example:
public class ArrayReferenceExample {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3}; // Initialize an array
// Assign the original array reference to newArray
int[] newArray = originalArray;
// Modify the first element of newArray
newArray[0] = 10; // This will also change the first element of originalArray
// Print the first element of originalArray
[Link]("First element of originalArray: " + originalArray[0]);
// Outputs: 10
} }
Dynamic Change of Array Size
Java arrays are of fixed size, meaning that once an array is created, its size cannot be
changed.
However, you can create a new array with a different size and copy elements from the
original array to the new one.
5|Page By [Link] (Technical Trainer)
Example:
public class ArrayCopyExample {
public static void main(String[] args) {
int[] oldArray = {1, 2, 3}; // Initialize the original array
int[] newArray = new int[5]; // Create a new array with a larger size
// Copy elements from oldArray to newArray
[Link](oldArray, 0, newArray, 0, [Link]);
[Link]("newArray: "); // Print the elements of the newArray
for (int i : newArray) {
[Link](i + " "); // Outputs: 1 2 3 0 0
} } }
Sorting of Arrays
Java provides a built-in method `[Link]()` to sort elements in an array. This method
sorts the array in ascending order.
Example:
import [Link];
public class ArraySortExample {
public static void main(String[] args) {
// Initialize the array with unsorted elements
int[] numbers = {5, 2, 8, 7, 1};
// Sort the array
[Link](numbers);
// Print the sorted array
[Link]("Sorted Array: " + [Link](numbers));
// Outputs: [1, 2, 5, 7, 8]
} }
6|Page By [Link] (Technical Trainer)
Search for Values in Arrays
The `[Link]()` method is used to search for a specific value in a sorted
array. It returns the index of the value if found; otherwise, it returns a negative value.
Example:
import [Link];
public class BinarySearchExample {
public static void main(String[] args) {
// Initialize a sorted array
int[] numbers = {1, 2, 5, 7, 8};
// Perform binary search for the value 7
int index = [Link](numbers, 7);
// Print the index of the value 7
[Link]("Index of 7: " + index); // Outputs: Index of 7: 3
}
}
Class Arrays
The `[Link]` class provides static methods for manipulating arrays, including
sorting, searching, copying, comparing, and more.
Example:
import [Link];
public class ArrayCopyExample {
public static void main(String[] args) {
// Initialize an array
int[] numbers = {1, 2, 3};
// Copy the array and extend the length to 5
int[] copy = [Link](numbers, 5);
// Print the new array
[Link]([Link](copy)); // Outputs: [1, 2, 3, 0, 0]
}
}
7|Page By [Link] (Technical Trainer)
Three-dimensional Arrays
A three-dimensional array is an array of two-dimensional arrays, which can be
visualized as a cube or a series of tables stacked on top of each other.
Example: simple Java program demonstrating how to use a three-dimensional array,
assign values, and print them:
public class ThreeDArrayExample {
public static void main(String[] args) {
// Create a 2x2x2 3D array
int[][][] threeDArray = new int[2][2][2];
// Assign values to the array
threeDArray[0][0][0] = 1;
threeDArray[0][0][1] = 2;
threeDArray[0][1][0] = 3;
threeDArray[0][1][1] = 4;
threeDArray[1][0][0] = 5;
threeDArray[1][0][1] = 6;
threeDArray[1][1][0] = 7;
threeDArray[1][1][1] = 8;
// Print all elements using nested loops
for (int i = 0; i < 2; i++) {
[Link]("Layer " + i + ":");
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
[Link](threeDArray[i][j][k] + " ");
}
[Link]();
}
[Link]();
}
}
}
Output:
Layer 0:
12
34
Layer 1:
56
78
8|Page By [Link] (Technical Trainer)
Assignment Questions: Arrays – Industry-Relevant Practice
Question 1: One-Dimensional Array – Sales Report Tracker
A company tracks daily sales for a week.
Write a Java program that:
Takes sales for 7 days using a 1D array
Displays the total and average sales
Question 2: Memory Structure – Find the Address Offset (Conceptual)
Assume a 1D array int[] arr = new int[5]; is stored in memory.
If the base address of arr[0] is 1000 and each integer takes 4 bytes, calculate the memory
address of arr[4].
Question 3: Two-Dimensional Array – Employee Work Hours
A company records employee work hours over 5 days for 3 employees.
Write a Java program to:
Accept input into a 2D array [3][5]
Display the total hours worked by each employee
Question 4: Type of Arrays – 3D Array for Product Stock in Warehouses
A company has 2 warehouses. Each warehouse stores 3 products, and each product has 4
quantity records.
Use a 3D array to represent this data and print the total stock per warehouse.
Question 5: Array Concept – Frequency of Elements
Write a Java program to count and display the frequency of each element in an integer array.
Use appropriate data structures for optimization.
9|Page By [Link] (Technical Trainer)
UNIT -5
Classes and Objects: Introduction
Classes and objects are fundamental concepts in object-oriented programming (OOP). A
class is a blueprint or template for creating objects, which are instances of a class. Each
object can have attributes (fields) and behaviors (methods) defined by its class.
1. Classes:
A class in Java is like a blueprint or template for creating objects.
It defines a datatype by bundling data and methods that work on the data into
one single unit.
In simpler terms, a class is a user-defined blueprint or prototype from which
objects are created.
Example:
public class Car {
String color;
String model;
int speed;
void accelerate() {
speed += 10;
}
void brake() {
speed -= 10;
}
}
In the example above, Car is a class. It has fields like color, model, and speed,
and methods like accelerate() and brake().
10 | P a g e By [Link] (Technical Trainer)
2. Objects:
An object is an instance of a class.
When a class is defined, no memory is allocated until an object of that class is
created.
Objects are the actual entities that have state and behavior defined by the class.
Example:
Car myCar = new Car();
[Link] = "Red";
[Link] = "Tesla Model S";
[Link]();
Here, myCar is an object of the Car class. It has specific values for color and model,
and the accelerate() method increases its speed.
An object has three characteristics:
- State: represents the data (value) of an object.
- Behavior: represents the behavior (functionality) of an object such as
deposit,withdraw, etc.
- Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.
11 | P a g e By [Link] (Technical Trainer)
Class Declaration and Modifiers:
In Java, a class is declared using the class keyword, followed by the class name. Modifiers
like public, private, or final can be used to control access and behavior.
1. Class Declaration:
A class in Java is declared using the class keyword.
The followed by the class name and a pair of curly braces {} containing the class
body.
Syntax:
Example:
In the above example, student is a class haveing regno, fees and name as data
members. The getdata() and printdata() are the members functions of the class. The
obj1 and obj2 are objects of class student.
2. Modifiers:
There are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
We can change the access level of fields, constructors, methods, and class by
applying the access modifier on it.
12 | P a g e By [Link] (Technical Trainer)
i. Access Modifiers:
a) public: The class is accessible from any other class.
b) private: The class is accessible only within the class it is defined.
c) protected: The class is accessible within the same package and subclasses.
d) default (no modifier): The class is accessible only within its own package.
ii. Non-Access Modifiers:
a) final: The class cannot be subclassed (i.e., no other class can inherit from it).
b) abstract: The class cannot be instantiated; it can only be subclassed.
Class Members:
Class members include fields (variables) and methods (functions). These members
define the properties and behaviors of the objects created from the class.
Fields are variables that hold data for objects. They represent the state or attributes
of an object.
Example:
public class Car {
String color;
String model;
int speed;
}
13 | P a g e By [Link] (Technical Trainer)
Here, color, model, and speed are fields of the Car class.
Methods define the behavior of objects. They are functions defined within a class
that operate on objects of that class.
Example:
public class Car {
void accelerate() {
speed += 10;
}
void brake() {
speed -= 10;
}
}
Here, accelerate() and brake() are methods of the Car class.
Declaration of Class Objects:
Objects are instances of a class.
They are created using the ‘new’ keyword followed by the class constructor.
Syntax:
ClassName objectName = new ClassName();
Example:
Car myCar = new Car();
Here, myCar is an object of the Car class.
Assigning One Object to Another:
When you assign one object to another, you are copying the reference to the object,
not the object itself.
Both references will point to the same memory location.
Syntax:
ClassName obj2 = obj1; // Now obj2 refers to the same object as obj1
Example:
Car car1 = new Car();
Car car2 = car1; // car2 now refers to the same object as car1
14 | P a g e By [Link] (Technical Trainer)
Access Control for Class Members:
Access control is used to restrict access to the members of a class.
It is defined using access modifiers like private, public, protected, and default.
Example:
public class Car {
private String color; // Private field, accessible only within the class
public String getColor() {
return color; // Public method, accessible from outside the class
}
public void setColor(String color) {
[Link] = color;
}
}
Accessing Private Members of Class:
Private members can only be accessed within the class they are declared in.
To allow controlled access from outside, getter and setter methods are used.
Example:
public class Car {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
[Link] = color;
}
}
Here, the color field is private, but you can access it using the public getColor() and
setColor() methods.
15 | P a g e By [Link] (Technical Trainer)
Constructor Methods for Class:
Constructors are special methods used to initialize objects.
They have the same name as the class and do not have a return type.
Example:
public class Car {
String color;
public Car(String color) {
[Link] = color; // Constructor initializing the color field
}
}
Overloaded Constructor Methods:
Constructor overloading allows a class to have more than one constructor, each with
a different parameter list.
This is known as constructor overloading.
Example:
public class Car {
String color;
String model;
public Car(String color) { // Constructor 1
[Link] = color;
}
public Car(String color, String model) { // Constructor 2
[Link] = color;
[Link] = model;
}
}
Nested Classes:
A nested class is a class defined within another class.
It can be used to logically group classes that are only used in one place, increasing
encapsulation.
This is known as a nested class.
16 | P a g e By [Link] (Technical Trainer)
Example:
public class OuterClass {
private int outerField = 10;
class InnerClass {
void display() {
[Link]("Outer field: " + outerField);
}
}
}
Here, InnerClass is a nested class within OuterClass.
Final Class and Methods
A final class cannot be subclassed (no inheritance), and a final method cannot be
overridden by subclasses.
Example:
public final class FinalClass {
public final void finalMethod() {
[Link]("This method cannot be overridden");
}
}
Passing Arguments by Value and by Reference:
Primitive types: When passing primitive data types (like int, double, etc.) to methods, the
method receives a copy of the value. Any changes made to the parameter inside the method
do not affect the original value.
public void changeValue(int value) {
value = 100; // Changes the local copy, not the original value
}
Object references: When passing objects to methods, the method receives a copy of the
reference to the object. Changes made to the object inside the method will affect the original
object.
public void changeObject(Car car) {
[Link] = "Red"; // This change affects the original object
}
17 | P a g e By [Link] (Technical Trainer)
Keyword this:
The ‘this’ keyword is a reference to the current object - the object whose method or
constructor is being invoked.
It is often used to distinguish between class fields and parameters with the same
name.
Example:
public class Car {
String color;
public Car(String color) {
[Link] = color; // '[Link]' refers to the class field, 'color' refers
to the parameter
}
}
Method in Java:
A method is a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation.
It is used to achieve the reusability of code. We write a method once and use it many
times.
We do not require to write code again and again. It also provides the easy modification
and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it. The most important method in
Java is the main() method.
Types of Method - There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.
It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point.
User defined Method:
Once we have defined a method, it should be called. The calling of a method in a
program is simple.
When we call or invoke a user-defined method, the program control transfer to the
called method.
18 | P a g e By [Link] (Technical Trainer)
Example:
import [Link].*;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from user
int n=[Link](); //method calling
checkEvenOdd(n);
}
public static void checkEvenOdd(int n)
{
//method body
if(n%2==0)
[Link](n+" is even");
else
[Link](n+" is odd");
}
}
Parameter Passing/Call by value
If we call a method passing a value, it is known as call by value.
The changes being done in the called method, is not affected in the calling method.
Example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
[Link]("before change "+[Link]);
[Link](500);
[Link]("after change "+[Link]);
}
}
19 | P a g e By [Link] (Technical Trainer)
Recursion in Java:
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
It makes the code compact but complex to understand.
Java Recursion Example: Factorial Number
import [Link].*;
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
int n=[Link]();
[Link]("Factorial=”+factorial(n));
} }
Polymorphism:
Implementing the same thing in different ways. “Poly” means “many”, and “morph”
means “type”. So the term polymorphism indicates the same thing of different types.
Types of polymorphism:
1) compile time polymorphism
- Method overloading
- Static binding
2) Runtime polymorphism
- Method overriding
- Dynamic binding
20 | P a g e By [Link] (Technical Trainer)
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading - Method overloading increases the readability of the
program.
Different ways to overload the method in Method Overloading:
// Java program to demonstrate working of method overloading in Java
21 | P a g e By [Link] (Technical Trainer)
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Methods Overriding in Java:
Method Overriding allows a subclass to provide a specific implementation of a method
that is already defined in its superclass.
The overridden method in the subclass should have the same name, return type, and
parameters as the method in the superclass.
Example:
class Animal {
public void sound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
22 | P a g e By [Link] (Technical Trainer)
@Override
public void sound() {
[Link]("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
[Link](); // Output: Animal makes a sound.
[Link](); // Output: Dog barks.
}
}
Here, the Dog class overrides the sound method of the Animal class to provide its
specific implementation.
Java constructor:
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the classis created.
At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
Rules for creating Java constructor: There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors: There are two types of constructors in Java -
1. Default constructor (no-arg constructor)
2. Parameterized constructor
23 | P a g e By [Link] (Technical Trainer)
Java Default Constructor:
• A constructor is called "Default Constructor" when it doesn't have any parameter.
• Syntax of default constructor: <class_name>(){}
• Example of default constructor - In this example, we are creating the no-arg constructor
in the Bike class. It will be invoked at the time of object creation.
//Java Program to create and call a default constructor
class Car { // Creating a default constructor
Car() {
[Link]("Car is created");
}
// Main method
public static void main(String args[]) {
// Calling a default constructor
Car b = new Car();
}
}
//Let us see another example of default constructor which displays the
default values
class Student3{
int id;
class Student3 {
// Instance variables
int id;
String name;
24 | P a g e By [Link] (Technical Trainer)
// Method to display the value of id and name
void display() {
[Link](id + " " + name);
}
// Main method
public static void main(String args[]) {
// Creating objects of Student3 class
Student3 s1 = new Student3();
Student3 s2 = new Student3();
// Displaying values of the objects
[Link](); //0 null
[Link](); //0 null
}
Java Parameterized Constructor:
A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Example of parameterized constructor - In this example, we have created the
constructor of Student class that have two parameters. We can have any number of
parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(123,"Sai");
Student4 s2 = new Student4(345,"Pradeep");
//calling method to display the values of object
[Link]();
25 | P a g e By [Link] (Technical Trainer)
[Link]();
}
}
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists.
They are arranged in a way that each constructor performs a different task. They are
Example of Constructor Overloading:
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i; name = n; age=a;
}
void display(){[Link](id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(123,"Armaan");
Student5 s2 = new Student5(345,"Pradeep",25);
[Link]();
[Link]();
}
}
Access Control/Modifiers in Java: There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
26 | P a g e By [Link] (Technical Trainer)
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Java static keyword:
The static keyword in Java is used for memory management mainly.
We can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable:
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college
name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable: It makes your program memory efficient (i.e., it saves
memory).
Example of static variable:
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="MIT";//static variable
//constructor
Student(int r, String n){
rollno = r; name = n;
}
//method to display the values
void display (){[Link](rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
27 | P a g e By [Link] (Technical Trainer)
public static void main(String args[]){
Student s1 = new Student(110,"Ravi");
Student s2 = new Student(222,"Mani");
//we can change the college of all objects by the single line of code
//[Link]="QIS";
[Link]();
[Link]();
}}
2) Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Example of static method:
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "QIS";
//static method to change the value of static variable
static void change(){
college = "MIT SCHOOL";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
28 | P a g e By [Link] (Technical Trainer)
//calling display method
[Link]();
[Link]();
[Link]();
}
}
Final Keyword in Java:
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will
be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //Compile time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class
2) Java final method
If you make any method as final, you cannot override it.
public final void display() {
[Link]("This is a final method");
}
29 | P a g e By [Link] (Technical Trainer)
3) Java final class
If you make any class as final, you cannot extend it.
public final class Vehicle {
// class body
}
Java Inner Classes (Nested Classes):
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax of Inner class
class Java_Outer_class{
//code class
Java_Inner_class{
//code
}
}
Advantage of Java inner classes:
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Example:
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1
obj=new TestMemberOuter1();
30 | P a g e By [Link] (Technical Trainer)
[Link] in=[Link] Inner();
[Link]();
}
}
Assignment Questions: Object-Oriented Programming in Java
Question 1: Class & Object – Student Grade Manager
Design a Student class with the following attributes: name, rollNumber, and marks.
Include:
A constructor to initialize these fields
A method to calculate grade based on marks (e.g., A/B/C)
In main, create multiple student objects and display their grades.
Question 2: Method Overloading & Constructors – Bank Account System
Create a BankAccount class that includes:
Overloaded constructors (one with no parameters, one with name & balance)
Overloaded methods deposit() for integer and double values
Demonstrate both constructor and method overloading through a menu-driven
program.
Question 3: Static & Final – Employee ID Generator
Create an Employee class with:
A static variable to generate a unique employee ID
A final variable for company name
Constructor to initialize name and assign an auto-generated ID
Print employee details with ID and company name.
Question 4: Access Control, Garbage Collection – Car Rental System
Create a Car class with private fields for model and price.
Include:
Getters and setters for accessing/modifying private fields
A method to print car details
Demonstrate garbage collection by setting object references to null and calling
[Link]().
Question 5: Nested Class & Recursion – Directory Structure Simulation
Create a Directory class that contains:
A nested File class with file name and size
A method to display the directory structure recursively
In main, create a directory and add multiple files using recursion to simulate
folders and subfolders.
31 | P a g e By [Link] (Technical Trainer)
UNIT – 6
Inheritance in Java:
Inheritance is an OOP (Object-Oriented Programming) concept where one class
(subclass or derived class) inherits the properties and behaviors (fields and methods) of
another class (superclass or base class).
It establishes an *is-a* relationship, making subclasses a specialized version of their
superclass.
Benefits of Inheritance -
- Code Reusability: Common code can be written in a base class and reused in
derived classes.
- Method Overriding: Subclasses can modify the behavior of methods defined in
the base class.
- Polymorphism: Allows methods to work differently based on the object being
called.
Process of Inheritance
The process of inheritance involves:
1. Defining a Superclass: A class that holds common properties and methods.
2. Defining a Subclass: A class that inherits from the superclass using the `extends`
keyword. It automatically inherits all non-private members of the superclass.
Example:
class Animal {
void eat() {
[Link]("Animal eats");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
32 | P a g e By [Link] (Technical Trainer)
}
public class TestInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Method from superclass
[Link](); // Method from subclass
}
}
Types of Inheritance in Java:
1. Single Inheritance:
• A subclass inherits from one superclass.
• This is the only type of class-based inheritance directly supported by Java.
Example:
class A { // Fields and methods }
class B extends A { // Additional Fields and methods }
33 | P a g e By [Link] (Technical Trainer)
2. Multilevel Inheritance:
• A class is derived from a class, which is also derived from another class, creating a
multilevel chain.
Example:
class A { // Fields and methods }
class B extends A { // Additional Fields and methods }
class C extends B { // Additional Fields and methods }
3. Hierarchical Inheritance:
• Multiple classes inherit from a single superclass.
Example:
class A { // Fields and methods }
class B extends A { // Additional Fields and methods }
class C extends A { // Additional Fields and methods }
4. Multiple Inheritance:
• Java does not support multiple inheritance with classes (i.e., a class cannot directly
inherit from multiple classes).
• However, it can be achieved through interfaces.
Example:
interface A { // Fields and methods }
interface B { // Additional Fields and methods }
class C implements A, B { // Additional Fields and methods }
• The Universal Superclass: `Object` Class
- Every class in Java is a direct or indirect subclass of the `Object` class.
- The `Object` class provides essential methods like `toString()`, `equals()`,
`hashCode()`, `clone()`, `finalize()`, `getClass()`, `notify()`, `notifyAll()`,
and `wait()`.
34 | P a g e By [Link] (Technical Trainer)
Example of `toString()` and `equals()`:
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
@Override
public String toString() {
return "Animal name: " + name;
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal("Dog");
[Link]([Link]()); // Outputs: Animal name: Dog
}
}
5. Inhibiting Inheritance Using `final` Keyword
• The `final` keyword is used to prevent inheritance.
• A class marked as `final` cannot be subclassed.
• Similarly, a method marked as `final` cannot be overridden.
Example:
final class Vehicle { }
// This will give a compile-time error
class Car extends Vehicle { }
class Bike {
final void run() {
[Link]("Running...");
}
}
class Honda extends Bike {
// This will give a compile-time error
void run() {
[Link]("Running safely...");
}
}
35 | P a g e By [Link] (Technical Trainer)
Access Control in Inheritance:
Access modifiers determine the accessibility of members (fields, methods) of a class:
- Private (`private`): Accessible only within the same class. Not inherited.
- Default (no modifier): Accessible within the same package. Inherited by
subclasses within the same package.
- Protected (`protected`): Accessible within the same package and by subclasses,
even if they are in different packages.
- Public (`public`): Accessible from any other class. Fully inherited.
Example of Single Inheritance:
class Parent {
private int privateVar = 10; // Not accessible in Child
int defaultVar = 20; // Accessible in Child if in the same package
protected int protectedVar = 30; // Accessible in Child
public int publicVar = 40; // Accessible in Child
}
class Child extends Parent {
void display() {
// [Link](privateVar); // Error: not accessible
[Link](defaultVar); // Accessible
[Link](protectedVar); // Accessible
[Link](publicVar); // Accessible
}
}
Example of Multilevel Inheritance:
class Animal {
void eat() {
[Link]("Animal eats");
}
}
class Mammal extends Animal {
void sleep() {
[Link]("Mammal sleeps");
}
}
36 | P a g e By [Link] (Technical Trainer)
class Dog extends Mammal {
void bark() {
[Link]("Dog barks");
}
}
public class TestMultilevelInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Method from Animal class
[Link](); // Method from Mammal class
[Link](); // Method from Dog class
}
}
Example of Hierarchical Inheritance:
// Superclass Animal
class Animal {
// Protected variable - accessible in subclasses and in the same package
protected String name;
// Public method - accessible from anywhere
public void eat() {
[Link](name + " is eating");
}
// Private method - accessible only within the Animal class
private void privateMethod() {
[Link]("This is a private method of Animal");
}
}
// Subclass Dog inheriting from Animal
class Dog extends Animal {
public void setName(String dogName) {
// Accessing protected member of superclass
name = dogName;
}
public void bark() {
[Link](name + " is barking");
37 | P a g e By [Link] (Technical Trainer)
}
}
// Subclass Cat inheriting from Animal
class Cat extends Animal {
public void setName(String catName) {
// Accessing protected member of superclass
name = catName;
}
public void meow() {
[Link](name + " is meowing");
}
}
// Main class to test hierarchical inheritance and access control
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
// Creating objects of Dog and Cat
Dog dog = new Dog();
[Link]("Buddy");
[Link](); // Buddy is eating
[Link](); // Buddy is barking
Cat cat = new Cat();
[Link]("Whiskers");
[Link](); // Whiskers is eating
[Link](); // Whiskers is meowing
// Attempt to access private method will result in a compile-time error
// [Link](); // Error: privateMethod() has private access in Animal
}
}
Application of `super` Keyword: [Purpose of `super`]
1. Access Superclass Constructor: `super()` is used to call the superclass constructor.
2. Access Superclass Methods: `[Link]()` is used to call the superclass
method.
3. Access Superclass Variables: `[Link]` is used to access superclass
variables.
38 | P a g e By [Link] (Technical Trainer)
Example:
class Animal {
String color = "white";
Animal() {
[Link]("Animal is created");
}
void eat() {
[Link]("Animal eats");
}
}
class Dog extends Animal {
String color = "black";
Dog() {
super(); // Calls Animal() constructor
[Link]("Dog is created");
}
void printColor() {
[Link](color); // black
[Link]([Link]); // white
}
void eat() {
[Link](); // Calls eat() method of Animal class
[Link]("Dog eats");
}
}
public class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
39 | P a g e By [Link] (Technical Trainer)
Constructor Method and Inheritance
Constructors are not inherited but are called when creating an object of a subclass.
A subclass can invoke the constructor of its superclass using `super()`.
Example:
class A {
A() {
[Link]("A's constructor");
}
}
class B extends A {
B() {
super(); // Calls constructor of A
[Link]("B's constructor");
}
}
public class TestConstructorInheritance {
public static void main(String[] args) {
B b = new B();
}
}
Method Overriding:
Overriding allows a subclass to provide a specific implementation for a method
already defined in its superclass.
Rules:
- The method must have the same name, return type, and parameters.
- It must be marked `public` or `protected` to be overridden.
- Cannot override `final` methods.
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
40 | P a g e By [Link] (Technical Trainer)
@Override
void sound() {
[Link]("Dog barks");
}
}
public class TestMethodOverriding {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Outputs: Dog barks
}
}
Dynamic Method Dispatch
Dynamic method dispatch is a mechanism by which a call to an overridden method is
resolved at runtime rather than compile-time, enabling polymorphism.
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
public class TestDynamicMethodDispatch {
public static void main(String[] args) {
Animal a;
41 | P a g e By [Link] (Technical Trainer)
a = new Dog();
[Link](); // Outputs: Dog barks
a = new Cat();
[Link](); // Outputs: Cat meows
}
}
Abstract Classes:
Abstract classes cannot be instantiated. They can contain abstract methods (without
body) and concrete methods (with implementation).
Subclasses of abstract classes must provide implementations for all abstract methods.
Example:
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
42 | P a g e By [Link] (Technical Trainer)
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
public class TestAbstractClass {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link](); // Outputs: Dog barks
a = new Cat();
[Link](); // Outputs: Cat meows
}
}
Using `final` with Inheritance in Java:
In Java, the `final` keyword can be used in the context of inheritance in the following ways:
1. Final Class: A class declared as `final` cannot be inherited.
2. Final Method: A method declared as `final` cannot be overridden by subclasses.
Why use `final` in inheritance?
To prevent modification of core logic in base classes.
To improve security and consistency.
To optimize performance by enabling method inlining at runtime.
43 | P a g e By [Link] (Technical Trainer)
Example: Final Method – Prevent Overriding
class Vehicle {
final void startEngine() {
[Link]("Engine started...");
}
void drive() {
[Link]("Vehicle is moving...");
}
}
class Car extends Vehicle {
// void startEngine() { // Not allowed: Cannot override final method
// [Link]("Custom start...");
// }
void drive() {
[Link]("Car is driving...");
}
}
public class FinalInheritanceExample {
public static void main(String[] args) {
Car myCar = new Car();
[Link](); // Allowed
[Link](); // Overridden method
}
}
Key Points:
Use `final class` to stop inheritance completely.
Use `final method` to stop selective method overriding.
Variables declared as `final` are constants (not related to inheritance directly, but good
to know).
44 | P a g e By [Link] (Technical Trainer)
Assignment Questions: Inheritance in Java:
Question 1: Inheritance Basics – Vehicle Management System
Create a base class `Vehicle` with attributes `brand` and `speed`.
Derive two subclasses: `Car` and `Bike`, which include their specific attributes like
`carType` and `bikeType`.
Write a Java program to:
Demonstrate inheritance
Display details of Car and Bike objects using inherited members
Question 2: super Keyword & Method Overriding – Employee Salary Calculator
Create a base class `Employee` with `name` and `basicSalary`.
Create a subclass `Manager` that overrides a method `calculateSalary()` to add
additional incentives.
Use the `super` keyword to:
Call the base class constructor
Invoke the overridden method for comparison
Question 3: Abstract Class & Dynamic Method Dispatch – Payment System
Define an abstract class `Payment` with an abstract method `pay()`.
Create two subclasses: `CreditCard` and `UPI`.
Use dynamic method dispatch to call the correct `pay()` implementation at
runtime.
Question 4: Forms of Inheritance – Academic Structure
Implement the following structure:
`Person` → `Student` → `ResearchStudent` (Multilevel Inheritance)
Each class should have appropriate attributes and methods.
Demonstrate multilevel inheritance by creating and displaying a `ResearchStudent`
object.
Question 5: Using final with Inheritance – Secure System Access
Create a class `User` with a `final` method `accessPortal()`.
Create a subclass `Admin` that adds admin-level access but cannot override
`accessPortal()`.
Demonstrate how the `final` keyword prevents method overriding.
45 | P a g e By [Link] (Technical Trainer)