Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

lOMoARcPSD|15524672

21CSL35-OOPS LAB - lab manual

Computer Applications I (CMR University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by kavitha cr (csebce2020@gmail.com)
lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

CMR INSTITUTE OF TECHNOLOGY


Department of Computer Science and Engineering

LAB MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY


(21CSL35)
Semester-III

Academic Year: 2022-2023

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY


[As per Choice Based Credit System (CBCS) Scheme]
(Effective from the Academic Year 2021-2022)

Semester-III

Course Code 21CSL35 CIE Marks 50

Teaching Hours/Week 0:0:2:0 SEE Marks 50

Total Number of Lecture Hours 24 Exam Hours 03

Course Objectives
CLO 1. Demonstrate the use of Eclipse/Net beans IDE to create Java Applications.
CLO 2. Using java programming to develop programs for solving real-world problems.
CLO 3. Reinforce the understanding of basic object-oriented programming concepts.

Prerequisites
฀ Students should be familiarized about java installation and setting the java environment.
฀ Usage of IDEs like Eclipse/Net beans should be introduced.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Course CO-PO-PSO Mapping

Course Program PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO PSO


Outcome Covered 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4
CO1 1-12 2 1 3 1 3 0 0 0 3 2 0 0 0 0 0 0
CO2 1-12 2 3 0 1 0 0 0 0 0 1 0 0 1 0 0 0
CO3 1-12 2 3 3 1 2 0 0 1 1 1 0 0 3 0 0 0
CO4 1-12 1 2 1 2 2 0 0 0 1 0 1 0 2 0 0 0
CO5 1-12 1 2 1 1 2 0 0 1 1 1 0 0 2 0 0 0

CORRELATION
PROGRAM OUTCOMES (PO), PROGRAM SPECIFIC OUTCOMES (PSO)
LEVELS

PO1 Engineering knowledge PO7 Environment and sustainability 0 No Correlation

PO2 Problem analysis PO8 Ethics 1 Slight/Low

Moderate/
PO3 Design/development of solutions PO9 Individual and teamwork 2
Medium

Conduct investigations of complex


PO4 PO10 Communication 3 Substantial/ High
problems

PO5 Modern tool usage PO11 Project management and finance

PO6 The Engineer and society PO12 Life-long learning

PSO1 Design and develop applications using different stacks of web and programming technologies.

PSO2 Design and develop secure, parallel, distributed, networked, and digital systems.

PSO3 Apply software engineering methods to design, develop, test and manage software systems.

PSO4 Design and develop intelligent applications for business and industry.

CO 1. Use Eclipse/NetBeans IDE to design, develop, debug Java Projects.


CO 2. Analyze the necessity for Object Oriented Programming paradigm over structured programming
and become familiar with the fundamental concepts in OOP.
CO 3. Demonstrate the ability to design and develop java programs, analyze, and interpret object oriented
data and document results.
CO 4. Apply the concepts of multiprogramming, exception/event handling, abstraction to develop
robust programs.
CO 5. Develop user friendly applications using File I/O and GUI concepts.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Syllabus
Part-A-
List of problems for which student should develop program and execute in the
Laboratory
1. Write a java program that prints all real solutions to the quadratic equation. ax2+bx+c=0. Read in a, b, c and
use the quadratic formula.
2. Create a Java class called Student with the following details as variables within it.
USN, Name, Branch, Phone.
Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone
of these objects with suitable headings.
3. i) Write a program to check prime number
ii) Write a program for Arithmetic calculator using switch case menu
4. Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing three
subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java
program to read and display at least 3 staff objects of all three categories.
5. Write a java program demonstrating Method overloading and Constructor overloading.
6. Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to INR and
vice versa), distance converter (meter to KM, miles to KM and vice versa), time converter (hours to minutes,
seconds and vice versa) using packages.
7. Write a program to generate the resume. Create 2 Java classes Teacher (data: personal information,
qualification, experience, achievements) and Student (data: personal information, result, discipline) which
implements the java interface Resume with the method biodata().
8. Write a Java program that implements a multi-thread application that has three threads. First thread generates a
random integer for every 1 second; second thread computes the square of the number and prints; third thread
will print the value of cube of the number.
9. Write a program to perform string operations using ArrayList. Write functions for the following a. Append -
add at end b. Insert – add at particular index c. Search d. List all string starts with given letter.
10. Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an
exception when b is equal to zero.
11. Write a java program that reads a file name from the user, displays information about whether the file exists,
whether the file is readable, or writable, the type of file and the length of the file in bytes.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


12. Develop an applet that displays a simple message in center of the screen. Develop a simple calculator using
Swings.
Part-B

A problem statement for each batch is to be generated in consultation with the co-examiner and student should
develop an algorithm, program and execute the program for the given problem with appropriate outputs.
Content Beyond Syllabus

Prog # Title
13
14

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-1: Write a java program that prints all real solutions to the quadratic equation. ax2+bx+c=0. Read in a, b,
c and use the quadratic formula.
Aim: Introduce the java fundamentals, data types, operators in java.
Problem Statement: Design and develop a flowchart or an algorithm that accepts 3 coefficients of a quadratic
equation as input and compute all possible roots. Implement a C program for the developed flowchart and execute
to find the possible roots for the given set of coefficients and print messages accordingly.
Algorithm:
1. Start.

2. Read three non-zero coefficients a, b and c.


3. Check if a is equal to zero. If true, go to step 4 else go to step 5.
4. Display the equation is linear and go to step 11.
5. Calculate the determinant as follows:
determinant = b*b - 4* a*c
6. Check if the determinant is equal to 0. If true, go to step 7, else go to step 8.
7. Compute roots as follows:
root1 = -b/2*a
root2 = root 1
Display: Roots are real and equal (i.e. root1) then go to step 11.
8. Check is determinant is greater than 0. If true, go to step 9 else go to step 10.
9. Compute roots as follows:
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
Display: Roots are real and distinct (i.e. root1 and root2)then go to step 11.
10. Calculate:
Real = -b / (2 * a);
Imaginary part = Math.sqrt(- determinant) / (2 * a);
Display: Roots are imaginary i.e. Real part and imaginary part the go to step 11.
11. Stop.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
double a,b,c,determinant;
double root1, root2;
System.out.println("Enter the coefficients a,b,c");
Scanner sc = new Scanner(System.in);
a=sc.nextInt();
if (a==0)
{
System.out.println("a can not be zero");
}
else
{
b=sc.nextInt();
c=sc.nextInt();
determinant = b * b - 4 * a * c;
// check if determinant is greater than 0
if (determinant > 0) {
// two real and distinct roots
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
}
// check if determinant is equal to 0
else if (determinant == 0) {
// two real and equal roots
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


// determinant is equal to 0
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}
// if determinant is less than zero
else {
// roots are complex number and distinct
double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}
}
Sample Output:
Enter the coefficients a,b,c
121
root1 = root2 = -1.00;
Enter the coefficients a,b,c
1 -1 -12
root1 = 4.00 and root2 = -3.00
Enter the coefficients a,b,c
111
root1 = -0.50+0.87i
root2 = -0.50-0.87i
Questions for Viva:
1) Which of the following is not a keyword in java?
a) new b) identifier c) void
2) What is the size of float and double in java?
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


a) 32 and 64 b) 32 and 32 c) 64 and 64 d) 64 and 32
3) Find the output of the following code
public class Demo
{
public static void main(String[] args) {
int Integer=24;
char string='I';
System.out.print(Integer);
System.out.print(string);
}
}
a) Compiler error b) Throws exception c) I d) 24 I
4) int x=0, y=0, z=0;
x=(++x + y--)*z++;
what will be the value of “x” after execution?
a) -2 b) -1 c) 0 d) 1 e) 2
5) What is the output of a logical AND (&) operation if both inputs/operands are true?
a) False b) True c) true or false d) None of the above

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-2: Create a Java class called Student with the following details as variables within it.
USN, Name, Branch, Phone.
Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone of these objects
with suitable headings.
Aim: Demonstrating creation of java classes, objects, constructors, declaration, and initialization of variables.
Problem Statement: Design and develop a flowchart or an algorithm that create n number of objects and input the
following parameters such as USN, Name, Branch, Phone. Create a constructor to initialize class variables with
default values and develop corresponding methods for reading and displaying the variables declared in the class.
Algorithm:
1. Start
2. Declare the class and variables (USN, Name, Branch, Phone).
3. Create no-argument constructor to initialize class variables with default values.
4. Read n value from the user and create n objects.
5. Read values for class variables using object.
6. Implement read() method to read the values from calling method.
7. Implement display() method to display the values of class members referenced by individual object.
8. Stop.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.io.*;
class Student
{
String usn, name, branch;
long ph;
Student()
{
usn = name = branch = "no value";
ph = 0;
}
void read_data(String u, String n, String b, long p)
{
usn = u;
name = n;
branch = b;
ph =p;
}
void display()
{
System.out.println(usn + "\t" + name + "\t" + branch + "\t" + ph);
}
}
class Main
{
public static void main(String args[]) throws Exception
{
String u, n, b;
long p;
int no;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println("Enter number of records");
no = Integer.parseInt(br.readLine());
Student[] s = new Student[no];
for(int i=0; i<s.length;i++)
{
System.out.println("Enter " + (i + 1) + " Student record");
s[i] = new Student();
System.out.println("Enter student USN");
u = br.readLine();
System.out.println("Enter student Name");
n = br.readLine();
System.out.println("Enter student Branch");
b = br.readLine();
System.out.println("Enter student Phone number");
p = Long.parseLong(br.readLine());
s[i].read_data(u, n, b, p);
}
System.out.println("USN\tNAME\tBRANCH \t PHONE NO");
for(int i=0; i<s.length;i++)
{
s[i].display();
}
}
}
Sample Output:
Enter number of records
3
Enter 1 Student record
Enter student USN
101
Enter student Name
Rojer
Enter student Branch
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


B.Arch
Enter student Phone number
9884495925
Enter 2 Student record
Enter student USN
102
Enter student Name
Mahibha
Enter student Branch
CSE
Enter student Phone number
9994963041
Enter 3 Student record
Enter student USN
103
Enter student Name
Federer
Enter student Branch
Civil
Enter student Phone number
9944963046
USN NAME BRANCH PHONE NO
101 Rojer B.Arch 9884495925
102 Mahibha CSE 9994963041
103 Federer Civil 9944963046
Questions for Viva:
1) An object is an instance of ___________-
a) Program b) class c) method d) data
2) Which of the following statements is a valid declaration of an object that belongs to “MyClass”?
a) MyClass onj=new MyClass();
b) MyClass obj=new MyClass;
c) obj=new MyClass();
d) new MyClass obj;
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


3) Which of these operators is used to allocate memory for an object?
a) malloc b) alloc c) new d) realloc
4) There is a special portion of memory called the _______where the object live.
a) Heap b) File c) Stack d) All of these
5) A java constructor is like a method without _____________
a) Statements b) return type c) argument list d) None

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-3: a) Write a program to check prime number


b) Write a program for Arithmetic calculator using switch case menu
Aim: Discuss various decision-making statements, loop constructs in java.
Problem Statement: a) A positive integer greater than or equal to 2 is a prime number if the only divisor of this
integer is 1 and itself. b) Create a simple calculator which can perform basic arithmetic operations like addition,
subtraction, multiplication or division depending upon the user input.
Algorithm: (a)
1. Start.
2. Enter num as input.
3. Initialize the variable temp to 0.
4. Iterate a for loop from 2 to num/2.
5. If num is divisible by loop iterator, then increment the value of temp.
6. If the temp is equal to 0 then print the given number is prime else not a prime.
7. Stop.
Algorithm: (b)
1. Start.
2. Declare three variables n1, n2 and result and declare a character variable op.
3. Read the required values from the user.
4. Define case statements which takes ‘operator’ value as switch case to calculate sum, difference,
multiplication, division, modulus.
5. Pass the operator value to the case statements to calculate arithmetic operation between the two inputs
num1 and num2.
6. Display the result.
7. Stop.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (a)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (b)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code: (a)


import java.util.*;
public class Main
{
public static void main(String[] args) {
int i, num, temp = 0;
// read input from user.
Scanner s1=new Scanner(System.in);
System.out.println("Enter any numb to Check for Prime: ");
num=s1.nextInt();
// iterate up to n/2.
for (i = 2; i <= num / 2; i++)
{
// check if num is divisible by any number.
if (num % i == 0)
{
temp++;
break;
}
}
// check for the value of temp and num.
if (temp == 0 && num != 1)
{
System.out.println("The given number is prime");
}
else
{
System.out.println("The given number is not a prime");
}
}

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}

Program Code: (b)


import java.util.Scanner;
class Main {
public static void main(String[] args) {
char operator;
Double num1, num2, res;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
do {
if(operator=='E')
{
break;
}
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
switch (operator) {
// performs addition between numbers
case '+':
res = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + res);
break;
case '-':
res = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + res);
break;
case '*':
res = num1 * num2;
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println(num1 + " * " + num2 + " = " + res);
break;

// performs division between numbers


case '/':
res = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + res);
break;
default:
System.out.println("Invalid operator!");
break;
}
System.out.println("Choose an operator: +, -, *, or /");
operator= input.next().charAt(0);
} while(operator!='E');
input.close();
}
}
Sample Output: (a)
Enter any numb to Check for Prime:
7
The given number is prime
Enter any numb to Check for Prime:
9
The given number is not a prime
Sample Output: (b)
Choose an operator: +, -, *, or /
/
Enter first number
8
Enter second number
2
8.0 / 2.0 = 4.0
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Choose an operator: +, -, *, or /
E

Questions for Viva:


1 A switch case statement in java is a ______________ control statement.
b) Iteration b) Loop c) Selection d) Jump
2 An if-else statement is also called ________--.
e) Branching statement
f) Control statement
g) Block statements
h) All
3 Choose a valid loop name in java below
b) for b) while c) do while d) All
4 There is a special portion of memory called the _______where the object live.
b) Heap b) File c) Stack d) All of these
5 A java constructor is like a method without _____________
b) Statements b) return type c) argument list d) None

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-4 Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by
writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a
Java program to read and display at least 3 staff objects of all three categories.

Aim: Demonstration of how classes can be extended using inheritance and how methods will be invoked by
object.
Problem Statement: a) Create a Java program with a staff main class, which has properties like Staffid, Name,
Phone, and Salary. Three classes, including Teaching (domain, publications), Technical (skills), and Contract, are
extended from the primary class staff (period). Make an object for each class, call its methods, and show
information about the main class with any of the other three classes.
Algorithm:
1. Start
2. Create a class Staff with the variables StaffId, Name, Phone and Salary.
3. Extend the class Staff by class Teaching and add attributes (domain, publications).
4. Extend the class Staff by class Technical and add attributes (skills).
5. Extend the class Staff by class Contract and add attributes (period).
6. Create a new class and objects for the classes Teaching, Technical, and Contract.
7. Using the respective object, invoke the methods implemented in the parent and derived classes.
8. Finally, create a display() method to display user-supplied data.
9. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.Scanner;
class Staff {
private String staffId;
private String name;
private long phone;
private float salary;
public void accept() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Staff Id: ");
staffId = scanner.next();
System.out.print("Enter Name: ");
name = scanner.next();
System.out.print("Enter Phone: ");
phone = scanner.nextLong();
System.out.print("Enter Salary: ");
salary = scanner.nextFloat();
}
public void display() {
System.out.println("Staff Id: " + staffId);
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
System.out.println("Salary: " + salary);
}
}
class Teaching extends Staff {
private String domain;
private String[] publications;

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);

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


domain = scanner.next();
System.out.print("Enter Number of Publications: ");
int n = scanner.nextInt();
publications = new String[n];
System.out.print("Enter Publications: ");
for (int i = 0; i < n; i++) {
publications[i] = scanner.next();
}
}
public void display() {
super.display();
System.out.println("Domain: " + domain);
System.out.println("Publications:");
for (int i = 0; i < publications.length; i++) {
System.out.println(publications[i]);
}
}
}
class Technical extends Staff {
private String[] skills;
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Skills: ");
int n = scanner.nextInt();
skills = new String[n];
System.out.println("Enter Skills:");
for (int i = 0; i < n; i++) {
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


skills[i] = scanner.next();
}
}
public void display() {
super.display();
System.out.println("Skills:");
for (int i = 0; i < skills.length; i++) {
System.out.println(skills[i]);
}
}
}
class Contract extends Staff {
private int period;
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Period: ");
period = scanner.nextInt();
}
public void display() {
super.display();
System.out.println("Period: " + period);
}
}
class Main {
public static void main(String[] args) {
Teaching teaching = new Teaching();
Technical technical = new Technical();
Contract contract = new Contract();
System.out.println("Enter Details for Teaching Staff Member");
teaching.accept();
System.out.println("Enter Details for Technical Staff Member");
technical.accept();
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println("Enter Details for Contract Staff Member");
contract.accept();
System.out.println("Details for Teaching Staff Member are");
teaching.display();
System.out.println("Details for Technical Staff Member are");
technical.display();
System.out.println("Details for Contract Staff Member are");
contract.display();
}
}
Sample Output:
Enter Details for Teaching Staff Member
Enter Staff Id: 101
Enter Name: Robert
Enter Phone: 9994963046
Enter Salary: 10000
Enter Domain: ML
Enter Number of Publications: 2
Enter Publications: Image Denoising
Enter Details for Technical Staff Member
Enter Staff Id: 102
Enter Name: Rojer
Enter Phone: 9884495925
Enter Salary: 25000
Enter Number of Skills: 1
Enter Skills:
Arhcitect
Enter Details for Contract Staff Member
Enter Staff Id: 103
Enter Name: Mahi
Enter Phone: 9791666615
Enter Salary: 24000
Enter Period: 12
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Details for Teaching Staff Member are
Staff Id: 101
Name: Robert
Phone: 9994963046
Salary: 10000.0
Domain: ML
Publications:
Image
Denoising
Details for Technical Staff Member are
Staff Id: 102
Name: Rojer
Phone: 9884495925
Salary: 25000.0
Skills:
Arhcitect
Details for Contract Staff Member are
Staff Id: 103
Name: Mahi
Phone: 9791666615
Salary: 24000.0
Period: 12
Questions for Viva:
1) Which of this keyword must be used to inherit a class?
a) super b) this c) extent d) extends
2) Which of these is correct way of inheriting class A by class B?
a) Class B + class A{}
b) class B inherits class A{}
c) class B extends A{}
d) class B extends class A{}
3) Which of these keywords is used to refer to member of base class from a sub class?
a) upper b) super c) this d) none of the mentioned
4) What are the features reused using inheritance in java?
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


a) Methods b) Variables c) Constants d) All the above
5) In a multi-level inheritance in java, the last subclass inherits methods and properties of _______.
a) Only one immediate superclass
b) Few classes above it
c) Al classes above it
Program-5: Write a java program demonstrating Method overloading and constructor overloading.
Aim: Introduce the concepts of method overloading, constructor overloading, overriding.
Problem Statement: Create or develop simple java program to add different data type numbers using method
overloading and constructor overloading.
Algorithm: (Method Overloading)
1. Start.
2. Create the class called Sum with main function.
3. Implement addition method with different arguments.
4. Create an object for the class.
5. Call the methods using the object.
6. Return the result.
7. Stop
Algorithm: (Constructor Overloading)
1. Start
2. Create the class called Main with main function.
3. Create the constructor with the main class name.
4. Implement two constructors (No argument and parameterized).
5. Create the objects and constructor which will be called implicitly.
6. Return the result.
7. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (a)

Flowchart: (b)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code: (Method Overloading)


public class Sum{
//addition method of parameter a and b
void addition(int a,int b){
int sum=a+b;
System.out.println("Sum of two numbers is "+sum);
}
//addition method of parameter a, b and c
void addition(int a,int b,int c){
int sum=a+b+c;
System.out.println("Sum of three numbers is "+sum);
}
public static void main(String args[]){
Sum s=new Sum();
s.addition(2,5,10);
s.addition(15,10);
}
}
Program Code: (Constructor Overloading)
import java.util.Scanner;
class Main {
int s;
Main() {
System.out.print("Sum is:");
}
Main(int a, int b) {
s = a + b;

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}
void display() {
System.out.print(s);
}
public static void main(String args[]) {
int a, b;
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers:");
a = sc.nextInt();
b = sc.nextInt();
Main t1 = new Main();
Main t2 = new Main(a, b);
t2.display();
}
}
Sample Output: (Method Overloading)
E:\Java Programs>javac Sum.java
E:\Java Programs>java Sum
Sum of three numbers is 17
Sum of two numbers is 25
Sample Output: (Constructor Overloading)
E:\Java Programs>java Main
Enter two numbers:3 4
Sum is:7
Questions for Viva:
1) To successfully overload a method in java, the method names must be___________.
a) Same b) Different c) Same or Different d) None
2) Java method overloading implements the OOPS concept _________.
a) Inheritance b) Polymorphism c) Encapsulation d) None
3) Which is the overloaded static method of Math class to get absolute value in java?
a) Math.abs(int)
b) Math.abs(float)
c) Math.abs(double)
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


d) All the above
4) A java constructor is like a method without ________.
a) Statements b) return type c) argument list d) None
5) The name of the constructor and the name of the class are
a) Same b) different

Program-6: Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to
INR and vice versa), distance converter (meter to KM, miles to KM and vice versa), time converter (hours to
minutes, seconds and vice versa) using packages.

Aim: To develop a java application to implement currency converter, distance converter and time converter using
the concept of packages.
Problem Statement: Create a Java software that converts between currency, distance, and time. Make a package
containing three classes with method implementations, such as Currency, Distance, and Time. Design a primary
class, make objects for those classes, then call the appropriate methods to do conversions.
Algorithm:
1. Start
2. Create a Package currency conversion and place the class currency under the package.
3. Create the methods to perform currency conversion from dollar to rupee, rupee to dollar, euro to rupee,
rupee to euro, yen to rupee and rupee to yen.
4. Create the package distance conversion and create the class distance within the package.
5. Create the methods to convert from meter to km, km to meter, miles to km, km to miles.
6. Create the package time conversion and create the class timer. Create the methods to convert from hours to
minutes, hours to seconds, minutes to hours and seconds to hours.
7. Create a class and import the packages currency conversion, distance conversion and time conversion.
Create the objects for the class currency, distance and timer.
8. Get the choice from the user and invoke the methods to perform the corresponding conversion and display
the value.
9. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (Currency Converter)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (Distance Converter)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (Time Converter)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
//currency.java
package currencyconversion;
import java.util.*;
public class currency
{
double inr,usd;
double euro,yen;
Scanner in=new Scanner(System.in);
public void dollartorupee()
{
System.out.println("Enter dollars to convert into Rupees:");
usd=in.nextInt();
inr=usd*67;
System.out.println("Dollar ="+usd+"equal to INR="+inr);
}
public void rupeetodollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();
usd=inr/67;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}
public void eurotorupee()
{
System.out.println("Enter euro to convert into Rupees:");

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


euro=in.nextInt();
inr=euro*79.50;
System.out.println("Euro ="+euro +"equal to INR="+inr);
}
public void rupeetoeuro()
{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();
euro=(inr/79.50);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
}
public void yentorupee()
{
System.out.println("Enter yen to convert into Rupees:");
yen=in.nextInt();
inr=yen*0.61;
System.out.println("YEN="+yen +"equal to INR="+inr);
}
public void rupeetoyen()
{
System.out.println("Enter Rupees to convert into Yen:");
inr=in.nextInt();
yen=(inr/0.61);
System.out.println("INR="+inr +"equal to YEN"+yen);
}
}
//distance.java
package distanceconversion;
import java.util.*;
public class distance
{
double km,m,miles;
Scanner sc = new Scanner(System.in);
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


public void kmtom()
{
System.out.print("Enter in km ");
km=sc.nextDouble();
m=(km*1000);
System.out.println(km+"km" +"equal to"+m+"metres");
}
public void mtokm()
{
System.out.print("Enter in meter ");
m=sc.nextDouble();
km=(m/1000);
System.out.println(m+"m" +"equal to"+km+"kilometres");
}
public void milestokm()
{
System.out.print("Enter in miles");
miles=sc.nextDouble();
km=(miles*1.60934);
System.out.println(miles+"miles" +"equal to"+km+"kilometres");
}
public void kmtomiles()
{
System.out.print("Enter in km");
km=sc.nextDouble();
miles=(km*0.621371);
System.out.println(km+"km" +"equal to"+miles+"miles");
}
}
//timer.java
package timeconversion;
import java.util.*;
public class timer
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


{
int hours,seconds,minutes;
int input;
Scanner sc = new Scanner(System.in);
public void secondstohours()
{
System.out.print("Enter the number of seconds: ");
input = sc.nextInt();
hours = input / 3600;
minutes = (input % 3600) / 60;
seconds = (input % 3600) % 60;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
}
public void minutestohours()
{
System.out.print("Enter the number of minutes: ");
minutes=sc.nextInt();
hours=minutes/60;
minutes=minutes%60;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
}
public void hourstominutes()
{
System.out.println("enter the no of hours");
hours=sc.nextInt();
minutes=(hours*60);
System.out.println("Minutes: " + minutes);
}
public void hourstoseconds()
{
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println("enter the no of hours");
hours=sc.nextInt();
seconds=(hours*3600);
System.out.println("Minutes: " + seconds);
}
}

//converter.java
import currencyconversion.currency;
import distanceconversion.distance;
import timeconversion.timer;
import java.util.*;
import java.io.*;
class converter
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int choice,ch;
currency c=new currency();
distance d=new distance();
timer t=new timer();
do
{
System.out.println("1.dollar to rupee ");
System.out.println("2.rupee to dollar ");
System.out.println("3.Euro to rupee ");
System.out.println("4..rupee to Euro ");
System.out.println("5.Yen to rupee ");
System.out.println("6.Rupee to Yen ");
System.out.println("7.Meter to kilometer ");
System.out.println("8.kilometer to meter ");
System.out.println("9.Miles to kilometer ");
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println("10.kilometer to miles");
System.out.println("11.Hours to Minutes");
System.out.println("12.Hours to Seconds");
System.out.println("13.Seconds to Hours");
System.out.println("14.Minutes to Hours");
System.out.println("Enter ur choice");
choice=s.nextInt();
switch(choice)
{
case 1:
{
c.dollartorupee();
break;
}
case 2:
{
c.rupeetodollar();
break;
}
case 3:
{
c.eurotorupee();
break;
}
case 4:
{
c.rupeetoeuro();
break;
}
case 5:
{c.yentorupee();
break;}
case 6 :
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


{
c.rupeetoyen();
break;
}
case 7 :
{
d.mtokm();
break;
}
case 8 :
{
d.kmtom();
break;
}
case 9 :
{
d.milestokm();
break;
}
case 10 :
{
d.kmtomiles();
break;
}
case 11 :
{
t.hourstominutes();
break;
}
case 12 :
{
t.hourstoseconds();
break;
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}
case 13 :
{
t.secondstohours();
break;
}
case 14 :
{
t.minutestohours();
break;
}
}
System.out.println("Enter 0 to quit and 1 to continue ");
ch=s.nextInt();
}while(ch==1);
}
}
Sample Output:
E:\Java Programs>javac -d . currency.java
E:\Java Programs>javac -d . distance.java
E:\Java Programs>javac -d . timer.java
E:\Java Programs>javac converter.java
E:\Java Programs>java converter
1.dollar to rupee
2.rupee to dollar
3.Euro to rupee
4..rupee to Euro
5.Yen to rupee
6.Rupee to Yen
7.Meter to kilometer
8.kilometer to meter
9.Miles to kilometer
10.kilometer to miles
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


11.Hours to Minutes
12.Hours to Seconds
13.Seconds to Hours
14.Minutes to Hours
Enter ur choice
1
Enter dollars to convert into Rupees:
250
Dollar =250.0equal to INR=16750.0
Enter 0 to quit and 1 to continue
1
1.dollar to rupee
2.rupee to dollar
3.Euro to rupee
4..rupee to Euro
5.Yen to rupee
6.Rupee to Yen
7.Meter to kilometer
8.kilometer to meter
9.Miles to kilometer
10.kilometer to miles
11.Hours to Minutes
12.Hours to Seconds
13.Seconds to Hours
14.Minutes to Hours
Enter ur choice
8
Enter in km 5
5.0kmequal to5000.0metres
Enter 0 to quit and 1 to continue
1
1.dollar to rupee
2.rupee to dollar
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


3.Euro to rupee
4..rupee to Euro
5.Yen to rupee
6.Rupee to Yen
7.Meter to kilometer
8.kilometer to meter
9.Miles to kilometer
10.kilometer to miles
11.Hours to Minutes
12.Hours to Seconds
13.Seconds to Hours
14.Minutes to Hours
Enter ur choice
11
enter the no of hours
2
Minutes: 120
Enter 0 to quit and 1 to continue
Questions for Viva:
1) Choose the correct syntax of a java package below.
a) package PACKAGE_NAME;
b) package PACKAGE_NAME.*;
c) pkg PACKAGE_NAME;
d) pkg PACKAGE_NAME.*;
2) The keyword used to declare a java package is _________-.
a) pkg b) package c) pkge d) none of the above
3) The keyword used to import a package into java class or interface is _________
a) import b) download c) use d) none of the above
4) Which is the default java package that will be auto included (imported) in the classpath while compiling
and running a java program?
a) java.io b) java.util c) java.net d) java.lang
5) What is the maximum number of java class files that can be kept inside a single java package?
a) 8 b) c) 128 d) unlimited
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-7: Write a program to generate the resume. Create 2 Java classes Teacher (data: personal information,
qualification, experience, achievements) and Student (data: personal information, result, discipline) which
implements the java interface Resume with the method biodata().
Aim: Introduction to abstract classes, abstract methods, and interfaces in java.
Problem Statement: Create a Java application to display resume of student and faculty using the concepts of
classes and interfaces in java.
Algorithm:
1. Start
2. Create the Resume interface and include the abstract method (biodata()).
3. Create the Faculty class by including relevant class members’ personal information, qualifications,
experience, and achievement.
4. Create the Student class by including relevant class members’ personal information, result, and discipline..
5. Allow the Faculty class to implement the interface Resume, and this class to implement abstract method
biodata().
6. Allow the Student class to implement the interface Resume, and this class to implement abstract method
biodata().
7. Create a Main class in which you will create objects for classes such as Faculty and Student. And use class
methods to generate a resume.
8. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.Scanner;
interface Resume
{
public void biodata();
}
class Teacher implements Resume
{
String name,gen,dept,qual,achiv,mail,address,mob;
int exp,fac_id;
public void biodata()
{
Scanner s1=new Scanner(System.in);
System.out.print("Name:");
name=s1.next();
System.out.print("Gender:");
gen=s1.next();
System.out.print("Employee ID:");
fac_id=s1.nextInt();
System.out.print("Department:");
dept=s1.next();
System.out.print("Qualification:");
qual=s1.next();
System.out.print("Achievement:");
achiv=s1.next();
System.out.print("Experience:");

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


exp=s1.nextInt();
System.out.print("Mail Id:");
mail=s1.next();
System.out.print("Address:");
address=s1.next();
System.out.print("Mobile:");
mob=s1.next();
System.out.println("");
System.out.println("************************");
System.out.println(" Biodata-Teacher ");
System.out.println("************************");
System.out.println("----------------------------------------*");
System.out.println("|Name :| "+name);
System.out.println("|Employee ID :| "+fac_id);
System.out.println("|Department :| "+dept);
System.out.println("|Qualification :| "+qual);
System.out.println("|Experience :| "+exp);
System.out.println("|Achievement :| "+achiv);
System.out.println("|Experience :| "+achiv);
System.out.println("|Address :| "+address);
System.out.println("|Mobile :| "+mob);
System.out.println("----------------------------------------*");
}
}
class Student implements Resume
{
String name,address,section,res,disc,mob;
int rollno;
public void biodata()
{
Scanner s1=new Scanner(System.in);
System.out.print("Name:");
name=s1.next();
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.print("Rollno:");
rollno=s1.nextInt();
System.out.print("Section:");
section=s1.next();
System.out.print("Result:");
res=s1.next();
System.out.print("Discipline:");
disc=s1.next();
System.out.print("Address:");
address=s1.next();
System.out.print("Mobileno:");
mob=s1.next();
System.out.println("");
System.out.println("************************");
System.out.println(" Biodata-Student ");
System.out.println("************************");
System.out.println("----------------------------------------*");
System.out.println("|Name :| "+name);
System.out.println("|Rollno :| "+rollno);
System.out.println("|Section :| "+section);
System.out.println("|Section :| "+section);
System.out.println("|Result :| "+res);
System.out.println("|Discipline :| "+disc);
System.out.println("|Address :| "+address);
System.out.println("|Mobile :| "+mob);
System.out.println("----------------------------------------*");
}
}
class Demo7
{
public static void main(String args[])
{
Student stud=new Student();
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Teacher teach=new Teacher();
Scanner s2=new Scanner(System.in);
System.out.println("Resume");
System.out.println("*******");
System.out.println("1.Student");
System.out.println("2.Teacher");
System.out.println("Enter your option");
int choice=s2.nextInt();
switch(choice)
{
case 1:
stud.biodata();
break;
case 2:
teach.biodata();
break;
default:
System.out.println("Wrong Option");
}
}
}
Sample Output:
Resume
*******
1.Student
2.Teacher
Enter your option
1
Name:Eliza
Rollno:121
Section:A
Result:9
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Discipline:Good
Address:bangalore
Mobileno:8989546526
************************
Biodata-Student
************************
----------------------------------------*
|Name :| Eliza
|Rollno :| 121
|Section :| A
|Section :| A
|Result :| 9
|Discipline :| Good
|Address :| bangalore
|Mobile :| 8989546526
----------------------------------------*
Questions for Viva:
1) An abstract class in java can be created using the keyword________
a) final b) interface c) abstract d) static
2) Can you create an object from an abstract class in java?
a) True b) False
3) Which is the opposite of abstract class
a) interface b) concrete class
4) Does the below java code with abstract method compile?
class Puppy
{
abstract void showName();
}
a) No b) yes
5) An interface in java is like a 100%____________
a) abstract class b) public class c) inner class d) anonymous class

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-8: Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number and prints; third
thread will print the value of cube of the number.

Aim: Demonstration creation of threads using Thread class and Runnable interface, multithreaded programming.
Problem Statement: Develop java application to generate random number and find out the square and cube of the
same random number using multithreaded programming.
Algorithm:
1. Start
2. Create a class called ‘Square’ and implement ‘Runnable’ interface. Use this class to receive a number from
a thread and to print square of that number in run method of it.
3. Create a class called ‘Cube’ and implement ‘Runnable’ interface. Use this class to receive a number from a
thread and to print cube of that number in run method of it.
4. Create a class called ‘Number’ that should extend ‘Thread’ class.
4.1 Inside the ‘run’ method of this class generate random number and pass this number to constructor
‘Square’.
4.2 Call ‘run’ method in ‘Square’ class using t1.start() method to find the square of random number.
4.3 Inside the ‘run’ method of this class generate random number and pass this number to constructor
‘Cube’.
4.4 Call ‘run’ method in ‘Cube’ class using t1.start() method to find the cube of random number.
5. Create main class and call the method of Number class to display the output.
6. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.*;
class Square implements Runnable
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube implements Runnable
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<5; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
Thread t1=new Thread(new Square(randomInteger));
t1.start();
Thread t2=new Thread(new Cube(randomInteger));
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class DemoThread {
public static void main(String args[])
{
Number n = new Number();
n.start();
}
}
Sample Output:
E:\Java Programs>java DemoThread
Random Integer generated : 90
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


Square of 90 = 8100
Cube of 90 = 729000
Random Integer generated : 68
Square of 68 = 4624
Cube of 68 = 314432
Random Integer generated : 76
Square of 76 = 5776
Cube of 76 = 438976
Random Integer generated : 22
Square of 22 = 484
Cube of 22 = 10648
Random Integer generated : 69
Square of 69 = 4761
Cube of 69 = 328509
Questions for Viva:
1) In java thread can be created by ____________
a) Extending the Thread class
b) Implementing the Runnable interface
c) Both of the above
d) None of these
2) When a class extends the Thread class, it should override________ method of Thread class to start that
thread.
a) start() b) run() c) init() d) go()
3) Which of this method of Thread class is used to find out the priority given to a thread?
a) Get() b) ThreadPriority() c) GetPriority() d) GetThreadPriority()
4) Which function of pre-defined class Thread is used to check whether current thread being checked is still
running?
a) isAlive() b) Join() c) isRunning() d) Alive()
5) Number of threads in below java program is
public class ThreadExtended extends Thread {
public void run() {

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


System.out.println("\nThread is running now\n");
}
public static void main(String[] args) {
ThreadExtended threadE = new ThreadExtended();
threadE.start();
}
}
a) 0 b) 1 c) 2 d) 3

Program-9: Write a program to perform string operations using ArrayList. Write functions for the following a.
Append - add at end b. Insert – add at particular index c. Search d. List all string starts with given letter.
Aim: Introduce java Collections.
Problem Statement: Develop a java program to create ArrayList and implement operations such as add element at
the end, insert at index, search, and list all strings start with given letter.
Algorithm :
1. Start
2. Create the class DemoArrayList and create the object for the class.
3. Display the options to the user for performing string handling.
4. Use the function add() to append the string at the end and to insert the string at the particular index.
5. The function sort() is used to sort the elements in the array list.
6. The function indexof() is used to search whether the element is in the array list or not.
7. The function startswith() is used to find whether the element starts with the specified character.
8. The function remove() is used to remove the element form the array list.
9. The function size() is used to determine the number of elements in the array list.
10. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.*;
import java.io.*;
public class DemoArrayList
{
public static void main(String args[])throws IOException
{
ArrayList<String> obj = new ArrayList<String>();
DataInputStream in=new DataInputStream(System.in);
int c,ch;
int i,j;
String str,str1;
do
{
System.out.println("STRING MANIPULATION");
System.out.println("******************************");
System.out.println(" 1. Append at end \t 2.Insert at particular index \t 3.Search \t");
System.out.println( "4.List string that starting with letter \t");
System.out.println("5.Size \t 6.Remove \t 7.Sort\t 8.Display\t" );
System.out.println("Enter the choice ");
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1:
{
System.out.println("Enter the string ");
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


str=in.readLine();
obj.add(str);
break;
}
case 2:
{
System.out.println("Enter the string ");
str=in.readLine();
System.out.println("Specify the index/position to insert");
i=Integer.parseInt(in.readLine());
obj.add(i-1,str);
System.out.println("The array list has following elements:"+obj);
break;
}
case 3:
{
System.out.println("Enter the string to search ");
str=in.readLine();
j=obj.indexOf(str);
if(j==-1)
System.out.println("Element not found");
else
System.out.println("Index of:"+str+"is"+j);
break;
}
case 4:
{
System.out.println("Enter the character to List string that starts with specified character");
str=in.readLine();
for(i=0;i<(obj.size()-1);i++)
{
str1=obj.get(i);
if(str1.startsWith(str))
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


{
System.out.println(str1);
}}
break;
}
case 5:
{
System.out.println("Size of the list "+obj.size());
break;
}
case 6:
{
System.out.println("Enter the element to remove");
str=in.readLine();
if(obj.remove(str))
{
System.out.println("Element Removed"+str);
}
else
{
System.out.println("Element not present");
}
break;
}
case 7:
{
Collections.sort(obj);
System.out.println("The array list has following elements:"+obj);
break;
}
case 8:
{
System.out.println("The array list has following elements:"+obj);
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


break;
}
}
System.out.println("enter 0 to break and 1 to continue");
ch=Integer.parseInt(in.readLine());
}while(ch==1);
}}
Sample Output:
E:\Java Programs>java DemoArrayList
STRING MANIPULATION
******************************
1. Append at end 2.Insert at particular index 3.Search
4.List string that starting with letter
5.Size 6.Remove 7.Sort 8.Display
Enter the choice
1
Enter the string
Paul
enter 0 to break and 1 to continue
1
STRING MANIPULATION
******************************
1. Append at end 2.Insert at particular index 3.Search
4.List string that starting with letter
5.Size 6.Remove 7.Sort 8.Display
Enter the choice
3
Enter the string to search
pa
Element not found
enter 0 to break and 1 to continue
1
STRING MANIPULATION
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


******************************
1. Append at end 2.Insert at particular index 3.Search
4.List string that starting with letter
5.Size 6.Remove 7.Sort 8.Display
Enter the choice
8
The array list has following elements:[Paul]
enter 0 to break and 1 to continue
1
STRING MANIPULATION
******************************
1. Append at end 2.Insert at particular index 3.Search
4.List string that starting with letter
5.Size 6.Remove 7.Sort 8.Display
Enter the choice
2
Enter the string
Robert
Specify the index/position to insert
1
The array list has following elements:[Robert, Paul]
enter 0 to break and 1 to continue
0
Questions for Viva:
1) Which of these collection class can grow dynamically?
a) Array b) Arrays c) ArrayList d) None of the above
2) Which of these method can be used to increase the capacity of ArrayList object manually?
a) Capacity() b) increaseCapacity() c) increasecapacity() d) ensureCapacity()
3) Which of these method of ArrayList class is used to obtain present size of an object?
a) size() b) length() c) index() 4) capacity()
4) Which of these method is used to reduce the capacity of an ArrayList object?
a) trim() b) trimSize() c) trimTosize() d) trimToSize()
5) What will be the output of the following java program?
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


import java.util.*;
class Output
{
public static void main(String args[])
{
ArrayList obj = new ArrayList();
obj.add("A");
obj.ensureCapacity(3);
System.out.println(obj.size());
}
}
a) 1
b) 2
c) 3
d) 4
6) In Java, the underlying data structure for the ArrayList and Vector class is?
a) Resizable Array or Growable Array
b) Hash table
c) Balanced Tree
d) Linked List

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-10: Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise
an exception when b is equal to zero.
Aim: Exception handling in java, introduction to throwable class, throw, throws, finally.
Problem Statement: Develop a simple java program to divide one number by another number and generate
exception if the second number is zero.
Algorithm:
1. Start
2. Create a class called ‘DemoException’.
3. Read two integers (a, b) from the user.
4. Use Exception handling mechanism to handle exception.
5. If b is equal to zero , then throw an exception using the keyword ‘throw’.
6. Otherwise return the result of a/b.
7. Stop.

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.util.Scanner;
public class DemoException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b,c;
System.out.print("Enter the Two Interger Values\nA :");
a=scan.nextInt();
System.out.print("B :");
b=scan.nextInt();
scan.close();
try {
if(b==0)
throw new ArithmeticException("Divide By Zero");
c=a/b;
System.out.println("\nThe Value of "+a+" / "+b+" is "+c);
}catch(ArithmeticException e)
{
e.printStackTrace();
}
}
}
Sample Output:
E:\Java Programs>java DemoException
Enter the Two Interger Values
A :4
B :4

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


The Value of 4 / 4 is 1
E:\Java Programs>java DemoException
Enter the Two Interger Values
A :4
B :0
java.lang.ArithmeticException: Divide By Zero
at DemoException.main(DemoException.java:13)
Questions for Viva:
1) All java exceptions can be handled gracefully. State True or False.
a) True b) False
2) Are the classes Error and Exception similar in java?
a) No b) Yes
3) Which is the super class in Java that bundles all classes to deal with exceptions and errors?
a) Error b) Exception c) Throwable d) Throw
4) Which are the keywords used to handle exceptions in Java?
a) try, catch
b) finally
c) throw, throws
d) all the above
5) What is the output of the below Java code with Exceptions?
public class ExceptionTest1
{
public static void main(String[] args)
{
try
{
int a=9, b=0;
int c = a/b;
System.out.println("Exception occurred.");
}
catch(Exception e)
{
System.out.println("Catching an Exception.");
}
}
}
a) Exception occurred, catching the exception
b) Exception occurred

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


c) Catching an exception

Program-11: Write a java program that reads a file name from the user, displays information about whether the
file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes.

Aim: Introduce file operations in java.


Problem Statement: Create a Java program that checks for the presence of a file, displays its contents, determines
whether it is readable or writable, and returns the file's length in bytes.
Algorithm:
1. Start
2. Create a class called ‘FileDemo’ with main method.
3. Inside the main method create file object. While creating file object, pass the name of the file.
4. Print information’s about the files by using various file methods.
5. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart:

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code:
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
Sample Output:
E:\Java Programs>javac FileDemo.java
E:\Java Programs>java FileDemo
File exists: true
File is readable: true
File is writable: true
Is a directory: false
length of the file: 12 bytes
Contents of the file are:
Learn Java
Questions for Viva:
1) Which of these class contains the methods used to write in a file?
a) FileStream
b) FileInputStream
c) BufferedOutputStream
d) FileBufferStream
2) Which of these exception is thrown in cases when the file specified for writing is not found?
a) IOException
b) FileException
c) FileNotFoundException
d) FileInputException
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


3) Which of these values is returned by read() method is end of file (EOF) is encountered?
a) 0
b) 1
c) -1
d) Null
4) Which of these methods is used to write() into a file?
a) put()
b) putFile()
c) write()
d) writeFile()
5) Which of these class is not a member class of java.io package?
a) File
b) StringReader
c) Writer
d) String

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program-12: Develop an applet that displays a simple message in center of the screen. Develop a simple
calculator using Swings.

Aim: Introduce java Applet, awt, swings.


Problem Statement: Develop a java program to display a simple message using Applet. Also develop simple
calculator using components available in java swing.
Algorithm (Display Message):
1. Start
2. Import all relevant packages.
3. Create a class called MessageDemo which extends Applet class.
4. Use init() method to initialize settings.
5. Use paint() method to display message in the center of the screen.
6. Stop
Algorithm (Calculator):
1. Start
2. Import all relevant packages.
3. Create a class called Cal which extends Applet class and implements ActionListener interface.
4. Declare and initialize all the variables required for designing calculator.
5. Use init() method to initialize settings.
6. Set the layout and add all the components into Applet window using add() method.
7. Use ActionListener method to generate the event when the button is clicked.
8. Use ActionPerformed() method to receive an event and perform the corresponding operation.
9. Display the result.
10. Stop

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (Display Message)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Flowchart: (Calculator)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Program Code: (Display Message)


MessageDemo.java
import java.awt.*;
import java.applet.*;
public class MessageDemo extends Applet
{
public void init()
{
setForeground(Color.green);
}
public void paint(Graphics g)
{
g.drawString(" Hello World ",80,40);
}
}
a.html
<applet code=MessageDemo.class height=400 width=400>
</applet>
Program Code: (Calculator)
Cal.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Cal extends Applet implements ActionListener
{
String msg=" "; int v1,v2,result;
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
clear=new Button("clear");
EQ=new Button("=");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand(); char ch=str.charAt(0);
if ( Character.isDigit(ch)) t1.setText(t1.getText()+str);
else
if(str.equals("+"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("-"))
{
v1=Integer.parseInt(t1.getText()); OP='-';
t1.setText("");
} else if(str.equals("*"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


t1.setText("");
}
else if(str.equals("/"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("%"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("="))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}
}
Demo.html
<applet code="Cal.class" width=300 height=300></applet>

Sample Output: (Display Message)


E:\Java Programs>javac MessageDemo.java
E:\Java Programs>appletviewer a.html

Sample Output: (Calculator)

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23

Questions for Viva:


1) Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
2) Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawstring()
d) transient()
3) What is the Message is displayed in the applet made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)


lOMoARcPSD|15524672

OOPS with Java Laboratory– 21CSL35 Academic Year: 2022-23


}
}
a) A Simple Applet
b) A Simple Applet 20 20
c) Compilation Error
d) Runtime Error
4) Which one method is used to set the visibility of the frame?
a) setVisible(true)
b) setVisible(false)
c) setVisible()
d) None
5) Which is a component in AWT that can contain another components like buttons, text fields, labels etc.?
a) Window
b) Container
c) Panel
d) Frame

Department of ComputerScience and Engineering, CMRIT, Bangalore.

Downloaded by kavitha cr (csebce2020@gmail.com)

You might also like