java
java
Name: ……………………………………………………..….
Branch: ………………………………………………….……
USN: ……………………………….……………………….…
PREFACE
Mission
M1: To inculcate strong academic foundation in the information technology domain to empower
and equip students for successful career through various teaching learning approaches.
M3 To emphasize the ethical use of technology instilling in our students, a sense of social
responsibility towards the betterment of society.
I
PROGRAM OUTCOMES (POs)
ii
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as
a member or leader in diverse teams, and in multidisciplinary settings.
iii
INDEX
Sl.No Contents Page No
iv
7 Develop a JAVA program to create an interface Resizable with 21
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
8 Develop a JAVA program to create an outer class with a function 24
display. Create another class inside the outer class named inner
with a function called display and call the two functions in the
main class.
9 Develop a JAVA program to raise a custom exception (user 26
defined exception) for DivisionByZero using try, catch, throw and
finally.
10 Develop a JAVA program to create a package named mypack and 28
import & implement it in a suitable class.
11 Write a program to illustrate creation of threads using runnable 30
class. (start method start each of the newly created thread. Inside
the run method there is sleep() for suspend the thread for 500
milliseconds).
12 Develop a program to create a class MyThread in this class a 32
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.
13 VIVA Questions 34
Laboratory Outcomes:
The student should be able to:
● Analyse primitive constructs of JAVA programming language.
● Analyse features of object-oriented programming with JAVA.
● Apply knowledge on packages, multithreaded programming and exceptions.
CO2 Design a class involving data members and methods for the given scenario
CO3 Apply the concepts of inheritance and interfaces in solving real world problems.
CO4 Use the concept of packages and exception handling in solving complex problem
v
CO-PO Mapping:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 2 2 - - - - - - - - -
CO2 2 3 3 - - - - - - - - -
CO3 2 2 3 1 1 - - - - - - -
CO4 2 2 2 2 - - - - - - - -
CO5 2 2 3 1 1 - - - - - - -
LABORATORY RUBRICS
Sl No Description Marks
vi
Program 1:
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read
from command line arguments).
import java.util.Scanner;
public class matrix_add{
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
int N = Integer.parseInt(args[0]);
System.out.println("the value of N is "+N);
int[][] A = new int[10][10];
int[][] B = new int[10][10];
int[][] C = new int[10][10];
System.out.println("Enter the elements of the matrix A ");
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
A[i][j] = in.nextInt();
System.out.println("Enter the elements of the matrix B ");
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
B[i][j] = in.nextInt();
//addition of 2 matrix
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
C[i][j]= A[i][j] + B[i][j];
For compilation
C:\java3sem>javac matrix_add.java
For Execution
C:\java3sem>java matrix_add 3
//the value of N is 3
OUTPUT
Enter the elements of the matrix A
123
234
345
Enter the elements of the matrix B
976
321
378
Elements of the matrix C are
10 9 9
5 5 5
6 11 13
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.
import java.util.Scanner;
//Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main
method to illustrate Stack operations.
class Stack{
//static int ch;
private int arr[];
private int top,size;
// Creating a stack
Stack() {
arr = new int[10];
top = -1;
size= 5;
}
// push elements to the top of stack
public void push(int x) {
if (top==size-1) {
System.out.println("Stack OverFlow");
}
else{
// insert element on top of stack
System.out.println("Inserting " + x);
arr[++top] = x;}
}
// pop elements from top of stack
public int pop() {
}
}
// display elements of stack
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
}
public class Demo_stack
{
public static void main(String[] args) {
int ch;
Stack s1 = new Stack();
while (true) {
System.out.println("\nEnter your choice\n1.PUSH\n2.POP\n3.Display \n4..EXIT");
Scanner integer = new Scanner(System.in);
ch = integer.nextInt();
switch (ch) {
case 1:
System.out.println("Enter Element");
OUTPUT
Enter your choice
1.PUSH
2.POP
3.Display
4..EXIT
1
Enter Element
11
Inserting 11
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.
import java.util.Scanner;
public class Employee {
private int id;
private String name;
private double salary;
e1.display_Employee();
C:\java3sem>java Employee
C:\java3sem>javac Employee.java
C:\java3sem>java Employee
enter the employee Id , Name and salary
2 Arun 50000
enter the percetage to be increased
10
Initial Employee Details:
Employee ID =2, Name=Arun, Salary=50000.0
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.
class MyPoint {
private int x;
private int y;
// Default constructor
public MyPoint() {
x = 0;
y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
// Setter method to set both x and y
C:\java3sem>javac TestMyPoint.java
C:\java3sem>java TestMyPoint
OUTPUT
Coordinates of point1: (3, 4)
Point1: (3, 4)
Point2: (4, 6)
Distance between point1 and point2: 2.23606797749979
Distance from point1 to (0, 0): 5.0
Distance from point2 to (0, 0): 7.211102550927978
// Base class
class Shape {
System.out.println("Drawing a shape");
System.out.println("Erasing a shape");
// Subclass Circle
@Override
System.out.println("Drawing a circle");
@Override
System.out.println("Erasing a circle");
// Subclass Triangle
@Override
System.out.println("Drawing a triangle");
@Override
System.out.println("Erasing a triangle");
// Subclass Square
@Override
System.out.println("Drawing a square");
@Override
System.out.println("Erasing a square");
s1.erase();
c1.draw();
c1.erase();
t1.draw();
t1.erase();
sq1.draw();
sq1.erase();
C:\java3sem>javac PolymorphismDemo.java
C:\java3sem>java PolymorphismDemo
OUTPUT
Drawing a circle
Erasing a circle
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square
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.
// Abstract Shape class
abstract class Shape {
// Abstract method to calculate area
public abstract double calculateArea();
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}
C:\java3sem>javac ShapeDemo.java
C:\java3sem>java ShapeDemo
OUTPUT
Circle - Area: 78.53981633974483
Circle - Perimeter: 31.41592653589793
Triangle - Area: 6.0
Triangle - Perimeter: 12.0
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
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
OUTPUT
Initial Width: 10
Initial Height: 20
Resized Width: 15
Resized Height: 25
Program 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.
// Outer class
class Outer {
// Display method in the outer class
void display() {
System.out.println("This is the display method in the Outer class.");
}
// Inner class
class Inner {
// Display method in the inner class
void display() {
C:\java3sem>javac InnerClassDemo.java
C:\java3sem>java InnerClassDemo
OUTPUT
This is the display method in the Outer class.
This is the display method in the Inner class.
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
OUTPUT
Custom Exception Caught: Division by zero is not allowed.
Finally block executed.
Program 10:
Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Follow these steps
1.Create a directory structure to organize your code. You should have a directory named "mypack"
to represent the package and a separate directory for your main class.
2. Inside the "mypack" directory, create a Java file with a class that you want to include in the
package For example, let's create a class called MyClass in a file named MyClass.java
// File: mypack/MyClass.java
package mypack;
public class MyClass {
public void display() {
System.out.println("This is a method from the 'mypack' package.");
}
}
Create a separate java file for main class that will import and use the Class from the “mypack” package
Now, create a separate Java file for your main class that will import and use the class from
// File: MainClass.java
import mypack.MyClass;
Program 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).
@Override
public void run() {
try {
System.out.println("Thread " + name + " is running.");
// Sleep for 500 milliseconds
Thread.sleep(500);
System.out.println("Thread " + name + " has completed.");
C:\java3sem>javac RunnableThreadDemo.java
C:\java3sem>java RunnableThreadDemo
OUTPUT
Thread Thread 2 is running.
Thread Thread 1 is running.
Thread Thread 1 has completed.
Thread Thread 2 has completed
Program 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.
C:\java3sem>javac ThreadDemo.java
C:\java3sem>java ThreadDemo
OUTPUT:
Child Thread: ChildThread - Count: 1
Main Thread - Count: 1
Main Thread - Count: 2
Child Thread: ChildThread - Count: 2
Main Thread - Count: 3
Child Thread: ChildThread - Count: 3
Main Thread - Count: 4
Child Thread: ChildThread - Count: 4
Main Thread - Count: 5
Child Thread: ChildThread - Count: 5
3. What is an object?
An object is a real-world entity which is the basic unit of OOPs for example chair, cat, dog, etc.
Different objects have different states or attributes, and behaviors.
4. What is a class?
A class is a prototype that consists of objects in different states and with different behaviors. It
has a number of methods that are common the objects present within that class.
6. What is inheritance?
Inheritance is a feature of OOPs which allows classes inherit common properties from other
classes. For example, if there is a class such as ‘vehicle’, other classes like ‘car’, ‘bike’, etc can inherit
common properties from the vehicle class. This property helps you get rid of redundant code thereby
reducing the overall size of the code.
13. What is the difference between public, private and protected access modifiers?