0% found this document useful (0 votes)
9 views61 pages

Java Object-Oriented Programming Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views61 pages

Java Object-Oriented Programming Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming with Java (22UCS316C)

#1. Assignment Questions


1. Explain the two different paradigms of programming
Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java.

Two Paradigms
All computer programs consist of two elements: code and data. A program can be
conceptually organized around its code or around its data.

The first way is called the process-oriented model. This approach characterizes a program as
a series of linear steps (that is, code). Procedural languages such as C employ this model.

The second approach, called object-oriented programming organizes a program around its
data (that is, objects) and a set of well-defined interfaces to that data.

2. Explain with an example the features/pillars of Object Oriented Programming

Object-Oriented Programming (OOP) has four main pillars or features: Encapsulation,


Abstraction, Inheritance, and Polymorphism. Here's a simple example in Java to
demonstrate each of these concepts.
1. Encapsulation
Encapsulation is the bundling of data (fields) and methods that operate on the data into a
single unit (class). It also restricts direct access to some of the object's components, which is a
way of protecting the integrity of the data.
Example:
class Car {
// Private fields: Encapsulated data
private String color;
private String model;

// Public getter and setter methods


public String getColor() {
return color;
}

public void setColor(String color) {


[Link] = color;
}

public String getModel() {


return model;
}

public void setModel(String model) {


[Link] = model;
}
}
2. Abstraction
Abstraction hides complex details and shows only the essential features of an object. In Java,
abstraction can be achieved using abstract classes or interfaces.
abstract class Animal {
// Abstract method (does not have a body)
public abstract void sound();

// Regular method
public void sleep() {
[Link]("The animal sleeps");
}
}

class Dog extends Animal {


// Providing implementation for the abstract method
public void sound() {
[Link]("The dog barks");
}
}
3. Inheritance
Inheritance is a mechanism where one class (subclass) can inherit fields and methods from
another class (superclass), promoting code reuse and creating a relationship between classes.
class Vehicle {
public void startEngine() {
[Link]("Engine started");
}
}

class Car extends Vehicle {


public void honk() {
[Link]("Car honks");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
[Link](); // Inherited from Vehicle
[Link](); // Defined in Car
}
}
4. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class, and the correct
method implementation is determined at runtime. There are two types of polymorphism:
compile-time (method overloading) and runtime (method overriding).

Example:
class Animal {
public void sound() {
[Link]("Animal makes a sound");
}
}

class Cat extends Animal {


@Override
public void sound() {
[Link]("Cat meows");
}
}

class Dog extends Animal {


@Override
public void sound() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myCat = new Cat();
Animal myDog = new Dog();

[Link](); // Outputs: Cat meows


[Link](); // Outputs: Dog barks
}
}

3. What are all the data types available in java? Explain each of them.

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

There are 8 types of primitive data types:

o boolean data type

o byte data type

o char data type

o short data type

o int data type

o long data type

o float data type

o double data type

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-
2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data
type is used when you need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never be used
for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

Non-Primitive Data Types:


Strings (String): Represents a sequence of characters. In Java, String is a class, not a primitive type, but it’s
often treated like a primitive for convenience.

String name = "Java Programming";

[Link]("Name: " + name);

Arrays: A collection of elements of the same type. Arrays are fixed in size and can be of any data type,
including primitives and objects.

int[] numbers = {1, 2, 3, 4, 5};

[Link]("First number: " + numbers[0]);

Classes and Objects: Classes are blueprints for creating objects. Objects are instances of classes. They can
have properties (fields) and behaviors (methods).

class Person {

String name;

int age;

Person(String name, int age) {

[Link] = name;

[Link] = age;

Person person = new Person("Alice", 30);

[Link]("Name: " + [Link] + ", Age: " + [Link]);

Interface: An interface is a reference type that contains abstract methods, which other classes can
implement.

interface Animal {

void makeSound();

4. Write a java program to print size and range of values to assign the variables of these types.
public class DataTypeInfo {

public static void main(String[] args) {

[Link]("Primitive Data Types in Java:");

[Link]("1. byte:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);

[Link]("\n2. short:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);

[Link]("\n3. int:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);

[Link]("\n4. long:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);

[Link]("\n5. float:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);

[Link]("\n6. double:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);

[Link]("\n7. char:");

[Link](" Size: " + [Link] + " bits");

[Link](" Range: " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE);


[Link]("\n8. boolean:");

[Link](" Size: Not precisely defined (JVM-dependent, often 1 bit)");

[Link](" Range: " + [Link] + " to " + [Link]);

5. Explain Type Conversion and Casting in java with example program.

Type Conversion:

• Definition: Type conversion happens automatically when:

1. The source type is smaller than the destination type.

2. There is no data loss or precision issue.

• Examples of widening:

o byte → short → int → long → float → double

Example Program:

public class TypeConversionExample {

public static void main(String[] args) {

int num = 50; // Integer type

double doubleNum = num; // Automatic conversion (int to double)

[Link]("Integer value: " + num);

[Link]("Double value: " + doubleNum); // No data loss

output

Integer value: 50

Double value: 50.0

Type Casting
Definition: Type casting is done manually to convert a data type into another type. This is required when:
1. Converting from a larger to a smaller data type.
2. Data loss or precision issues might occur.
Examples of narrowing:
• double → float → long → int → short → byte
Example Program:
public class TypeCastingExample {
public static void main(String[] args) {
double doubleNum = 99.99; // Double type
int num = (int) doubleNum; // Manual conversion (double to int)

[Link]("Double value: " + doubleNum);


[Link]("Integer value: " + num); // Data loss occurs
}
}
Output:
Double value: 99.99
Integer value: 99

6. What is Automatic Type Promotion in Expressions? Give example.


When performing arithmetic or mixed-type operations in Java, smaller data types (byte, short, char) are
automatically promoted to a larger data type. This process ensures that the operations are carried out
without loss of precision.
Key Rules for Automatic Type Promotion
1. Small types (byte, short, char) are promoted to int before any operation.
2. If one of the operands is long, the result is promoted to long.
3. If one of the operands is float, the result is promoted to float.
4. If one of the operands is double, the result is promoted to double.
public class TypePromotionExample {
public static void main(String[] args) {
byte a = 10;
byte b = 20;
// a and b are promoted to int before addition
int result = a + b;

[Link]("Result of byte addition promoted to int: " + result);

char c = 'A'; // ASCII value of 'A' is 65


int charResult = c + 1; // char is promoted to int
[Link]("Result of char + int: " + charResult);

double d = 5.5;
int i = 2;
double mixedResult = d + i; // int is promoted to double
[Link]("Result of double + int: " + mixedResult);
}
}
Ouput
Result of byte addition promoted to int: 30
Result of char + int: 66
Result of double + int: 7.5

7. What is command line argument? Explain with an example how to process command line arguments
in java.
Command Line Arguments in Java
Definition
• Command-line arguments are inputs provided to a Java program during its execution via the terminal or
command prompt.
• They are passed as a sequence of String values and are stored in the args array of the main method.
How It Works
1. When you run a Java program, you can specify arguments after the class name in the command line.
2. These arguments are separated by spaces and are accessible as args[0], args[1], etc., in the main method.

Example Program:
public class CommandLineExample {
public static void main(String[] args) {
// Check if arguments are provided
if ([Link] == 0) {
[Link]("No arguments provided!");
} else {
[Link]("You entered the following arguments:");
// Loop through and print each argument
for (int i = 0; i < [Link]; i++) {
[Link]("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}
How to Run the Program
1. Compile the program:
bash
Copy code
javac [Link]
2. Run the program with arguments:
bash
Copy code
java CommandLineExample Hello World 123

Output
You entered the following arguments:
Argument 1: Hello
Argument 2: World
Argument 3: 123

8. Explain the following operators in java with example program


i. The ? operator
j. Boolean logical operators.

i. The ? (Ternary) Operator

The ternary operator (? :) is a shorthand for an if-else statement in Java. It takes three operands:

1. A condition.

2. The value if the condition is true.


3. The value if the condition is false.

Syntax:

condition ? value_if_true : value_if_false;

Example Program

public class TernaryOperatorExample {

public static void main(String[] args) {

int a = 10, b = 20;

// Ternary operator to find the maximum of two numbers

int max = (a > b) ? a : b;

[Link]("The maximum value is: " + max);

Output: The maximum value is: 20

[Link] Logical Operators

Boolean logical operators are used to perform logical operations on boolean values. They return true
or false depending on the operands.

public class LogicalOperatorsExample {

public static void main(String[] args) {

boolean a = true;

boolean b = false;

// Logical AND

[Link]("a && b: " + (a && b)); // false

// Logical OR

[Link]("a || b: " + (a || b)); // true

// Logical NOT
[Link]("!a: " + (!a)); // false

Output:

a && b: false

a || b: true

!a: false

9. Explain the following selection statements with syntax and example.


i. Else-if ladder
ii. Switch statement
iii. Nested switch statement

Else-If Ladder
The else-if ladder is used when multiple conditions need to be checked sequentially. If one
condition is true, its corresponding block is executed, and the rest are ignored.
Syntax
if (condition1) {
// Block of code for condition1
} else if (condition2) {
// Block of code for condition2
} else if (condition3) {
// Block of code for condition3
} else {
// Block of code if none of the conditions are true
}
Example Program
public class ElseIfExample {
public static void main(String[] args) {
int marks = 85;

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 75) {
[Link]("Grade: A");
} else if (marks >= 50) {
[Link]("Grade: B");
} else {
[Link]("Grade: F");
}
}
}
Output:
Grade: A
ii. Switch Statement
The switch statement is used when a variable or expression is tested against multiple values
(cases). It is an alternative to the if-else-if ladder, usually more efficient for discrete values.
Syntax
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no cases match
break;
}
Example Program
public class SwitchExample {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
break;
}
}
}
Output:
Wednesday

iii. Nested Switch Statement


A nested switch statement is when one switch statement is inside another. It is useful for
multi-level decision-making.
Syntax
switch (expression1) {
case value1:
switch (expression2) {
case valueA:
// Code for valueA
break;
case valueB:
// Code for valueB
break;
}
break;
case value2:
// Code for value2
break;
default:
// Code if no cases match
break;
}
Example Program

public class NestedSwitchExample {


public static void main(String[] args) {
int branch = 1; // 1: Engineering, 2: Medical
int year = 2; // Year of study

switch (branch) {
case 1:
[Link]("Branch: Engineering");
switch (year) {
case 1:
[Link]("Subjects: Physics, Chemistry, Mathematics");
break;
case 2:
[Link]("Subjects: Data Structures, Algorithms");
break;
default:
[Link]("Invalid year");
break;
}
break;
case 2:
[Link]("Branch: Medical");
// Further nested cases for Medical
break;
default:
[Link]("Invalid branch");
break;
}
}
}
Output:
Branch: Engineering
Subjects: Data Structures, Algorithms

10. Explain the following iteration statements with syntax and example.
i. For
ii. While
iii. Do-while
iv. For-each
i. For Loop
The for loop is used when the number of iterations is known beforehand. It consists of three
parts:
1. Initialization: Executes once before the loop starts.
2. Condition: Evaluated before each iteration. The loop continues as long as the condition is true.
3. Increment/Decrement: Updates the loop control variable after each iteration.
Syntax
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example Program
public class ForLoopExample {
public static void main(String[] args) {
// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}
Output:
1
2
3
4
5

ii. While Loop


The while loop is used when the number of iterations is not known in advance, and the loop
continues as long as the condition is true.
Syntax
while (condition) {
// Code to be executed
}
Example Program
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;

// Print numbers from 1 to 5 using while loop


while (i <= 5) {
[Link](i);
i++; // Increment the value of i
}
}
}
Output:
1
2
3
4
5

iii. Do-While Loop


The do-while loop is similar to the while loop, but it guarantees that the code will execute at
least once, even if the condition is false from the start.
Syntax
do {
// Code to be executed
} while (condition);
Example Program
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;

// Print numbers from 1 to 5 using do-while loop


do {
[Link](i);
i++; // Increment the value of i
} while (i <= 5);
}
}
Output:
1
2
3
4
5

iv. For-Each Loop (Enhanced for loop)


The for-each loop (or enhanced for loop) is used to iterate over collections (arrays, lists, etc.)
without using an index. It is mainly used for accessing each element of an array or a
collection directly.
Syntax
for (type var : collection) {
// Code to be executed
}
Example Program
public class ForEachLoopExample {
public static void main(String[] args) {
// Array of integers
int[] numbers = {1, 2, 3, 4, 5};

// Using for-each loop to print all numbers in the array


for (int num : numbers) {
[Link](num);
}
}
}
Output:
1
2
3
4
5
11. Explain the use of break and continue statements in java. Write example for each

Break Statement

The break statement is used to terminate the current loop or switch statement immediately, regardless of the
loop condition. It causes the program to exit from the loop and resume execution at the next statement after
the loop.

• Exiting a loop early based on a condition.


• Exiting a switch statement when a case is matched.
Example Program
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Breaking the loop when i = " + i);
break; // Exit the loop when i is 5
}
[Link](i);
}
}
}
Output:
1
2
3
4
Breaking the loop when i = 5

Continue Statement
The continue statement is used to skip the current iteration of a loop and move to the next iteration.
It doesn't terminate the loop but skips the remaining code for the current iteration and proceeds to the
next loop cycle.

Example Program
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Skipping the iteration when i = " + i);
continue; // Skip the iteration when i is 5
}
[Link](i);
}
}
}
Output:
1
2
3
4
Skipping the iteration when i = 5
6
7
8
9
10

12. What is array? Explain the following with respect to an array.


i. Declaration of 1D and 2D array with syntax and example
ii. Initialization of 1D array.
iii. Processing 1D and 2D array.

An array is a collection of variables of the same type stored in contiguous memory locations.
It is a data structure that allows you to store multiple values in a single variable, which can be
accessed by an index. Arrays in Java are objects, and their size is fixed once declared.

i. Declaration of 1D and 2D Array

1D Array Declaration

A 1D array is a simple list of elements of the same type.

Syntax for Declaring 1D Array


dataType[] arrayName; or dataType arrayName[];

Example of 1D Array Declaration

public class OneDArrayExample {

public static void main(String[] args) {

// Declaration of a 1D array

int[] numbers;

// Allocation of memory for 5 integers

numbers = new int[5];


// Initializing elements of the array

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

// Accessing and printing the array elements

for (int i = 0; i < [Link]; i++) {

[Link]("Element at index " + i + ": " + numbers[i]);

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

2D Array Declaration

A 2D array is an array of arrays. It can be viewed as a matrix with rows and columns.

Syntax for Declaring 2D Array

dataType[][] arrayName; or dataType arrayName[][];

Example of 2D Array Declaration

public class TwoDArrayExample {

public static void main(String[] args) {

// Declaration of a 2D array

int[][] matrix;

// Allocation of memory for 2 rows and 3 columns


matrix = new int[2][3];

// Initializing elements of the 2D array

matrix[0][0] = 1;

matrix[0][1] = 2;

matrix[0][2] = 3;

matrix[1][0] = 4;

matrix[1][1] = 5;

matrix[1][2] = 6;

// Accessing and printing the elements of the 2D array

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < matrix[i].length; j++) {

[Link](matrix[i][j] + " ");

[Link]();

Output:

123

456

ii. Initialization of 1D Array

You can initialize a 1D array at the time of declaration by specifying the elements within curly braces {}.
This method is called array initialization.

Syntax for Initialization

dataType[] arrayName = {element1, element2, ..., elementN};

Example of 1D Array Initialization

public class ArrayInitializationExample {

public static void main(String[] args) {


// Initialization of a 1D array

int[] numbers = {10, 20, 30, 40, 50};

// Accessing and printing the array elements

for (int i = 0; i < [Link]; i++) {

[Link]("Element at index " + i + ": " + numbers[i]);

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

Processing 1D and 2D Arrays

Processing 1D Array

Processing a 1D array generally involves iterating through the array and performing operations (like reading,
updating, or manipulating data).

Example: Processing a 1D Array

public class ProcessOneDArray {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5};

// Processing 1D array: Calculating the sum of elements

int sum = 0;

for (int i = 0; i < [Link]; i++) {

sum += numbers[i];

}
[Link]("Sum of all elements in the array: " + sum);

Output: Sum of all elements in the array: 15

Processing 2D Array

Processing a 2D array involves accessing elements by their row and column indices, typically with nested
loops (one loop for rows and another for columns).

Example: Processing a 2D Array

public class ProcessTwoDArray {

public static void main(String[] args) {

int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};

// Processing 2D array: Calculating the sum of all elements

int sum = 0;

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < matrix[i].length; j++) {

sum += matrix[i][j];

[Link]("Sum of all elements in the matrix: " + sum);

Output: Sum of all elements in the matrix: 21

13. Write a java program to perform following


i. Read and print 1D array.
ii. To find variance of an array
iii. To find maximum and minimum element in array.
import [Link];

public class ArrayOperations {

public static void main(String[] args) {

// Create a scanner object to read input

Scanner scanner = new Scanner([Link]);

// Reading the size of the array

[Link]("Enter the size of the array: ");

int size = [Link]();

// Create an array of the given size

int[] arr = new int[size];

// Reading elements of the array

[Link]("Enter the elements of the array:");

for (int i = 0; i < size; i++) {

arr[i] = [Link]();

// Print the 1D array

[Link]("\n1D Array Elements:");

for (int i = 0; i < size; i++) {

[Link](arr[i] + " ");

// Calculate the variance of the array

double mean = calculateMean(arr);

double variance = calculateVariance(arr, mean);


[Link]("\n\nVariance of the array: " + variance);

// Find maximum and minimum element in the array

int max = findMax(arr);

int min = findMin(arr);

[Link]("\nMaximum element: " + max);

[Link]("Minimum element: " + min);

// Close the scanner object

[Link]();

// Method to calculate the mean of the array

public static double calculateMean(int[] arr) {

double sum = 0;

for (int i = 0; i < [Link]; i++) {

sum += arr[i];

return sum / [Link];

// Method to calculate the variance of the array

public static double calculateVariance(int[] arr, double mean) {

double sumSquaredDifferences = 0;

for (int i = 0; i < [Link]; i++) {

sumSquaredDifferences += [Link](arr[i] - mean, 2);

return sumSquaredDifferences / [Link];

}
// Method to find the maximum element in the array

public static int findMax(int[] arr) {

int max = arr[0];

for (int i = 1; i < [Link]; i++) {

if (arr[i] > max) {

max = arr[i];

return max;

// Method to find the minimum element in the array

public static int findMin(int[] arr) {

int min = arr[0];

for (int i = 1; i < [Link]; i++) {

if (arr[i] < min) {

min = arr[i];

return min;

Output

Enter the size of the array: 5

Enter the elements of the array:

12345

1D Array Elements:

12345
Variance of the array: 2.0

Maximum element: 5

Minimum element: 1

14. Write a java program to perform following


iv. Read and print 2D array.
v. To find sum of principle diagonal elements.
vi. To find sum of all elements except principle diagonal.
vii. To find sum of secondary diagonal elements

import [Link];

public class TwoDArrayOperations {

public static void main(String[] args) {

// Create a scanner object to read input

Scanner scanner = new Scanner([Link]);

// Reading the size of the 2D array (square matrix)

[Link]("Enter the number of rows and columns for the square matrix: ");

int n = [Link]();

// Create a 2D array of size n x n

int[][] matrix = new int[n][n];

// Reading elements of the matrix

[Link]("Enter the elements of the matrix:");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

matrix[i][j] = [Link]();

}
// Print the 2D matrix

[Link]("\n2D Matrix:");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

[Link](matrix[i][j] + " ");

[Link]();

// Find the sum of the principal diagonal

int principalDiagonalSum = sumPrincipalDiagonal(matrix, n);

[Link]("\nSum of Principal Diagonal: " + principalDiagonalSum);

// Find the sum of all elements except principal diagonal

int sumExceptPrincipalDiagonal = sumExceptPrincipalDiagonal(matrix, n);

[Link]("Sum of all elements except Principal Diagonal: " + sumExceptPrincipalDiagonal);

// Find the sum of the secondary diagonal

int secondaryDiagonalSum = sumSecondaryDiagonal(matrix, n);

[Link]("Sum of Secondary Diagonal: " + secondaryDiagonalSum);

// Close the scanner object

[Link]();

// Method to calculate the sum of the principal diagonal elements

public static int sumPrincipalDiagonal(int[][] matrix, int n) {

int sum = 0;

for (int i = 0; i < n; i++) {


sum += matrix[i][i]; // Principal diagonal elements are at [i][i]

return sum;

// Method to calculate the sum of all elements except the principal diagonal

public static int sumExceptPrincipalDiagonal(int[][] matrix, int n) {

int sum = 0;

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

if (i != j) { // Excluding principal diagonal

sum += matrix[i][j];

return sum;

// Method to calculate the sum of the secondary diagonal elements

public static int sumSecondaryDiagonal(int[][] matrix, int n) {

int sum = 0;

for (int i = 0; i < n; i++) {

sum += matrix[i][n - 1 - i]; // Secondary diagonal elements are at [i][n-1-i]

return sum;

Output

Enter the number of rows and columns for the square matrix: 3

Enter the elements of the matrix:


123

456

789

2D Matrix:

123

456

789

Sum of Principal Diagonal: 15

Sum of all elements except Principal Diagonal: 30

Sum of Secondary Diagonal: 15

[Link] class and object. With syntax and example, explain how to create a class and its objects

Class: A class is a blueprint or template from which objects are created. It defines the properties
(attributes/fields) and behaviors (methods) that the objects created from it will have. A class doesn't occupy
memory itself; it's only a template for creating objects.

Object: An object is an instance of a class. When a class is instantiated (i.e., when an object is created),
the memory is allocated for the object, and it can access the properties and methods defined in the class.

Syntax for Defining a Class

class ClassName {

// Fields (Attributes)

dataType fieldName;

// Constructor (optional)

ClassName() {

// Initialization code (if needed)

// Methods (Behaviors)

returnType methodName() {

// Code block
}

Creating Objects

To create an object, you use the new keyword followed by a call to the class constructor. Here's the syntax:

ClassName objectName = new ClassName();

Example: Creating a Class and Objects

// Define the class

class Car {

// Fields (Attributes)

String brand;

String model;

int year;

// Constructor

Car(String b, String m, int y) {

brand = b;

model = m;

year = y;

// Method (Behavior)

void displayInfo() {

[Link]("Brand: " + brand);

[Link]("Model: " + model);

[Link]("Year: " + year);

public class Main {

public static void main(String[] args) {


// Creating objects of the Car class

Car car1 = new Car("Toyota", "Corolla", 2020);

Car car2 = new Car("Honda", "Civic", 2021);

// Calling the method to display information

[Link]("Car 1 Information:");

[Link]();

[Link]("\nCar 2 Information:");

[Link]();

Output

Car 1 Information:

Brand: Toyota

Model: Corolla

Year: 2020

Car 2 Information:

Brand: Honda

Model: Civic

Year: 2021

16 What is constructor? Explain with example.

A constructor is a special type of method in a class that is used to initialize objects. It is automatically
called when an object of the class is created. Constructors have the same name as the class and do not have a
return type, not even void.

Key Points About Constructors

1. Initialization: Constructors are primarily used to initialize the state of an object when it is created.

2. No Return Type: Constructors do not have any return type, not even void.

3. Name: The constructor’s name must be the same as the class name.

4. Automatic Invocation: A constructor is called automatically when an object of the class is created.
Types of Constructors

Default Constructor: A constructor that takes no parameters. If no constructor is defined, Java provides
a default constructor (which doesn't initialize any fields).

Parameterized Constructor: A constructor that accepts arguments to initialize an object with specific
values.

Syntax

• Default Constructor:

class ClassName {

ClassName() {

// Initialization code

Parameterized Constructor:

class ClassName {

ClassName(dataType param1, dataType param2) {

// Initialization code using the parameters

Example of Constructor in Java

// Define the class

class Student {

// Fields (Attributes)

String name;

int age;

// Default Constructor

Student() {

name = "Unknown";

age = 0;

}
// Parameterized Constructor

Student(String name, int age) {

[Link] = name;

[Link] = age;

// Method to display student information

void displayInfo() {

[Link]("Name: " + name);

[Link]("Age: " + age);

public class Main {

public static void main(String[] args) {

// Creating objects of Student class using constructors

// Object using the default constructor

Student student1 = new Student();

// Object using the parameterized constructor

Student student2 = new Student("Alice", 20);

// Displaying information for both students

[Link]("Student 1 Information:");

[Link]();

[Link]("\nStudent 2 Information:");

[Link]();

}
}

Output

Student 1 Information:

Name: Unknown

Age: 0

Student 2 Information:

Name: Alice

Age: 20

17. What is access control? Explain with example how you can provide access control in java.

Access control refers to the mechanism by which you can specify the visibility and accessibility of classes,
methods, and variables to other classes. In Java, access control is implemented using access modifiers that
determine the level of access other classes have to the members (fields, methods, and constructors) of a
class.

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.

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.

Example of Access Control

Class A:

// Class A

public class A {

// Public variable - accessible from anywhere

public int publicVar = 1;

// Protected variable - accessible within the same package and subclasses

protected int protectedVar = 2;


// Default (package-private) variable - accessible only within the same package

int defaultVar = 3;

// Private variable - accessible only within this class

private int privateVar = 4;

// Public method

public void displayPublic() {

[Link]("Public method called");

// Protected method

protected void displayProtected() {

[Link]("Protected method called");

// Default (package-private) method

void displayDefault() {

[Link]("Default method called");

// Private method

private void displayPrivate() {

[Link]("Private method called");

Class B:

// Class B

public class B {
public static void main(String[] args) {

// Creating object of class A

A obj = new A();

// Accessing the public variable and method

[Link]("Public variable: " + [Link]);

[Link]();

// Accessing the protected variable and method (within the same package)

[Link]("Protected variable: " + [Link]);

[Link]();

// Accessing the default (package-private) variable and method (within the same package)

[Link]("Default variable: " + [Link]);

[Link]();

// Accessing the private variable and method is not allowed

// [Link]("Private variable: " + [Link]); // Error

// [Link](); // Error

Output

Public variable: 1

Public method called

Protected variable: 2

Protected method called

Default variable: 3

Default method called

[Link] the box program explain the following

i. how to add different functions to the class


ii. Assigning object reference variables.

[Link] a java program to create class called ‘Person’ with data members name and age, suitable
constructors and member function ‘Display_info’. Write a suitable main function to create two persons P1
and P2 and demonstrate ‘Person’ class.

// Person class definition

class Person {

// Data members

String name;

int age;

// Constructor to initialize name and age

Person(String name, int age) {

[Link] = name;

[Link] = age;

// Method to display the person's information

void Display_info() {

[Link]("Name: " + name);

[Link]("Age: " + age);

public class PersonDemo {

public static void main(String[] args) {

// Creating two Person objects

Person P1 = new Person("Alice", 25);

Person P2 = new Person("Bob", 30);


// Displaying information of Person P1

[Link]("Person 1 Info:");

P1.Display_info();

// Displaying information of Person P2

[Link]("\nPerson 2 Info:");

P2.Display_info();

Output

Person 1 Info:

Name: Alice

Age: 25

Person 2 Info:

Name: Bob

Age: 30

[Link] the garbage collection in java.

[Link] a java program as following


Student Class:
Data members: name and studentId.
Constructor: Initializes name and studentId for each Student.
Method: displayStudentInfo to print student details.
Course Class:
Data members: courseName and a reference to a Student object.
Constructor: Initializes courseName and assigns a Student object reference.
Method: displayCourseInfo to display course and student details by calling displayStudentInfo on the
Student reference.
Main Class:
main Method: Creates Student objects and assigns them as references to Course objects. It displays
details of each course and associated student.

// Student class definition


class Student {
// Data members
String name;
int studentId;

// Constructor to initialize name and studentId


Student(String name, int studentId) {
[Link] = name;
[Link] = studentId;
}

// Method to display student information


void displayStudentInfo() {
[Link]("Student Name: " + name);
[Link]("Student ID: " + studentId);
}
}

// Course class definition


class Course {
// Data members
String courseName;
Student student; // Reference to a Student object

// Constructor to initialize courseName and Student reference


Course(String courseName, Student student) {
[Link] = courseName;
[Link] = student;
}

// Method to display course and student details


void displayCourseInfo() {
[Link]("Course Name: " + courseName);
[Link]("Student Info: ");
[Link](); // Call method on the student reference
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating Student objects
Student student1 = new Student("Alice", 101);
Student student2 = new Student("Bob", 102);

// Creating Course objects and associating with Student objects


Course course1 = new Course("Mathematics", student1);
Course course2 = new Course("Science", student2);

// Displaying course and student details


[Link]("Course 1 Information:");
[Link]();

[Link]("\nCourse 2 Information:");
[Link]();
}
}
Ouput
Course 1 Information:
Course Name: Mathematics
Student Info:
Student Name: Alice
Student ID: 101

Course 2 Information:
Course Name: Science
Student Info:
Student Name: Bob
Student ID: 102

[Link] is method overloading in java? Explain with example.

Method Overloading in Java refers to the ability to define multiple methods in a class with the same
name but with different method signatures. A method's signature is determined by the method's name,
the number of parameters, and the types of parameters.

• Method overloading allows a class to have more than one method with the same name but with
different argument lists (either by changing the number or type of parameters).

• It enhances the readability of the program by allowing similar operations to be performed with
methods that have the same name but work with different types or numbers of arguments.

• • Overloading is resolved at compile-time (also known as compile-time polymorphism).


• • The return type does not contribute to method overloading. Only the method name and parameter
list matter.
class MathOperations {

// Method to add two integers


public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


public double add(double a, double b) {
return a + b;
}

// Overloaded method to add two string values


public String add(String a, String b) {
return a + b;
}
}

public class MethodOverloadingExample {


public static void main(String[] args) {
MathOperations mathOps = new MathOperations();

// Calling add method with two integers


[Link]("Sum of 10 and 20: " + [Link](10, 20));

// Calling add method with three integers


[Link]("Sum of 10, 20, and 30: " + [Link](10, 20, 30));

// Calling add method with two doubles


[Link]("Sum of 10.5 and 20.5: " + [Link](10.5, 20.5));

// Calling add method with two strings


[Link]("Concatenation of Hello and World: " + [Link]("Hello", "World"));
}
}
Output
Sum of 10 and 20: 30
Sum of 10, 20, and 30: 60
Sum of 10.5 and 20.5: 31.0
Concatenation of Hello and World: HelloWorld
23. Write a java program to create a class called ‘Printer’ to overload a function ‘Print’ which prints
i. A number
j. a string
k. an array

Write main class with suitable main function to demonstrate method overloading.

class Printer {

// Method to print a number (integer)

public void Print(int number) {

[Link]("Printing a number: " + number);

// Overloaded method to print a string

public void Print(String text) {

[Link]("Printing a string: " + text);

// Overloaded method to print an array of integers

public void Print(int[] array) {

[Link]("Printing an array: ");

for (int i = 0; i < [Link]; i++) {

[Link](array[i] + " ");

[Link](); // Move to the next line after printing the array

// Main class to demonstrate method overloading

public class Main {

public static void main(String[] args) {


// Create an object of Printer class

Printer printer = new Printer();

// Demonstrating method overloading

// Print a number

[Link](100);

// Print a string

[Link]("Hello, Java!");

// Print an array

int[] numbers = {10, 20, 30, 40, 50};

[Link](numbers);

Output

Printing a number: 100

Printing a string: Hello, Java!

Printing an array: 10 20 30 40 50

[Link] a class called TIME and implement the following operations by Overloading ADD ( )as

i. ADD (T1, T2) - where T1 and T2 are two time objects.


j. ADD (T1, N) - where N is an integer number to be added to seconds of T1 object.

Write suitable main function to use these functions overloaded

[Link] a java program to perform different arithmetic operations on complex numbers.

// Class to represent a complex number

class Complex {
// Data members for real and imaginary parts

double real, imaginary;

// Constructor to initialize complex number

Complex(double real, double imaginary) {

[Link] = real;

[Link] = imaginary;

// Method to display complex number

void display() {

if (imaginary < 0)

[Link](real + " - " + [Link](imaginary) + "i");

else

[Link](real + " + " + imaginary + "i");

// Method to add two complex numbers

Complex add(Complex c) {

return new Complex([Link] + [Link], [Link] + [Link]);

// Method to subtract two complex numbers

Complex subtract(Complex c) {

return new Complex([Link] - [Link], [Link] - [Link]);

// Method to multiply two complex numbers

Complex multiply(Complex c) {

double realPart = ([Link] * [Link]) - ([Link] * [Link]);


double imaginaryPart = ([Link] * [Link]) + ([Link] * [Link]);

return new Complex(realPart, imaginaryPart);

// Method to divide two complex numbers

Complex divide(Complex c) {

double denominator = [Link] * [Link] + [Link] * [Link];

double realPart = ([Link] * [Link] + [Link] * [Link]) / denominator;

double imaginaryPart = ([Link] * [Link] - [Link] * [Link]) / denominator;

return new Complex(realPart, imaginaryPart);

public class ComplexNumberOperations {

public static void main(String[] args) {

// Create two complex numbers

Complex c1 = new Complex(4, 5); // Complex number: 4 + 5i

Complex c2 = new Complex(2, 3); // Complex number: 2 + 3i

// Display the complex numbers

[Link]("Complex Number 1: ");

[Link]();

[Link]("Complex Number 2: ");

[Link]();

// Perform addition

Complex sum = [Link](c2);

[Link]("\nAddition of c1 and c2: ");

[Link]();
// Perform subtraction

Complex difference = [Link](c2);

[Link]("\nSubtraction of c1 and c2: ");

[Link]();

// Perform multiplication

Complex product = [Link](c2);

[Link]("\nMultiplication of c1 and c2: ");

[Link]();

// Perform division

Complex quotient = [Link](c2);

[Link]("\nDivision of c1 by c2: ");

[Link]();

Output:

Complex Number 1:

4.0 + 5.0i

Complex Number 2:

2.0 + 3.0i

Addition of c1 and c2:

6.0 + 8.0i

Subtraction of c1 and c2:

2.0 + 2.0i

Multiplication of c1 and c2:

-7.0 + 22.0i
Division of c1 by c2:

2.0 + 0.0i

[Link] the use o f following keywords in java with an example program

i. ‘this’
iii. ‘static’
iv. ‘final’
v. ‘super’
vi. ‘public’
vii. ‘protected’

[Link] this keyword refers to the current object of the class. It is often used to differentiate between instance
variables and parameters with the same name, or to call other constructors within the same class

Example:

class Person {

String name;

// Constructor

Person(String name) {

[Link] = name; // 'this' is used to refer to the instance variable

void display() {

[Link]("Name: " + [Link]); // 'this' is optional here, but used for clarity

public class Test {

public static void main(String[] args) {

Person p = new Person("John");

[Link](); // Output: Name: John

}
[Link] static keyword is used to declare class-level members (variables or methods), meaning they belong to
the class itself rather than to instances of the class. static members are shared by all instances.

class Counter {

static int count = 0; // Static variable

// Static method

static void increment() {

count++;

public class Test {

public static void main(String[] args) {

[Link]();

[Link]();

[Link]("Count: " + [Link]); // Output: Count: 2

[Link] final keyword is used to define constants, prevent method overriding, and prevent inheritance. It can
be applied to variables, methods, and classes.

• Final variable: Once assigned a value, it cannot be changed.

• Final method: Cannot be overridden in a subclass.

• Final class: Cannot be inherited.

class Car {

final int MAX_SPEED = 120; // Final variable

// Final method

final void display() {

[Link]("Car max speed: " + MAX_SPEED);

}
class SportsCar extends Car {

// The following method would result in an error because display() is final in the parent class

// void display() {

// [Link]("SportsCar max speed: " + MAX_SPEED);

// }

public class Test {

public static void main(String[] args) {

Car c = new Car();

[Link](); // Output: Car max speed: 120

[Link] super keyword refers to the superclass (parent class) of the current object. It can be used to access
superclass methods and constructors.

class Animal {

void eat() {

[Link]("Animal is eating");

class Dog extends Animal {

void eat() {

[Link](); // Call the superclass's eat method

[Link]("Dog is eating");

public class Test {


public static void main(String[] args) {

Dog d = new Dog();

[Link](); // Output: Animal is eating

// Dog is eating

[Link] public keyword is an access modifier used to specify that a class, method, or variable is accessible
from any other class.

public class MyClass {

public int x; // Public variable

public void display() { // Public method

[Link]("Public method in MyClass");

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.x = 10; // Accessing public variable

[Link](); // Calling public method

[Link]("Value of x: " + obj.x); // Output: Value of x: 10

[Link] protected keyword is an access modifier that allows the member to be accessed within its package
and by subclasses (including those in other packages).

class Animal {

protected void sound() { // Protected method

[Link]("Animal makes sound");

}
class Dog extends Animal {

void sound() {

[Link]("Dog barks");

public class Test {

public static void main(String[] args) {

Dog d = new Dog();

[Link](); // Output: Dog barks

[Link] is inheritance? Explain multilevel inheritance with example.

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Java. It allows a new
class to inherit properties and behaviors (fields and methods) from an existing class. This enables code
reuse and establishes a relationship between the parent (superclass) and child (subclass) classes.

Superclass (Parent class): The class whose properties and methods are inherited by another class.

Subclass (Child class): The class that inherits the properties and methods from the parent class.

extends keyword: Used to establish inheritance between classes.

Multilevel Inheritance in Java

Multilevel Inheritance occurs when a class inherits from another class, and then another class inherits from
the first subclass, creating a chain of inheritance.

For example:

• Class A → Class B (inherits from Class A) → Class C (inherits from Class B)

Example of Multilevel Inheritance

// Parent class (Superclass)

class Animal {

void eat() {

[Link]("Animal is eating");

}
// Child class 1 (Subclass of Animal)

class Dog extends Animal {

void bark() {

[Link]("Dog is barking");

// Child class 2 (Subclass of Dog, and thus also a subclass of Animal)

class Puppy extends Dog {

void play() {

[Link]("Puppy is playing");

public class Test {

public static void main(String[] args) {

// Creating an object of the Puppy class

Puppy puppy = new Puppy();

// Calling methods from the Puppy, Dog, and Animal classes

[Link](); // Inherited from Animal

[Link](); // Inherited from Dog

[Link](); // Defined in Puppy

Output

Animal is eating

Dog is barking

Puppy is playing
[Link] with syntax and example the nested and inner class.
[Link] java program to define the following classes.

PERSON : Data members – Name, Address, Age


Member functions – Input(), Output()
STUDENT : Derived from PERSON
Data members : CGPA
Member functions – Input(), Output()
PROFESSOR : Derived from PERSON
Data members : No. of Publications
Member functions – Input(), Output()

Write main class to Display the details of the students having CGPA > 8.5 and also the details of the
professors having no. of publications > 25

import [Link];

// Base class PERSON

class PERSON {

// Data members

String name;

String address;

int age;

// Method to input details


void Input() {

Scanner sc = new Scanner([Link]);

[Link]("Enter Name: ");

name = [Link]();

[Link]("Enter Address: ");

address = [Link]();

[Link]("Enter Age: ");

age = [Link]();

[Link](); // consume the newline character

// Method to display details

void Output() {

[Link]("Name: " + name);

[Link]("Address: " + address);

[Link]("Age: " + age);

// Derived class STUDENT from PERSON

class STUDENT extends PERSON {

// Data member

double cgpa;

// Method to input details of student

void Input() {

[Link](); // calling the Input method of PERSON class

Scanner sc = new Scanner([Link]);

[Link]("Enter CGPA: ");

cgpa = [Link]();
}

// Method to display student details

void Output() {

[Link](); // calling the Output method of PERSON class

[Link]("CGPA: " + cgpa);

// Derived class PROFESSOR from PERSON

class PROFESSOR extends PERSON {

// Data member

int numOfPublications;

// Method to input details of professor

void Input() {

[Link](); // calling the Input method of PERSON class

Scanner sc = new Scanner([Link]);

[Link]("Enter Number of Publications: ");

numOfPublications = [Link]();

// Method to display professor details

void Output() {

[Link](); // calling the Output method of PERSON class

[Link]("Number of Publications: " + numOfPublications);

// Main class to demonstrate the functionality


public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Creating an array of students and professors

STUDENT[] students = new STUDENT[2];

PROFESSOR[] professors = new PROFESSOR[2];

// Input for Students

for (int i = 0; i < [Link]; i++) {

[Link]("\nEnter details of Student " + (i + 1) + ":");

students[i] = new STUDENT();

students[i].Input();

// Input for Professors

for (int i = 0; i < [Link]; i++) {

[Link]("\nEnter details of Professor " + (i + 1) + ":");

professors[i] = new PROFESSOR();

professors[i].Input();

// Display students with CGPA > 8.5

[Link]("\nStudents with CGPA greater than 8.5:");

for (STUDENT student : students) {

if ([Link] > 8.5) {

[Link]();

[Link](); // To separate the details

}
// Display professors with more than 25 publications

[Link]("\nProfessors with more than 25 publications:");

for (PROFESSOR professor : professors) {

if ([Link] > 25) {

[Link]();

[Link](); // To separate the details

Output

Enter details of Student 1:

Enter Name: Alice

Enter Address: New York

Enter Age: 20

Enter CGPA: 9.2

Enter details of Student 2:

Enter Name: Bob

Enter Address: California

Enter Age: 22

Enter CGPA: 7.5

Enter details of Professor 1:

Enter Name: Dr. Smith

Enter Address: Boston

Enter Age: 45

Enter Number of Publications: 30

Enter details of Professor 2:


Enter Name: Dr. Johnson

Enter Address: Texas

Enter Age: 50

Enter Number of Publications: 20

Students with CGPA greater than 8.5:

Name: Alice

Address: New York

Age: 20

CGPA: 9.2

Professors with more than 25 publications:

Name: Dr. Smith

Address: Boston

Age: 45

Number of Publications: 30

[Link] is method overriding? Explain with example.

Method Overriding is a feature of Object-Oriented Programming (OOP) in Java where a subclass provides
its specific implementation of a method that is already defined in its superclass.

Goal: To define a method in a subclass with the same signature (name, return type, and parameters) as a
method in the superclass, but with a different implementation.

Why Use It: Method overriding allows a subclass to modify or extend the behavior of a superclass
method without changing the superclass code. It supports runtime polymorphism in Java.

Syntax of Method Overriding:

class Superclass {

void display() {

[Link]("This is the Superclass display method.");

class Subclass extends Superclass {

@Override
void display() {

[Link]("This is the Subclass overridden display method.");

Example of Method Overriding in Java:

// Superclass

class Animal {

void sound() {

[Link]("Animals make sound");

// Subclass

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");

class Cat extends Animal {

@Override

void sound() {

[Link]("Cat meows");

public class Test {

public static void main(String[] args) {

// Creating objects of the subclasses


Animal myDog = new Dog(); // Animal reference, Dog object

Animal myCat = new Cat(); // Animal reference, Cat object

// Calling overridden methods

[Link](); // Calls Dog's sound()

[Link](); // Calls Cat's sound()

Output

Dog barks

Cat meows

You might also like