0% found this document useful (0 votes)
74 views

Ujjwal Oops File

The document discusses several Java programs with different aims: 1. Introduction to Object Oriented Programming in Java, discussing features like encapsulation, inheritance, polymorphism, and abstraction. 2. A simple "Hello World" program in Java. 3. A program that takes two numbers as command line arguments and prints their sum. 4. A program that takes two numbers as input using the Scanner class and prints their sum. 5. A program that generates a random number between 1-100 and checks if it is a prime number. 6. Programs to print the factorial of a number and the Fibonacci series up to a given number using recursion. 7. A

Uploaded by

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

Ujjwal Oops File

The document discusses several Java programs with different aims: 1. Introduction to Object Oriented Programming in Java, discussing features like encapsulation, inheritance, polymorphism, and abstraction. 2. A simple "Hello World" program in Java. 3. A program that takes two numbers as command line arguments and prints their sum. 4. A program that takes two numbers as input using the Scanner class and prints their sum. 5. A program that generates a random number between 1-100 and checks if it is a prime number. 6. Programs to print the factorial of a number and the Fibonacci series up to a given number using recursion. 7. A

Uploaded by

Farhan Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Program

No.1
AIM:
Introduction to Object Oriented Programming. Discuss features of OOP and Java along with
the Compilation and Execution Process.

THEORY:
The object-oriented programming is basically a computer programming design philosophy or
methodology that organizes/ models software design around data, or objects rather than
functions and logic. An object is referred to as a data field that has unique attributes and
behavior. Everything in OOP is grouped as self-sustainable objects. It is the most popular
programming model among developers. It is well suited for programs that are large,
complex, and actively updated or maintained. It simplifies software development and
maintenance by providing major concepts such as abstraction, inheritance, polymorphism,
and encapsulation. These core concepts support OOP.

Some of the key features of OOPs in Java include:

1. Encapsulation: This is the process of hiding the implementation details of a class and
exposing only the necessary information. This helps in maintaining the security and
integrity of the data.
2. Inheritance: This feature allows a new class to inherit properties and methods of an
existing class. It helps in reusing code and creating a hierarchy of classes.
3. Polymorphism: This is the ability of objects of different classes to be used
interchangeably. It allows multiple objects to respond to the same message or method
call in different ways
4. Abstraction: This feature enables you to focus on the essential features of an object
and ignore the details that are not necessary. This helps in reducing the complexity of
the code.
5. Class and Objects: In Java, everything is an object, and classes are used to create
objects. A class is a blueprint or a template for creating objects, and it contains data
and methods.
6. Method Overloading: This is a feature that allows a class to have multiple methods
with the same name but with different parameters. This helps in providing flexibility
and ease of use to the programmer.Dynamic Binding: This feature allows the selection
of the appropriate method to be done at runtime rather than at compile-time. This
helps in achieving polymorphism and flexibility in the code.
Compilation and Execution Process
1. Writing the Java code: First, the programmer writes the Java code in a text editor, such as
Notepad, Eclipse, or IntelliJ IDEA.
2. Compilation: Once the code is written, it needs to be compiled using the Java compiler
(javac). The compiler checks the syntax of the code, converts the source code into bytecode
and generates class files for each class in the code. The bytecode is platform-independent,
which means that it can be run on any system that has a Java Virtual Machine (JVM)
installed.

3. Loading: After the compilation, the class files are loaded by the JVM. The JVM loads the
class files as needed during the execution of the program.

4. Execution: Once the bytecode has been verified, the JVM starts executing the program. It
interprets the bytecode and runs the instructions in the program.
OUTPUT
Program
No.2
AIM:
Write a program to print “Hello World” in Java.

THEORY:
To create a simple Java program, you need to create a class that contains the main
method. Let's understand the requirements first. For executing any Java program, the
following software or application must be properly installed.

● Install the JDK if you don't have it, download the JDK and install it.
● Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
● Create the Java program
● Compile and run the Java program

CODE:
class Solution{

public static void main(String[] args)

{ System.out.println("Hello,

World!");

}
}
OUTPUT
Program No.3

AIM:
Write a program to perform the addition of two numbers using Command Line arguments.

THEORY:
The command-line arguments are passed to the program at run-time. Passing command-line
arguments in a Java program is quite easy. They are stored as strings in the String array
passed to the args[] parameter of the main() method in Java. In Java, finding the sum of two
or more numbers is very easy. First, declare and initialize two variables to be added.
Another variable to store the sum of numbers. Apply mathematical operator (+) between the
declared variable and store the result. The following program calculates and prints the sum
of two numbers.

CODE:
class Solution{

public static void main(String[] args){

int a =

Integer.parseInt(args[0]); int b

= Integer.parseInt(args[1]); int

sum = a + b;
System.out.println(sum);

}
}

OUTPUT
Program No.4
AIM:
Write a program to perform the addition of two numbers using Scanner Class.

THEORY:

There are two ways to find the sum of two numbers in Java.

● By using User-defined Method


● By using sum()

Method By Using User-


defined Method

The Java Scanner class allows us to read input from the user. We take two numbers as input
and pass them to the user-defined method sum(). The following program calculates the sum
of two numbers using the method and prints the result.

By Using Integer.sum() Method

The Integer class provides the sum() method. It is a static method that adds two integers
together as per the + operator. It can be overloaded and accepts the arguments in int, double,
float, and long.

CODE:
import java.util.*;

class Exp4{

public static void main(String args[]){

int a, b, sum;

Scanner s = new

Scanner(System.in);

System.out.print("a: ");

a = s.nextInt();

System.out.print("b:

"); b = s.nextInt();

sum = a + b;

System.out.println("Result: " +

sum)

}
OUTPUT
Program No.5
AIM:
Generate a random number up to 100 and print whether it is prime or not.

THEORY:

Random numbers are the numbers that use a large set of numbers and selects a number using
the mathematical algorithm. It satisfies the following two conditions:

● The generated values uniformly distributed over a definite interval.


● It is impossible to guess the future value based on current and past values.

Using the Math.random() Method

The Java Math class has many methods for different mathematical operations. One of them is
the random() method. It is a static method of the Math class. We can invoke it directly. It
generates only double type random numbers greater than or equal to 0.0 and less than 1.0. It
does not accept any parameter. It returns a pseudorandom double that is greater than or equal
to 0.0 and less than 1.0.

CODE:
class exp1{

public static void main(String[] args)

{ double num = Math.random();

int myrandInt = (int)(num*100 + 1);

System.out.println("Random Number between 1 and 100 : "+myrandInt);

boolean flag=true;

for(int i=2; i<=myrandInt/2; i++)

{ if(myrandInt%i==0)

{ System.out.println("Not a Prime

Number!"); flag=false;

break;
}

if(flag){

System.out.println("The number is Prime.");

OUTPUT
Program No. 6
AIM:
a) To print factorial of a number.
b) To print fibonacci series of a given number.

THEORY:

Factorial of a whole number 'n' is defined as the product of that number with every whole
number less than or equal to 'n' till 1. For example, the factorial of 4 is 4 × 3 × 2 × 1, which is
equal to 24. It is represented using the symbol '!' So, 24 is the value of 4!.

The Fibonacci sequence is a type series where each number is the sum of the two that
precede it. It starts from 0 and 1 usually. The Fibonacci sequence is given by 0, 1, 1, 2, 3, 5,
8, 13, 21, 34, 55, 89, 144, and so on. The numbers in the Fibonacci sequence are also called
Fibonacci numbers.

What is Recursion?

The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function. Using a recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A recursive function
solves a particular problem by calling a copy of itself and solving smaller subproblems of the
original problems.
CODE:
import java.util.Scanner;

public class Prog6 {


static int fact(int x) {
if (x <= 1)
return 1;
return x * fact(x - 1);
}

static int fib(int x) {


if (x <= 1)
return x;
return fib(x - 1) + fib(x - 2);
}

public static void main(String args[]) {

int k;
Scanner s = new Scanner(System.in);
System.out.print("Enter the n :");
k = s.nextInt();
int x = fact(k);
System.out.print("Factorial of a : ");
System.out.println(x);

int a;
System.out.print("Enter the n :");
a = s.nextInt();
System.out.print("Fibo series : ");

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


int b = fib(i);
System.out.print(b + " ");
}
}
}
OUTPUT
Program No. 7
AIM:

To make a basic menu driven calculator program using Java.

THEORY:

Create a simple calculator which can perform basic arithmetic operations like addition,
subtraction, multiplication or division depending upon the user input. In this program, made
a simple calculator using switch..case in Java.

CODE:
import java.util.*;

class Prog7{

public static void main(String args []){

int a,b,result = 0;

Scanner sc = new Scanner(System.in);


System.out.print("Enter a : ");
a = sc.nextInt();
System.out.print("Enter b : ");
b = sc.nextInt();

System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.print("Enter your choice : ");
int choice = sc.nextInt();

switch (choice) {
case 1:
result = a+b;
break;
case 2:
result = a-b;
break;
case 3:
result = a*b;
break;
case 4:
result = a/b;
break;
default:
System.out.println("Invalid Operation");
break;
}
System.out.println("Answer is " + result);
}
}

OUTPUT
Program
No. 8
AIM:

To demonstrate different types on variable available in Java.

THEORY:

There are three types of variables in Java:

local variable
instance variable
static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.

CODE:
class A {
int a = 5;
static int b = 6;
public static void main(String[] args) {
A a1 = new A();
int c =1265;
System.out.println("Local variable C " + c);
System.out.println("B " + b);
// Error line below
// System.out.println("static variable A " + a);
System.out.println("Instance variable A1 " + a1.a);
}
}

Program No. 9
AIM:

Write a program to output Sum and mean of a Array.

THEORY:

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, 2nd
element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we
need to use the sizeof operator.

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 multidimensional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
CODE:
import java.util.Scanner;

public class Prog9 {


public static void main(String []args) {
Scanner sc = new Scanner(System.in);

int size;
System.out.print("Enter size of array : ");
size = sc.nextInt();

int a[] = new int[size];// declaration and instantiation

for (int i = 0; i < a.length; i++) {


System.out.print("Enter Array element " + (i + 1) + " : ");
a[i] = sc.nextInt();
}

System.out.println("Your array is ");

for (int i = 0; i < a.length; i++) {// length is the property of array
System.out.print(a[i] + " ");
}

sc.close();

System.out.println(" ");

int sum = 0;

for (int i = 0; i < a.length; i++) {// length is the property of array
sum += a[i];
}

double avg = sum / a.length;

System.out.println("Sum of array is "+ sum);


System.out.println("Average of array is "+ avg);
}
}

OUTPUT
Program No. 10
AIM:

Write a program to perform any type of sort on a Array.

THEORY:

Sorting is the process of arranging the elements of an array so that they can be placed either
in ascending or descending order. For example, consider an array A = {A1, A2, A3, A4, ??
An }, the array is called to be in ascending order if element of A are arranged like A1 > A2 >
A3 > A4 > A5 > ? > An .

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like
the movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly,
the array elements in bubble sort move to the end in each iteration.

CODE:
import java.util.*;

public class Prog10 {

public static void sort(int [] arr){


for (int i = 0; i < arr.length; i++) {

for (int j = i + 1; j < arr.length; j++) {

int temp = 0;
if (arr[j] < arr[i]) {

temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

System.out.print(arr[i] + " ");


}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int size;
System.out.print("Enter size of array : ");
size = sc.nextInt();

int a[] = new int[size];// declaration and instantiation

for (int i = 0; i < a.length; i++) {


System.out.print("Enter Array element " + (i + 1) + " : ");
a[i] = sc.nextInt();
}

System.out.println("Your array is ");

for (int i = 0; i < a.length; i++) {// length is the property of array
System.out.print(a[i] + " ");
}

sc.close();

System.out.println("\nSorted array is ");


sort(a);
}
}

OUTPUT
Program No. 11
AIM:

Write a program to add Two matrix and output resultant matrix using Java.

THEORY:

In Java, a 2D array is a data structure that allows you to store elements in a grid format with
rows and columns. It is essentially an array of arrays, where each element is itself an array.
The two dimensions of a 2D array can be visualized as a grid or a table. In Java, you can
declare a 2D array using the syntax

datatype[][] arrayname = new datatype[rows][columns].

You can access the elements of a 2D array using the row and column indices. For example,
arrayname[0][0] refers to the element at the first row and first column of the array. 2D arrays
in Java can be used to represent matrices, game boards, and other types of grids or tables.
They are useful when you need to organize and manipulate data in a two-dimensional space.

CODE:
import java.util.Scanner;

public class Prog11 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int a[][] = new int[3][3];


int b[][] = new int[3][3];
int res[][] = new int[3][3];

System.out.println("Enter matrix 1");

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


for (int j = 0; j < 3; j++) {
System.out.print("Enter element " + (i + 1) + " " + (j + 1) + " : ");
a[i][j] = sc.nextInt();
}
}

System.out.println("Enter matrix 2");

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


for (int j = 0; j < 3; j++) {
System.out.print("Enter element " + (i + 1) + " " + (j + 1) + " : ");
b[i][j] = sc.nextInt();
}
}

System.out.println("Matrix 1 is : ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}

System.out.println("Matrix 2 is : ");

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


for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}

System.out.println("Resultant Matrix is : ");

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


for (int j = 0; j < 3; j++) {
res[i][j] = a[i][j] + b[i][j];
System.out.print(res[i][j] + " ");
}
System.out.print("\n");
}

sc.close();

}
}

OUTPUT
Program
No. 12
AIM:

Write a program to calculate perimeter and area of a Rectangle.

THEORY:

You can use the following formulas to calculate the area and perimeter of the rectangle:

● Area = length x width


● Perimeter = 2 x (length + width)

CODE:
import java.util.Scanner;

public class Prog12 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter length : ");


int l = sc.nextInt();
System.out.print("Enter breadth : ");
int b = sc.nextInt();

Rectangle r = new Rectangle(l, b);


System.out.println("Area " + r.Area());
System.out.println("Perimeter " + r.Perimeter());
sc.close();
}
}

class Rectangle {
int length;
int breadth;
Rectangle(int l, int b) {
this.length = l;
this.breadth = b;
}

int Area() {
return length * breadth;
}

int Perimeter() {
return 2 * (length + breadth);
}
}

OUTPUT
Program
No. 13
AIM:

Write a program in Java to perform constructor overloading.

THEORY:
Constructor overloading is a feature in Java that allows the creation of multiple constructors
with different parameter lists. This means that a class can have multiple constructors with
different arguments, and the appropriate constructor will be called depending on the
arguments used to create an object.

Constructor overloading is useful when a class needs to be initialized in different ways. For
example, a class that represents a person might have a constructor that takes only the person's
name as an argument, and another constructor that takes the person's name and age.

CODE:
public class Student {
//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}

public static void main(String[] args) {


//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

OUTPUT
Program No. 14
AIM:

Write a program in Java to perform single-level inheritance

THEORY:
Single-level inheritance is a type of inheritance in Java where a subclass or child class extends
a single superclass or parent class. In this type of inheritance, a class is derived from only one
parent class, and that parent class can also have only one direct child.

The child class inherits all the non-private members of its parent class, including fields,
methods, and nested classes. The child class can add new methods and fields, or modify the
inherited methods, to extend or specialize the functionality of the parent class.

CODE:
class Animal {
protected String species;

public Animal(String species) {


this.species = species;
}

public void makeSound() {


System.out.println("The " + species + " makes a sound.");
}
}

class Dog extends Animal {


public Dog() {
super("Dog");
}

public void bark() {


System.out.println("Woof!");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound();
myDog.bark();
}
}
OUTPUT
Program No. 15
AIM:

Write a program in Java to perform Multilevel inheritance.

THEORY:
Multilevel inheritance in Java is a type of inheritance where a subclass is derived from a
superclass, which is itself derived from another superclass. In other words, it involves
extending a class that has already been extended. This creates a hierarchy of classes, with each
class inheriting properties and methods from its parent class(es).

For example, consider a class hierarchy where class A is the superclass of class B, and class B
is the superclass of class C. In this case, class C will inherit properties and methods from both
class B and class A. This allows for code reuse and promotes the concept of code
organization, as classes can be grouped together in a logical hierarchy

CODE:
class Animal {
void eat() {
System.out.println("Called from top class");
System.out.println("Animal is eating");
}
}

class Mammal extends Animal {


void walk() {
System.out.println("Called from middle class");
System.out.println("Mammal is walking");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("Called from bottom class");
System.out.println("Dog is barking");
}
}

public class Prog15{


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.walk();
myDog.bark();
}
}

OUTPUT
Program No. 16
AIM:

Write a program in Java to perform Hierarchical inheritance.

THEORY:
Hierarchical inheritance is a type of inheritance where one parent class is inherited by multiple
child classes. This means that multiple subclasses inherit properties and methods from a single
superclass. The parent class defines the common attributes and behaviors, while the child
classes add their own unique attributes and behaviors.
For example, a "Vehicle" superclass can be inherited by "Car", "Bus", and "Truck" subclasses.
Each of these subclasses can add their own unique properties and methods, such as
"numberOfDoors" for "Car", "numberOfSeats" for "Bus", and "cargoCapacity" for "Truck".
This way, the code can be organized in a hierarchical manner, with a common superclass
defining the general properties and behaviors, and multiple subclasses adding their own
specific properties and behaviors.

CODE:
class Shape {
void explain() {
System.out.println("It's a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Circle");
}
}

class Rectangle extends Shape {


void draw() {
System.out.println("Rectangle");
}
}

public class Prog16 {


public static void main(String[] args) {
Circle c = new Circle();
Rectangle r = new Rectangle();
c.explain();
c.draw();
r.explain();
r.draw();
}
}

OUTPUT
Program No. 17
AIM:

A. Write a program in Java to implement static polymorphism (Method Overloading).


B. Write a program in Java to implement dynamic polymorphism (Method overriding).

THEORY:
Polymorphism is a fundamental concept in object-oriented programming (OOP) that refers to
the ability of objects to take on multiple forms. In Java, there are two types of polymorphism:
static polymorphism and dynamic polymorphism.
● Static Polymorphism: Static polymorphism, also known as compile-time
polymorphism or method overloading, occurs when multiple methods in a class have
the same name but different parameters. The compiler determines which method to
call based on the number, type, and order of the parameters passed in
● Dynamic Polymorphism: Dynamic polymorphism, also known as run-time
polymorphism or method overriding, occurs when a subclass overrides a method of its
parent class. The method of the subclass must have the same name, return type, and
parameter list as the method of the parent class.

CODE:
class Math {
public static int add(int x, int y) {
return x + y;
}

public static double add(double x, double y) {


return x + y;
}
}

class Animal {
void sound() {
System.out.println("Animal is making a sound");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat is meowing");
}
}

public class Prog17 {


public static void main(String[] args) {
//static
System.out.println(Math.add(1, 2));
System.out.println(Math.add(2.5, 3.5));

//Dynamic
Animal a = new Animal();
Cat c = new Cat();
a.sound(); // calls the sound() method of Animal class
c.sound(); // calls the sound() method of Cat class
}

OUTPUT
Program No. 18
AIM:

Write a program to demonstrate the use of the final keyword with data member, function, and
class.

THEORY:
● In Java, the final keyword is used to indicate that a variable, method, or class cannot
be modified or subclassed once it has been defined.
● When applied to a variable, the final keyword makes it a constant, meaning that its
value cannot be changed. This is useful for defining values that should not be
modified, such as mathematical constants or configuration settings.
● When applied to a method, the final keyword indicates that the method cannot be
overridden by a subclass. This is useful for defining methods that should not be
modified or that have a specific implementation that should not be altered.
● When applied to a class, the final keyword indicates that the class cannot be
subclassed. This is useful for defining classes that should not be extended or modified,
such as utility classes or classes with a specific implementation that should not be
altered.

CODE:
class Bike {
final int speedlimit = 90;// final variable

void run() {
speedlimit = 400;
}

final void walk() {


System.out.println("walking"); // final method
}
}

class Honda extends Bike {


void walk() {
System.out.println("walk");
}
}

final class Car { // final class


}

class Maruti extends Car {


void run() {
System.out.println("running safely with 100kmph");
}
}

public class Prog18 {


public static void main(String[] args) {
Bike obj=new Bike();
obj.run();

Honda honda = new Honda();


honda.run();

Maruti maruti = new Maruti();


maruti.run();
}
}

OUTPUT
Program No. 19
AIM:

Write a program to implement multiple inheritance in Java through

THEORY:
● Multiple inheritance is a feature of object-oriented programming (OOP) languages
that allows a class to inherit from more than one base class. This means that a derived
class can have characteristics and behaviors of multiple parent classes.

● The primary advantage of multiple inheritance is code reuse. By inheriting from


multiple base classes, a derived class can reuse the code from each base class, instead
of having to re-implement that code.

● However, multiple inheritance can also introduce complexity and potential conflicts.
For example, if two base classes have methods with the same name, the derived class
may inherit both methods and it may be unclear which one should be used in a
particular situation.

● To address these issues, some OOP languages provide features such as method
resolution order (MRO) and virtual inheritance. MRO determines the order in which
methods are searched for in a multiple inheritance hierarchy, while virtual inheritance
allows for shared base classes to be inherited only once by a derived class.

● Overall, multiple inheritance can be a powerful tool in OOP, but it should be used
judiciously to avoid creating overly complex and difficult-to-maintain code.

CODE:
interface AnimalEat {
void eat();
}

interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}

public void travel() {


System.out.println("Animal is travelling");
}
}

public class Prog19 {


public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}

OUTPUT
Program
No. 20
AIM:

Write a program to implement ‘Abstract’ class in Java

THEORY:
In Java, an abstract class is a class that cannot be instantiated directly and serves as a base class for
other classes to extend and implement. An abstract class is declared using the abstract keyword in its
class definition.

Abstract classes can contain both abstract and non-abstract methods. Abstract methods are declared
without an implementation and must be implemented by any concrete class that extends the abstract
class. Non-abstract methods can also be included in the abstract class and can be used by the concrete
classes that extend it.

An abstract class can have instance variables and constructors, just like any other class. However, it
cannot be instantiated on its own. Instead, a concrete subclass must be created that extends the
abstract class and provides implementations for all the abstract methods.

The main purpose of an abstract class is to define a common interface for a group of related classes.
By defining the common methods and properties in the abstract class, the concrete classes that extend
it can be more easily designed and implemented. Abstract classes can also help to ensure that certain
methods are always implemented by subclasses and can enforce a certain level of consistency across
the derived classes.
It is important to note that while an abstract class cannot be instantiated, it can be used as a reference
type, allowing variables to hold references to subclasses of the abstract class. This allows for more
flexible and modular code design

CODE:
abstract class Bank {
abstract int getRateOfInterest();
}

class SBI extends Bank {


int getRateOfInterest() {
return 7;
}
}

class PNB extends Bank {


int getRateOfInterest() {
return 8;
}
}

public class Prog20{


public static void main(String args[]) {
Bank b;
b = new SBI();
System.out.println("Rate of Interest is: " + b.getRateOfInterest() + " %");
b = new PNB();
System.out.println("Rate of Interest is: " + b.getRateOfInterest() + " %");
}
}

OUTPUT
Program No. 21
AIM:

Write a program to show the use of ‘static’ class in Java.

THEORY:
In Java, a static class is a nested class that has been declared with the static modifier. A static class
can be accessed without creating an instance of the outer class that it is nested within.

Static classes are commonly used for utility classes, which contain only static methods and constants.
These classes can be used to group related functionality together and to provide a namespace for the
methods and constants.

Because static classes do not require an instance of the outer class, they can be used to create code
that is more modular and easier to test. They can also be used to prevent accidental modification of
the instance variables of the outer class.

One important thing to note is that a static class can only access static members of the outer class. It
cannot access non-static members of the outer class, since those belong to an instance of the outer
class.

Static classes can also be used as private inner classes to encapsulate implementation details of the
outer class, while still allowing the outer class to expose a public API. In this case, the static class can
only be accessed within the context of the outer class.

Overall, static classes in Java provide a powerful tool for creating modular and encapsulated code, and
are commonly used for utility classes and private inner classes

CODE:
public class Prog21
{
private static String s= "Static class called";
//Static and nested class
static class StaticNestedClass
{
//non-static method of the nested class
public void show()
{
//prints the string defined in base class
System.out.println(s);
}
}
public static void main(String args[])
{
Prog21.StaticNestedClass obj = new Prog21.StaticNestedClass();
//invoking the method of the nested class
obj.show();
}
}

OUTPUT
Program
No. 22
AIM:

Write a program to demonstrate the use of following keywords: try, catch ,throw, throws,
finally

THEORY:
try: The try keyword is used to specify a block of code where an exception might occur. This block of
code is often referred to as the "try block". The purpose of the try block is to detect exceptions and
handle them appropriately. If an exception is thrown in the try block, the control is passed to the
nearest catch block.

catch: The catch keyword is used to specify a block of code that handles the exception that is thrown
in the try block. This block of code is often referred to as the "catch block". A catch block specifies
the type of exception that it can handle, so that the exception is caught only if it matches the specified
type.

throw: The throw keyword is used to throw an exception explicitly from a block of code. This
keyword is used to indicate that an exceptional condition has occurred and that the responsibility for
handling the exception has been passed to the calling code.

throws: The throws keyword is used in the method signature to declare the exceptions that a method
might throw. This keyword is used to indicate that the method might throw an exception, and that the
caller of the method must handle the exception appropriately.

finally: The finally keyword is used to specify a block of code that is guaranteed to be executed,
regardless of whether an exception is thrown or not. This block of code is often referred to as the
"finally block". The purpose of the finally block is to release resources or clean up after the execution
of the try block.

CODE:
public class Prog22 {
public static void main(String[] args) {

try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Code that handles the exception
System.out.println("Error: " + e.getMessage());
} finally {
// Code that always runs, regardless of whether an exception was thrown or not
System.out.println("Program completed.");
}
}

public static int divide(int a, int b) throws ArithmeticException {


if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return a / b;
}

OUTPUT

You might also like