Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

java lab program with output

from my friend

Uploaded by

ankithakarmanchi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

java lab program with output

from my friend

Uploaded by

ankithakarmanchi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 1:
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
read from command line arguments).

Aim: Program to perform addition of two matrices using array.


Learning Objectives: To learn primitive constructs Java programming language
Course outcome:
CO1: Demonstrate proficiency in writing simple programs involving branching and looping
structures.
Theory: An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index.

import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args)
{
int m, n;
int a[][], b[][], c[][];
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the size of matrix(row, col) : ");
m = scanner.nextInt();
n = scanner.nextInt();
System.out.println("Enter the elements of first matrix");
a = readMatrix(m,n);
System.out.println("Enter the elements of second matrix");
b = readMatrix(m,n);
c = addMatrix(a,b);
System.out.println("Result");
printMatrix(c);
}

public static int[][] readMatrix(int m, int n)


{
Scanner scanner = new Scanner(System.in);
int a[][] = new int[m][n];
for ( inti = 0; i< m; i++ )
for ( int j = 0; j < n; j++ )

De Dept. of AI&DS, GSSSIETW, Mysuru


1
3rd Sem–Object Oriented Programming with Java [BCS306A]

a[i][j] = scanner.nextInt();
return a;
}

public static void printMatrix(int a[][])


{
for ( inti = 0; i<a.length; i++ )
{
for ( int j = 0; j < a[0].length; j++ )
System.out.print(a[i][j] + "");

System.out.println();
}
}

public static int[][] addMatrix(int a[][], int b[][])


{
int c[][] = new int[a.length][a[0].length];
for ( inti = 0; i<a.length; i++ )
for ( int j = 0; j < a[0].length; j++ )
c[i][j] = a[i][j] + b[i][j];
return c;
}
}

Output:

Enter the size of matrix(row, col) :


22
Enter the elements of first matrix
23
45
Enter the elements of second matrix
41
24

Result
64
69

De Dept. of AI&DS, GSSSIETW, Mysuru


2
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 2:
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.
Aim: The aim of this program is to implement a basic stack data structure in Java that can hold
a maximum of 10 integers.
Learning Objectives: To learn primitive constructs Java programming language
Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:

Stack: A stack stores data using first-in, last-out ordering. That is, a stack is like a stack of plates
on a table—the first plate put down on the table is the last plate to be used. Stacks are controlled
through two operations traditionally called push and pop. To put an item on top of the stack, you
will use push. To take an item off the stack, you will use pop.

Stack operations: The method push( ) puts an item on the stack. To retrieve an item, call pop( ).
Since access to the stack is through push( ) and pop( ), the fact that the stack is held in an array is
actually not relevant to using the stack. For example, the stack could be held in a more
complicated data structure, such as a linked list, yet the interface defined by push( ) and pop( )
would remain the same.

De Dept. of AI&DS, GSSSIETW, Mysuru


3
3rd Sem–Object Oriented Programming with Java [BCS306A]

//Stack.java
public class Stack
{
final int MAX = 10;
int s[] = new int[MAX];
int top = -1;

void push(int element)


{
if ( top>= MAX-1 )
System.out.println("Stack overflow");
else
s[++top] = element;
}
int pop()
{
int element = 0;
if ( top == -1 )
System.out.println("Stack underflow");
else
element = s[top--];
return element;
}
void display()
{
if ( top == -1 )
System.out.println("Stack empty");
else
{
for ( inti = top; i> -1; i--)
System.out.println(s[i]+"");
}
}
}

import java.util.Scanner;
//StackDemo.java
public class StackDemo
{
public static void main(String args[])
{
Stack stack = new Stack();
System.out.println("Program to perform stack operations");

Scanner scanner = new Scanner(System.in);


while( true )

De Dept. of AI&DS, GSSSIETW, Mysuru


4
3rd Sem–Object Oriented Programming with Java [BCS306A]

{
System.out.println("1. push 2.pop 3. display 4.Exit");
System.out.println("Enter your choice");
int choice = scanner.nextInt();
int element = 0;
switch (choice)
{
case 1:
System.out.println("enter the element to be pushed");
element = scanner.nextInt();
stack.push(element);
break;
case 2:
element = stack.pop();
System.out.println("the poped element is" + element);
break;
case 3:
System.out.println("elements in the stack are");
stack.display();
break;
case 4:
return;
}
}
}
}

De Dept. of AI&DS, GSSSIETW, Mysuru


5
3rd Sem–Object Oriented Programming with Java [BCS306A]

Output:

Program to perform stack operations


1. push 2.pop 3. display 4.Exit
Enter your choice
1
enter the element to be pushed
12
1. push 2.pop 3. display 4.Exit
Enter your choice
1
enter the element to be pushed
13
1. push 2.pop 3. display 4.Exit
Enter your choice
1
enter the element to be pushed
14
1. push 2.pop 3. display 4.Exit
Enter your choice
3
elements in the stack are
14
13
12
1. push 2.pop 3. display 4.Exit
Enter your choice
2
the poped element is14
1. push 2.pop 3. display 4.Exit
Enter your choice
2
the poped element is13
1. push 2.pop 3. display 4.Exit
Enter your choice
2
the poped element is12
1. push 2.pop 3. display 4.Exit
Enter your choice
2
Stack underflow
the poped element is0
1. push 2.pop 3. display 4.Exit
Enter your choice
3

De Dept. of AI&DS, GSSSIETW, Mysuru


6
3rd Sem–Object Oriented Programming with Java [BCS306A]

elements in the stack are


Stack empty
1. push 2.pop 3. display 4.Exit
Enter your choice
4

De Dept. of AI&DS, GSSSIETW, Mysuru


7
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 3:
A class called Employee, which models an employee with an ID, name and salary, is designed as
shown in the following class diagram. The method raiseSalary (percent) increases the salary by
the given percentage. Develop the Employee class and suitable main method for demonstration.

Aim: This program is to model an Employee class that represents employees with an ID, name,
and salary.

Learning Objectives: To understand Object Oriented Programming Features of JAVA.

Course outcome:
CO2: Design a class involving data members and methods for the given scenario.
Theory:
class is a template for an object, and an object is an instance of a class.

Methods:
Methods define the behavior of an object. They represent actions that objects of a class can perform. In
Java, you define methods within a class.

Data Members (Fields):


Fields represent the attributes or properties of an object. They store the state of an object. In Java,
you declare fields within a class.

//Employee.java
public class Employee {
private int id;
private String name;
private int salary;

public Employee(int id, String name, int salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public int raiseSalary(int percent)


{
return this.salary + this.salary * percent / 100;

De Dept. of AI&DS, GSSSIETW, Mysuru


8
3rd Sem–Object Oriented Programming with Java [BCS306A]

}
}

//EmployeeDemo.java
import java.util.Scanner;

public class EmployeeDemo {


public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int id;
String name;
int salary;

System.out.println("Enter employee id, name, salary");


id = scanner.nextInt();
name = scanner.next();
salary = scanner.nextInt();

Employee employee = new Employee(id,name,salary);

System.out.println("Enter percent raise");


int percent = scanner.nextInt();
int raisedSalary = employee.raiseSalary(percent);
System.out.println("Raised salary : " + raisedSalary);
}
}

Output:

Enter employee id, name, salary


E123
Amrutha
60000

Enter percent raise


15

Raised salary: 69000

De Dept. of AI&DS, GSSSIETW, Mysuru


9
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 4:
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x,y)".
● A method called distance(int x, int y) that returns the distance from this point to another point
at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin
(0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to
test all the methods defined in the class

Aim: The aim of the provided program is to create a class called MyPoint that models a 2D
point with x and y coordinates, and then develop a Java program (TestMyPoint) to test all the
methods defined in the MyPoint class.

Learning Objectives: To understand Object Oriented Programming Features of JAVA.

Course outcome:

CO2: Design a class involving data members and methods for the given scenario.

Theory:
The MyPoint class is designed to represent and manipulate points in a 2D plane. The class
includes various constructors and methods for setting coordinates, getting coordinates,
calculating distances, and generating a string representation of a MyPoint instance.

Constructor:
A constructor initializes an object immediately upon creation. It has the same name as
the class in which it resides and is syntactically similar to a method.

De Dept. of AI&DS, GSSSIETW, Mysuru


10
3rd Sem–Object Oriented Programming with Java [BCS306A]

Once defined, the constructor is automatically called when the object is created, before the new
operator completes.

Overloading Methods:
In Java, it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism. If you have never used
a language that allows the overloading of methods, then the concept may seem strange at first.
But as you will see, method overloading is one of Java’s most exciting and useful features.

Default Constructor:
In Java, a default constructor explicitly defined in a class. The default constructor has no
parameters and initializes the object with default is a special type of constructor that is
automatically provided by the compiler if no other constructor is values.
Key points about default constructors:

1. No Parameters: The default constructor does not take any parameters.


2. Access Modifier: The access modifier for the default constructor is typically public to
ensure that it can be accessed from outside the class.
3. Automatic Creation: If you don't provide any constructor in your class, Java
automatically adds a default constructor during compilation.
4. Initialization: You can include initialization code within the default constructor
to set default values for the object's instance variables.
// MyPoint.java
public class MyPoint {
int x;
int y;

public MyPoint()
{
this.x = 0;
this.y = 0;
}

De Dept. of AI&DS, GSSSIETW, Mysuru


11
3rd Sem–Object Oriented Programming with Java [BCS306A]

public MyPoint(int x, int y)


{
this.x = x;
this.y = y;
}

public void setX(int x)


{
this.x = x;
}

public void setY(int y)


{
this.y = y;
}

public int getX()


{
return this.x;
}

public int getY()


{
return this.y;
}

public double distance()


{
double dist = 0.0;
dist= Math.sqrt(this.x * this.x + this.y * this.y);
return dist;
}

public double distance(int x, int y)


{
double dist = 0.0;

double xdiff = this.x - x;


double ydiff = this.y - y;

dist = Math.sqrt(xdiff * xdiff + ydiff * ydiff);


return dist;
}

public double distance(MyPoint point)

De Dept. of AI&DS, GSSSIETW, Mysuru


12
3rd Sem–Object Oriented Programming with Java [BCS306A]

{
double dist = 0.0;

double xdiff = this.x - point.getX();


double ydiff = this.y - point.getY();

dist = Math.sqrt(xdiff * xdiff + ydiff * ydiff);

return dist;
}

public String toString()


{
return "(" + this.x + "," + this.x + ")";
}
}

import java.util.Scanner;

public class PointDemo {


public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int choice = 0;
int x, y;
double distance = 0;

System.out.println("Enter the co-ords of Point under consideration");


x = scanner.nextInt();
y = scanner.nextInt();
MyPoint point = new MyPoint(x,y);

while (true)
{
System.out.println("1. Distance to origin");
System.out.println("2. Distance from point (x,y)");
System.out.println("3. Distance from Point object");
System.out.println("0. Exit");
System.out.println("Enter your choice : ");
choice = scanner.nextInt();

switch ( choice )
{
case 1 :
distance = point.distance();

De Dept. of AI&DS, GSSSIETW, Mysuru


13
3rd Sem–Object Oriented Programming with Java [BCS306A]

break;

case 2 :
System.out.println("Enter coordinates of other point");
x = scanner.nextInt();
y = scanner.nextInt();
distance = point.distance(x,y);
break;

case 3:
System.out.println("Enter coordinates of other point");
x = scanner.nextInt();
y = scanner.nextInt();
MyPoint point1 = new MyPoint(x,y);
distance = point.distance(point1);
break;

case 0:
return;
}
System.out.println("Distance : " + distance);
}
}
}

De Dept. of AI&DS, GSSSIETW, Mysuru


14
3rd Sem–Object Oriented Programming with Java [BCS306A]

Output:
Enter the co-ords of Point under consideration
1
2
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice :
1
distance: 2.23606797749979
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice:
2
Enter coordinates of other point
6
8
distance: 7.810249675906654
1. Distance to origin:
2. Distance from point (x,y)
3. Distance from Point object
0. Exit
Enter your choice:
3
Enter coordinates of other point
5
6
Distance: 5.656854249492381

De Dept. of AI&DS, GSSSIETW, Mysuru


15
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 5:
Develop a JAVA program to create a class named shape. Create three sub classes namely: circle,
triangle and square, each class has two member functions named draw () and erase ().
Demonstrate polymorphism concepts by developing suitable methods, defining member data and
main program.

Aim: The aim of this Java program is to demonstrate polymorphism by creating a class
hierarchy for geometric shapes. The base class Shape contains two methods, draw() and erase(),
and three subclasses (Circle, Triangle, and Square) inherit from it. Each subclass overrides the
draw() and erase() methods to provide their own implementation.

Learning Objectives: To understand Object Oriented Programming Features of JAVA.

Course outcome:

CO2: Design a class involving data members and methods for the given scenario.

Theory:
1. Polymorphism:

 Compile-time (Static) Polymorphism: Also known as method overloading, it occurs


when there are multiple methods in the same class with the same name but different
parameter types or a different number of parameters.

 Runtime (Dynamic) Polymorphism: It is achieved through method overriding.


Subclasses provide a specific implementation of a method defined in their superclass.

2. Member Functions (Methods):

Member functions are methods defined within a class. They represent the behavior or
actions that objects of the class can perform.

3. Data Members (Fields):

Data members are variables declared within a class. They represent the state or attributes of
objects of the class.

De Dept. of AI&DS, GSSSIETW, Mysuru


16
3rd Sem–Object Oriented Programming with Java [BCS306A]

public class Circle implements Shape {


public void draw()
{
System.out.println("Circle.draw() ...");
}
public void erase()
{
System.out.println("Circle.erase() ...");
}
}
public interface Shape {
public void draw();
public void erase();
}

public class ShapeDemo {


public static void main(String[] args)
{
Shape shape;

shape = new Circle();


shape.draw();
shape.erase();

shape = new Triangle();


shape.draw();
shape.erase();

shape = new Square();


shape.draw();
shape.erase();
}
}
public class Square implements Shape {
public void draw()
{
System.out.println("Square.draw() ...");
}
public void erase()
{
System.out.println("Square.erase() ...");
}
}

public class Triangle implements Shape {

De Dept. of AI&DS, GSSSIETW, Mysuru


17
3rd Sem–Object Oriented Programming with Java [BCS306A]

public void draw()


{
System.out.println("Triangle.draw() ...");
}
public void erase()
{
System.out.println("Triangle.erase() ...");
}

Output:

circle.draw( )…
circle.erase( )…
triangle.draw( )…
triangle.erase( )…
square.draw( )…
square.erase( )…

De Dept. of AI&DS, GSSSIETW, Mysuru


18
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 6:
Develop a Java program to create an abstract class Shape with abstract methods calculateArea()
and calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and perimeter of each shape.

Aim: The program is to demonstrate the concept of abstract classes and abstract methods. The
program defines an abstract class Shape with two abstract methods: calculateArea() and
calculatePerimeter().

Learning Objectives: To understand Object Oriented Programming Features of JAVA.

Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems.
Theory:

Subclass:

A subclass, also known as a derived class or child class, is a class that inherits properties and
behaviors from another class called the super-class or parent class. The subclass can extend the
functionality of the super-class by adding new methods or overriding existing methods.

Abstract Method:

An abstract method is a method declared without an implementation in an abstract class.


Abstract methods are meant to be implemented by concrete subclasses. An abstract method is
marked with the abstract keyword and ends with a semicolon instead of a method body.

Abstract Class:

An abstract class is a class that cannot be instantiated on its own. It may contain abstract methods
(methods without a body) that must be implemented by concrete subclasses. Abstract classes can
also have concrete methods with an implementation. Abstract classes provide a way to define a
common interface for a group of related classes.

De Dept. of AI&DS, GSSSIETW, Mysuru


19
3rd Sem–Object Oriented Programming with Java [BCS306A]

public class Circle extends Shape {

private int radius;

public Circle(int radius) {


this.radius = radius;
}

@Override
public float calculatePerimeter() {
return (float) (2 * Math.PI * radius);
}

@Override
public float calculateArea() {
return (float) (Math.PI * radius * radius );
}

}
public abstract class Shape {
public abstract float calculatePerimeter();
public abstract float calculateArea();

import java.util.Scanner;

public class ShapeDemo {


public static void main(String[] args)
{
int option = 0;
int radius;
int a;
int b;
int c;

float perimeter;
float area;

Scanner scanner = new Scanner(System.in);


System.out.println("1. Circle");
System.out.println("2. Triangle");
System.out.println("Enter your option : ");
option = scanner.nextInt();

Shape shape;

De Dept. of AI&DS, GSSSIETW, Mysuru


20
3rd Sem–Object Oriented Programming with Java [BCS306A]

switch ( option )
{
case 1 :
System.out.println("Enter radius : ");
radius = scanner.nextInt();
shape = new Circle(radius);
perimeter = shape.calculatePerimeter();
area = shape.calculateArea();
System.out.println("Perimeter : " + perimeter);
System.out.println("Area : " + area);
break;

case 2 :
System.out.println("Enter 3 sides of triangle : ");
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
shape = new Triangle(a,b,c);
perimeter = shape.calculatePerimeter();
area = shape.calculateArea();
System.out.println("Perimeter : " + perimeter);
System.out.println("Area : " + area);
break;

}
}

}
public class Triangle extends Shape {

private int a;
private int b;
private int c;

public Triangle(int a, int b, int c) {


this.a = a;
this.b = b;
this.c = c;
}

@Override
public float calculatePerimeter() {
return (float) (a + b + c);
}

De Dept. of AI&DS, GSSSIETW, Mysuru


21
3rd Sem–Object Oriented Programming with Java [BCS306A]

@Override
public float calculateArea() {
float s = (float)((a+b+c) / 2.0);
float area = (float)Math.sqrt(s * (s-a) * (s-b) * (s-c));
return area;
}
}

Output:

1. Circle
2. Triangle
Enter your option
1
Enter radius:
15
Perimeter: 94.24778
Area: 706.85834
Enter your option
2
Enter 3 sides of triangle
2
3
4
Perimeter:
Area:

De Dept. of AI&DS, GSSSIETW, Mysuru


22
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 7:
Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width)
and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods

Aim: The program is to demonstrate the use of interfaces and implementation of the Resizable
interface in a class. In this case, an interface named Resizable is defined with methods
resizeWidth(int width) and resizeHeight(int height) to allow an object to be resized. The program
then creates a class Rectangle that implements the Resizable interface and provides concrete
implementations for the resize methods.

Learning Objectives: To understand Object Oriented Programming Features of JAVA.

Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems
Theory:
Interface in Java:

An interface in Java is a collection of abstract methods. It represents a contract that a class must
adhere to by providing concrete implementations for all the methods declared in the interface.
Interfaces can also include constants (variables with the final modifier) and default methods
(methods with a default implementation).Resizable Interface:

In the provided program, the Resizable interface is defined with two abstract methods:
resizeWidth(int width) and resizeHeight(int height). These methods declare a contract that any
class implementing the Resizable interface must provide concrete implementations for resizing
an object's width and height.

Rectangle Class:

The Rectangle class implements the Resizable interface. It has two private fields, width and
height, to represent the dimensions of the rectangle. The class provides a constructor to initialize
these dimensions, as well as getter methods to retrieve them.

De Dept. of AI&DS, GSSSIETW, Mysuru


23
3rd Sem–Object Oriented Programming with Java [BCS306A]

public class Rectangle implements Resizable {

private int height;


private int width;

public Rectangle()
{

public Rectangle(int height, int width) {


this.height = height;
this.width = width;
}

@Override
public void resizeHeight(int height) {
this.height = height;
}

@Override
public void resizeWidth(int width) {
this.width = width;
}

public String toString()


{
return "Height : " + this.height + " Width : " + this.width;
}
}

import java.util.Scanner;

public class RectangleDemo {


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

int height = 0;
int width = 0;

System.out.println("Enter the height and width of rectangle");


height = scanner.nextInt();
width = scanner.nextInt();

De Dept. of AI&DS, GSSSIETW, Mysuru


24
3rd Sem–Object Oriented Programming with Java [BCS306A]

Rectangle rectangle = new Rectangle(height, width);


System.out.println(rectangle);

System.out.println("Enter the new height and width");


int newHeight = scanner.nextInt();
int newWidth = scanner.nextInt();

Resizable resizable = new Rectangle();


resizable.resizeHeight(newHeight);
resizable.resizeWidth(newWidth);

System.out.println(resizable);

}
}

public interface Resizable {


public void resizeHeight(int height);
public void resizeWidth(int width);

Output:

Enter the height and width of rectangle


23 76
Height: 23 Width: 78
Enter the new height and width
43 90
Height: 43 Width:90

De Dept. of AI&DS, GSSSIETW, Mysuru


25
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment: 8
Develop a JAVA program to create an outer class with a function display. Create another class
inside the outer class named inner with a function called display and call the two functions in the
main class.

Aim: The program is to demonstrate the concept of inner classes. The program defines an outer
class (OuterClass) with a function display. Inside the outer class, there is an inner class (Inner)
that also has a function display. The main class (MainClass) creates an instance of both the outer
and inner classes and calls their respective display methods to showcase how outer and inner
classes can coexist and have separate implementations of the same method.
Learning Objectives: To understand Object Oriented Programming Features of JAVA
Course outcome:
CO3: Apply the concepts of inheritance and interfaces in solving real world problems.
Theory:
Inner Classes in Java:

An inner class is a class defined within another class. In Java, inner classes provide a way to
logically group classes that are only used in one place, and they increase encapsulation.

Types of Inner Classes:

Member Inner Class: Defined at the member level of a class.

Local Inner Class: Defined inside a method or a block of code.

Anonymous Inner Class: Without a name, defined for implementing interfaces or extending
classes on the spot.

Member Inner Class:

A member inner class is defined inside another class as a member of that class. It has access to
the members (fields and methods) of its outer class, including private members.

De Dept. of AI&DS, GSSSIETW, Mysuru


26
3rd Sem–Object Oriented Programming with Java [BCS306A]

MainClass:

In the MainClass, an instance of the outer class (OuterClass) is created, and its display method is
called.

An instance of the inner class (Inner) is created using the outer class instance, and its display
method is called.

public class Outer {


public void display()
{
System.out.println("Inside Outer.display()");
}

class Inner
{
public void display()
{
System.out.println("Inside Inner.display()");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args)
{
Outer o = new Outer();
o.display();

Outer.Inneri = o.newInner();
i.display();
}
}

Output:

Inside Outer.display( )

Inside Inner.display( )

De Dept. of AI&DS, GSSSIETW, Mysuru


27
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment: 9
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionBy
Zero using try, catch, throw and finally.

Aim: The program is to demonstrate the use of custom exceptions. The program defines a
custom exception class (DivisionByZeroException) that extends the built-in Exception class. The
program performs a division operation and throws the custom exception if a division by zero is
detected.

Learning Objectives: To gain knowledge on: packages, multithreaded programming and


exceptions.
Course outcome:
CO4: Use the concept of packages and exception handling in solving complex problem

Theory:
Custom Exception (User-Defined Exception):

In Java, we create our own exceptions by extending the Exception class or one of its subclasses.
These are known as custom exceptions or user-defined exceptions. Creating custom exceptions
allows you to handle specific error conditions in a more structured and meaningful way.

Explanation:

The DivisionByZeroException class extends the built-in Exception class and has a constructor
that takes a message.

The divide method in the main program performs division and throws a Division By Zero
Exception if the denominator is zero.

In the main method, a try block is used to enclose the code that might throw an exception.

The catch block catches and handles the custom exception if it occurs.

The finally block contains code that always executes, whether an exception is thrown or not.
This block is useful for cleanup or releasing resources.

De Dept. of AI&DS, GSSSIETW, Mysuru


28
3rd Sem–Object Oriented Programming with Java [BCS306A]

import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args)
{
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the divisor : ");
n = scanner.nextInt();
try
{
int quotient = 22 / n;
System.out.println("quotient : " + quotient);
}

catch(ArithmeticException ae)
{
try
{
throw new MyException();
}
catch(MyException me)
{

}
}
}
}

public class MyException extends Exception {


public MyException()
{
System.out.println("MyException.constructor() ...");
}
}

De Dept. of AI&DS, GSSSIETW, Mysuru


29
3rd Sem–Object Oriented Programming with Java [BCS306A]

Output:

Enter the divisor :

44

quotient : 0

Enter the divisor :

MyException.constructor( )…

De Dept. of AI&DS, GSSSIETW, Mysuru


30
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 10:
Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.

Aim:
This program aims to illustrate the process of creating and utilizing packages in Java for better
code organization, modularity, and reusability.
Learning Objectives: To gain knowledge on: packages, multithreaded programming and
exceptions.
Course outcome:
CO4: Use the concept of packages and exception handling in solving complex problem

Theory:
Packages in Java:

In Java, a package is a way to organize related classes and interfaces into a single directory
hierarchy. It helps in preventing naming conflicts, improves code modularity, and enhances code
reusability. A package can contain subpackages, and classes in a package can be grouped
logically.

Package (mypack):

A package named mypack is created, and it contains a class named MyPackageClass.

The MyPackageClass class has a method displayMessage() that prints a simple message.

Main Class (MainClass):

The main class is outside the mypack package.

It imports the MyPackageClass from the mypack package using the import statement.

In the main method, an instance of MyPackageClass is created, and its displayMessage method is
called.

De Dept. of AI&DS, GSSSIETW, Mysuru


31
3rd Sem–Object Oriented Programming with Java [BCS306A]

package pgm10.mypack;
public class MyClass {
public void display()
{
System.out.println("Inside MyClass.display() method ...");
}
}

import pgm10.mypack.MyClass;

public class PackageDemo {


public static void main(String[] args)
{
MyClassmyClass = new MyClass();
myClass.display();
}
}

Output:

Inside MyClass.display() method ...

De Dept. of AI&DS, GSSSIETW, Mysuru


32
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 11:
Write a program to illustrate creation of threads using runnable class. (start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).

Aim: The program is to demonstrate the creation of threads using the Runnable interface. The
program aims to illustrate the basics of multi-threading, thread creation, and the concept of
thread suspension.
Learning Objectives: Gain hands-on experience with multi-threading concepts, including
creating and managing multiple threads in a Java program
Course outcome:
CO5: Apply concepts of multithreading, autoboxing and enumerations in program development
Theory:
The Thread class in Java provides a constructor that takes a Runnable object as an argument.
When a Thread object is created with a Runnable object, it can start a new thread of execution,
and the run() method of the Runnable object will be executed in that thread.

We can create threads using the Runnable interface. The Runnable interface represents a task
that can be executed concurrently by a thread. To use the Runnable interface, you typically
create a class that implements Runnable and override its run() method. The run() method
contains the code that will be executed when the thread is started.

Explanation:

MyRunnable is a class that implements the Runnable interface. It overrides the run() method,
where the thread sleeps for 500 milliseconds.

In the ThreadExample class, two instances of MyRunnable are created.

Two Thread objects (thread1 and thread2) are created, each associated with one of the
MyRunnable instances.

The start() method is called on each Thread object to begin the execution of the associated run()
method.

De Dept. of AI&DS, GSSSIETW, Mysuru


33
3rd Sem–Object Oriented Programming with Java [BCS306A]

While the new threads are running, the main thread also continues its execution, printing
messages to the console.

The start() method of the Thread class is used to initiate the execution of the thread. It internally
calls the run() method of the Runnable object.

The sleep() method is used to make the thread sleep for a specified amount of time. In this
example, it's used to simulate some work being done by the threads

public class MyThread implements Runnable {


@Override
public void run()
{
for ( inti = 1; i<= 10; i++ )
System.out.println("run() : " + Thread.currentThread().getName());
try
{
Thread.sleep(2000);
}
catch(InterruptedExceptionie)
{
System.out.println(ie);
}
}
}

public class ThreadDemo {


public static void main(String[] args)
{
Thread t1,t2,t3;

t1 = new Thread(new MyThread());


t2 = new Thread(new MyThread());
t3 = new Thread(new MyThread());

t1.setName("JIT1");
t2.setName("JIT2");
t3.setName("JIT3");

t1.start();
t2.start();
t3.start();

for ( inti = 0; i< 10; i++ )

De Dept. of AI&DS, GSSSIETW, Mysuru


34
3rd Sem–Object Oriented Programming with Java [BCS306A]

System.out.println("run() : " + Thread.currentThread().getName());


}
}

Output:

run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : main
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT3
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT2
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1
run() : JIT1

De Dept. of AI&DS, GSSSIETW, Mysuru


35
3rd Sem–Object Oriented Programming with Java [BCS306A]

Experiment 12:
Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It can
be observed that both main thread and created child thread are executed concurrently.

Aim: The program aims to illustrate the concurrent execution of the main thread and the child
thread, highlighting the concepts of thread creation, base class constructors, and concurrent
execution.
Learning Objectives: To gain knowledge on: packages, multithreaded programming and
exceptions.
Course outcome:
CO5: Apply concepts of multithreading, auto-boxing and enumerations in program
development
Theory:
In Java, multithreading allows multiple threads to run concurrently, providing a way to execute
multiple tasks simultaneously. To create a thread, you can extend the Thread class or implement
the Runnable interface. In this case, let's extend the Thread class.
When extending the Thread class, you override the run() method with the code that will be
executed when the thread is started. You can also provide a constructor to initialize any specific
attributes of your thread.
When a new thread is created by extending the Thread class, the start() method must be called to
begin the execution of the thread. The start() method internally calls the run() method.
The main thread and the created child thread run concurrently, executing their respective code in
parallel.
The Thread.sleep() method is used to introduce a short delay, simulating some work being done
by the threads.

public class MyThread extends Thread {


public MyThread()
{
setName("JIT");
}

De Dept. of AI&DS, GSSSIETW, Mysuru


36
3rd Sem–Object Oriented Programming with Java [BCS306A]

@Override
public void run()
{
for ( inti = 0; i< 50; i++ )
System.out.println("run() : " + Thread.currentThread().getName());

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
}

public static void main(String[] args)


{
new MyThread().start();
for ( inti = 0; i< 50; i++ )
System.out.println(Thread.currentThread().getName());

}
}

Output:

main
main
main
main
main
main
main
main
main
main
main
main
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT
run() : JIT

De Dept. of AI&DS, GSSSIETW, Mysuru


37

You might also like