100% found this document useful (2 votes)
271 views69 pages

Lab Manual - OOC - 21CSL35 (Final)

This document outlines the laboratory manual for an Object Oriented Programming with Java course. It provides details on the course code, credits, teaching hours, assessment breakdown, course objectives, and list of programming problems and experiments for students to complete. The objectives are for students to use IDEs like Eclipse/NetBeans to develop Java applications, reinforce OOP concepts, and apply concepts like inheritance, polymorphism, exceptions handling and GUI/file operations. Assessment includes continuous internal evaluation based on lab journals and tests, and semester end evaluation conducted jointly by examiners.

Uploaded by

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

Lab Manual - OOC - 21CSL35 (Final)

This document outlines the laboratory manual for an Object Oriented Programming with Java course. It provides details on the course code, credits, teaching hours, assessment breakdown, course objectives, and list of programming problems and experiments for students to complete. The objectives are for students to use IDEs like Eclipse/NetBeans to develop Java applications, reinforce OOP concepts, and apply concepts like inheritance, polymorphism, exceptions handling and GUI/file operations. Assessment includes continuous internal evaluation based on lab journals and tests, and semester end evaluation conducted jointly by examiners.

Uploaded by

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

CANARA ENGINEERING COLLEGE

Benjanapadavu, Mangalore - 574219

LABORATORY MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY


(21CSL35)

PREPARED BY

Assistant Professor Assistant Professor


Dept. of CS&E Dept. of CS&E

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING
OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY
(Accredited by National Board of Accreditation, New Delhi.)
Course Code 21CSL35 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 1 Exam Hours 03
Course Objectives:

CLO 1. Demonstrate the use of Eclipse/Netbeans 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.

Note: two hours tutorial is suggested for each laboratory sessions.


Prerequisite
• Students should be familiarized about java installation and setting the java environ-
ment.
• Usage of IDEs like Eclipse/Netbeans should be introduced.

Sl. No. PART A – List of problems for which student should develop program and execute in
the Laboratory
Aim: Introduce the java fundamentals, data types, operators in java
1
Program: 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: Demonstrating creation of java classes, objects, constructors, declaration and
initialization of variables.
Program: Create a Java class called Student with the following details as variables within
it. USN
Name
2
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: Discuss the various Decision-making statements, loop constructs in java


Program:
3 A. Write a program to check prime number
B. Write a program for Arithmetic calculator using switch case menu

Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism


Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this
4 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 Aim: Introduce concepts of method overloading, constructor overloading, overriding.
Program: Write a java program demonstrating Method overloading and Constructor
overloading.

Aim: Introduce the concept of Abstraction, packages.

6 Program: 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.

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 2


7 Aim: Introduce the concept of Abstraction, packages.

Program: 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: Demonstrate creation of threads using Thread class and Runnable interface,
multithreaded programming.
8
Program: 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: Introduce java Collections.

9 Program: 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: Exception handling in java, introduction to throwable class, throw, throws, finally.
10 Program: 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: Introduce File operations in java.
Program: Write a java program that reads a file name from the user, displays information
11 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 java Applet, awt, swings.


Programs:
12
Develop an applet that displays a simple message in centre of the screen.
Develop a simple calculator using Swings.
PART B – Practical Based Learning

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

Course Outcome (Course Skill Set)


At the end of the course the student will be able to:

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.

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 3


Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student
shall be deemed to have satisfied the academic requirements and earned the credits allotted to each
course.
The student has to secure not less than 35% (18 Marks out of 50) in the semester-end examination (SEE).
Continuous Internal Evaluation (CIE):
CIE marks for the practical course is 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
Each experiment to be evaluated for conduction with observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments designed by the
faculty who is handling the laboratory session and is made known to students at the beginning of the
practical session.
• Record should contain all the specified experiments in the syllabus and each experiment write-up
will be evaluated for 10 marks.
• Total marks scored by the students are scaled downed to 30 marks (60% of maximum marks).
• Weightage to be given for neatness and submission of record/write-up on time.
• Department shall conduct 02 tests for 100 marks, the first test shall be conducted after the 8th week
of the semester and the second test shall be conducted after the 14th week of the semester.
• In each test, test write-up, conduction of experiment, acceptable result, and procedural knowledge
will carry a weightage of 60% and the rest 40% for viva-voce.
• The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
Rubrics suggested in Annexure-II of Regulation book
• The average of 02 tests is scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and average marks of two tests is
the total CIE marks scored by the student.

Semester End Evaluation (SEE):


• SEE marks for the practical course is 50 Marks.
• SEE shall be conducted jointly by the two examiners of the same institute, examiners are ap-
pointed by the University
• All laboratory experiments are to be included for practical examination.
• (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script to
be strictly adhered to by the examiners. OR based on the course requirement evaluation rubrics
shall be decided jointly by examiners.
• Students can pick one question (experiment) from the questions lot prepared by the internal /ex-
ternal examiners jointly.
• Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.
• General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and
result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100
marks and scored marks shall be scaled down to 50 marks (however, based on course type, rubrics
shall be decided by the examiners)

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 4


• Students can pick one experiment from the questions lot of PART A with equal choice to all the
students in a batch. For PART B examiners should frame a question for each batch, student should
develop an algorithm, program, execute and demonstrate the results with appropriate output for
the given problem.
• Weightage of marks for PART A is 80% and for PART B is 20%. General rubrics suggested to
be followed for part A and part B.
• Change of experiment is allowed only once and Marks allotted to the procedure part to be made
zero (Not allowed for Part B).
• The duration of SEE is 03 hours
• Rubrics suggested in Annexure-II of Regulation book

Suggested Learning Resources:


1. E Balagurusamy, Programming with Java, Graw Hill, 6th Edition, 2019.
2. Herbert Schildt, C: Java the Complete Reference, McGraw Hill, 11th Edition, 2020

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 5


Laboratory Program 1:

Aim: Introduce the java fundamentals, data types, operators in java.

Program: 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.

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

1. Primitive data types: The primitive data types include Boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Ar-
rays.

Boolean Data Type: Is used to store only two possible values: true and false.
Byte Data Type: The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128
and maximum value is 127. Its default value is 0.
Short Data Type: The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
Int Data Type: The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648(-2^31) to 2,147,483,647(2^31 -1) Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
Long Data Type: The long data type is a 64-bit two's complement integer. Its value-range lies between
-2^63 to 2^63 -1. Its default value is 0.
Float Data Type: The float data type is a single-precision 32-bit IEEE 754 floating point. Its value
range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating-point numbers. Its default value is 0.0F.
Double Data Type: The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal values just like float. Its
default value is 0.0d.
Char Data Type: The char data type is a single 16-bit Unicode character. Its value-range lies between
0 to 65,535.The char data type is used to store characters.

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 6


Stores whole numbers from -9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Array: is an object which contains elements of a similar data type. Additionally, the elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based.

Algorithm:
Step 1: Start
Step 2: Read a, b, c
Step 3: initialize d<-(b*b)-(4*a*c)
Step 4: initialize r<- b/2*a
Step 5: if d>0 go to Step 6, else go to Step 8
Step 6: m=(-b+r)/(2*a) and n=(-b-r)/(2*a)
Step 7: prints roots are real and distinct, first root r1 second root r2
Step 8: if d=0 go to Step 9, else go to Step 10
Step 9: print roots are real and equal,n
Step 10: d=-d
Step 11: print roots are imaginary
Step 12: Stop

Source Code:

import java.util.Scanner;
public class QuadraticEquation
{
public static void main (String args[])
{
double m=0,n=0,a,b,c,determinant,r;
Scanner s=new Scanner (System.in);
System.out.println("Enter the value of co-efficient a:");
a=s.nextDouble();
System.out.println("Enter the value of co-efficient b:");
b=s.nextDouble();

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 7


System.out.println("Enter the value of co-efficient c:");
c=s.nextDouble();
determinant=(b*b) -(4*a*c);
r=Math.sqrt(determinant);
if(determinant>0)
{
m=(-b+r)/(2*a);
n=(-b-r)/(2*a);
System.out.println("The roots are real and distinct \n m= "+m+" n= "+n);
}
else if(determinant==0)
{
m=(-b)/(2*a);
n=m;
System.out.println("The roots are real and equal \n m= "+m+" n= "+n);
}
else{
System.out.println("The roots are imaginary");
}
}
}

Sample Output:

Enter the value of co-effiecient a :1


Enter the value of co-effiecient b :-2
Enter the value of co-effiecient c :1
The roots are real and equal
m= 1.0 n= 1.0

Enter the value of co-effiecient a :1


Enter the value of co-effiecient b :3
Enter the value of co-effiecient c :2
The roots are real and distinct
m= -1.0 n= -2.0

Enter the value of co-effiecient a :1


Enter the value of co-effiecient b :1
Enter the value of co-effiecient c :1
The roots are imaginary

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 8


Laboratory Program 2:

Aim: Demonstrating creation of java classes, objects, constructors, declaration and initialization of
variables.
Program: 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.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity
only. An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen, table,
car, etc.

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Algorithm:
Input: Values for USN, Name, Branch and Phone no
Output: Displaying the details of n student objects//
Step:1 Class “Student” is created
Step 2: Declare variables USN, Name, Branch, and Phone no.
Step 3: A constructor of Student class is created to initialize these variables.
Step 4: Multiple objects of “student” class is created and print the details contained in student class

Source Code:
import java.util.Scanner;
public class Student{
String USN, Name, branch, phone;
void insertRecord(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the USN");
USN = sc.next();
System.out.println("Enter the name");
Name = sc.next();

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 9


System.out.println("Enter the Branch");
branch = sc.next();
System.out.println("Enter the Phone no");
phone = sc.next();
}
void displayRecord()
{
System.out.println(USN + "\t" + Name + "\t" + branch + "\t" + phone);
}
public static void main(String args[]) {
int i,n;
Student s[] = new Student[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of students");
n = sc.nextInt();
for ( i = 0; i < n; i++)
{
System.out.println("Enter the Student Details");
s[i] = new Student();
s[i].insertRecord();
}
System.out.println("#### Student Record ###");
System.out.println("USN\t\tName\tBranch\tPhone Number");
for (i = 0; i < n; i++)
{
s[i].displayRecord();
}
}
}

Sample Output:

Enter the number of students


3
Enter the Student Details
Enter the USN
4SUCS001
Enter the name
Sunitha
Enter the Branch
CSE
Enter the Phone no
1235678
Enter the Student Details
Enter the USN
4SUCS002
Enter the name

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 10


Anish
Enter the Branch
cse
Enter the Phone no
34567890
Enter the Student Details
Enter the USN
4SUCS003
Enter the name
Sharal
Enter the Branch
ECE
Enter the Phone no
56789234
#### Student Record ###
USN Name Branch Phone Number
4SUCS001 Sunitha CSE 1235678
4SUCS002 Anish cse 34567890
4SUCS003 Sharal ECE 56789234

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 11


Laboratory Program 3:

Aim: Discuss the various Decision-making statements, loop constructs in java Program:

3A. Write a program to check prime number

Java’s Selection Statements


Java supports two selection statements: if and switch. These statements allow you to control the flow
of your program’s execution based upon conditions known only during run time.
if: The if statement is Java’s conditional branch statement. It can be used to route program execution
through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly braces (that
is, a block). The condition is any expression that returns a boolean value. The else clause is optional.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it
exists) is executed.
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in
programming. When you nest ifs, the main thing to remember is that an else statement always refers to
the nearest if statement that is within the same block as the else and that is not already associated with
an else.
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed. The final else acts as a default

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 12


condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is
no final else and all other conditions are false, then no action will take place.
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execu-
tion to different parts of your code based on the value of an expression. As such, it often provides a
better alternative than a large series of if-else-if statements. Here is the general form of a switch state-
ment:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case state-
ments must be of a type compatible with the expression.
The switch statement works like this: The value of the expression is compared with each of the literal
values in the case statements. If a match is found, the code sequence following that case statement is
executed. If none of the constants matches the value of the expression, then the default statement is
executed. However, the default statement.
Iteration Statements
Java’s iteration statements are for, while, and do-while.

for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby provid-
ing a shorter, easy to debug structure of looping.
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based
on a given Boolean condition. The while loop can be thought of as a repeating if statement.
while (boolean condition)
{
loop statements...
}
do while: do while loop is similar to while loop with only difference that it checks for condition after

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 13


executing the statements, and therefore is an example of Exit Control Loop.
do
{
statements.
}
while (condition);

Algorithm:
Step 1: Take num as input.
Step 2: Initialize a variable flag to 0.
Step 3: Iterate a “for” loop from 2 to m.
Step 4: If n is divisible by loop iterator, then increment temp.
Step 5: If the flag is equal to 0,
Return “Num IS PRIME”.
Else,
Return “Num IS NOT PRIME”.

Source Code:

import java.util.Scanner;

public class PrimeNumber {

public static void main(String args[]) {


int i, m, flag = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number");
int n = s.nextInt();
m = n-1;
if (n == 0 || n == 1)
{
System.out.println(n + " is not prime number");
}
else
{
for (i = 2; i <= m; i++)
{
if (n % i == 0)
{
System.out.println(n + " is not a prime number");
flag = 1;
break;
}
}
if (flag == 0)

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 14


System.out.println(n + " is a prime number");
}
}
}

Sample Output:

Enter the number


1
1 is not prime number

Enter the number


2
2 is a prime number

Enter the number


17
17 is a prime number

Enter the number


69
69 is not a prime number

Enter the number


999983
999983 is a prime number

3B. Write a program for Arithmetic calculator using switch case menu
The switch statement selects one of many code blocks to be executed:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 15


switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Algorithm:
Step 1: Start.
Step 2: Read the two variable a and b
Step 3: Enter the opertaor
Step 4: Evaluate option code with case statements
Step 5: Evaluate option code with case statements
Step 5.1: case 1 Read the two variable a and b. result=a+b.print result. goto step 7.
Step 5.2: case 2 Read the two variable a and b. result=a-b.print result. goto step 7.
Step 5.3: case 3 Read the two variable a and b. result=a*b. print result. goto step 7.
Step 5.4: case 4 Read the two variable a and b. result=a/b. print result. goto step 7.
Step 5.5: case 5 Read the two variable a and b. result=a%b. print result. goto step 7.
Step 5.6: case 5 Read the two variable a and b. result=a^b. print result. goto step 7.
Step 6: Entered choice is invalid the print “invalid choice”
Step 7: Stop

Source code:

import java.util.Scanner;

public class ArithmeticCalculator


{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
double a,b;

System.out.println("Enter Two Numbers A and B");


a=s.nextDouble();
b=s.nextDouble();
System.out.println("Enter the Operator(Indicating that which operation to be done) ");
char op=s.next().charAt(0);
switch(op)
{
case '+': System.out.println("A+B = "+(a+b));
break;

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 16


case '-': System.out.println("A-B = "+(a-b));
break;
case '*': System.out.println("A*B = "+(a*b));
break;
case '/': System.out.println("A/B = "+(a/b));
break;
case '%': System.out.println("A%B = "+(a%b));
break;
case '^': System.out.println("A^B = "+(Math.pow(a,b)));
break;
default: System.out.println("Invalid operator!!!");
break;

}
}
}
Sample Output:
Enter Two Numbers A and B
555
996
Enter the Operator(Indicating that which operation to be done)
+
A+B = 1551.0
Enter Two Numbers A and B
78000
980
Enter the Operator(Indicating that which operation to be done)
-
A-B = 77020.0
Enter Two Numbers A and B
78
36
Enter the Operator(Indicating that which operation to be done)
*
A*B = 2808.0

Enter Two Numbers A and B


6572
9
Enter the Operator(Indicating that which operation to be done)
/
A/B = 730.2222222222222
Enter Two Numbers A and B
24
7
Enter the Operator(Indicating that which operation to be done)
%

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 17


A%B = 3.0

Enter Two Numbers A and B


78
34
Enter the Operator(Indicating that which operation to be done)
?
Invalid operator!!!

Laboratory Program 4:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 18


Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism

Program: Design a super class called Staff with details as Staff Id, Name, Phone, and 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

Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the mechanism in


java by which one class is allowed to inherit the features (of another class.
Super Class: The class whose features are inherited is known as a superclass
Sub Class: The class that inherits the other class is known as a subclass
Reusability: Inheritance supports the concept of “reusability”, i.e., when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our new
class from the existing class.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used
for a general class of actions. The specific action is determined by the exact nature of the situation
polymorphism is often expressed by the phrase “one interface, multiple methods.” This means that it is
possible to design a generic interface to a group of related activities.
This helps reduce complexity by allowing the same interface to be used to specify a general class of
action. It is the compiler’s job to select the specific action as it applies to each situation.

Algorithm:
Step 1: Create class Staffmain
Step 2: Enter the Teaching Staff Information inherits staff
Step 3: Enter the Technical Staff Information inherits Staff
Step 4: Enter the Contract Basis Staff Information
Step 5: Teaching Staff Information
Step 6: Technical Staff Information
Step 7: Contract Basis Staff Information
Step 8: Display the details.

Source Code:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 19


import java.util.Scanner;
class Staff
{
String id,name;
long phone,salary;
Scanner s=new Scanner(System.in);
void read()
{
System.out.println("Enter the Staff Id");
id=s.nextLine();
System.out.println("Enter the Staff Name");
name=s.nextLine();
System.out.println("Enter the Phone Number");
phone=s.nextLong();
System.out.println("Enter the Salary");
salary=s.nextLong();
}
void display()
{
System.out.println("Staff ID : "+id+"\nName : "+name+"\nPhone Number : "+phone+"\nSalary :
"+salary);
}

}
class Teaching extends Staff
{
String domain;
int n;
Scanner s=new Scanner(System.in);
void read()
{
super.read();
System.out.println("Enter the Domain of Teaching Staff");
domain=s.nextLine();
System.out.println("Enter the total number of Publications");
n=s.nextInt();
}
void display()
{
super.display();
System.out.println("Domain : "+domain+"\tNo. of Publications : "+n);
}
}
class Technical extends Staff
{
String skills;
Scanner s=new Scanner(System.in);

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 20


void read()
{
super.read();
System.out.println("Enter the skills of Technical Staff");
skills=s.nextLine();
}
void display()
{
super.display();
System.out.println("Skills : "+skills);
}
}
class Contract extends Staff
{
int period;
Scanner s=new Scanner(System.in);
void read()
{
super.read();
System.out.println("Enter the contract period in years");
period=s.nextInt();
}
void display()
{
super.display();
System.out.println("Contract Period : "+period);
}
}
public class Staffmain
{
public static void main(String args[])
{
Teaching t=new Teaching();
Technical tech=new Technical();
Contract c=new Contract();
System.out.println("Enter the Teaching Staff Information\n");
t.read();
System.out.println("Enter the Technical Staff Information\n");
tech.read();
System.out.println("Enter the Contract Basis Staff Information");
c.read();
System.out.println("\n\n*** Teaching Staff Information ***");
t.display();
System.out.println("\n\n*** Technical Staff Information ***");
tech.display();
System.out.println("\n\n*** Contract Basis Staff Information ***");
c.display();

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 21


}
}

Sample Output:
Enter the Teaching Staff Information
Enter the Staff Id
emp001
Enter the Staff Name
Lokesh
Enter the Phone Number
9108394594
Enter the Salary
65000
Enter the Domain of Teaching Staff
Data Structures
Enter the total number of Publications
5

Enter the Technical Staff Information


Enter the Staff Id
e401
Enter the Staff Name
Aneesh Kumar
Enter the Phone Number
9902207630
Enter the Salary
30000
Enter the skills of Technical Staff
Computer Operator

Enter the Contract Basis Staff Information


Enter the Staff Id
emp1001
Enter the Staff Name
Darshan
Enter the Phone Number
9447769846
Enter the Salary
20000
Enter the contract period in years
6

*** Teaching Staff Information ***


Staff ID : emp001

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 22


Name : Lokesh
Phone Number : 9108394594
Salary : 65000
Domain : Data Structures No. of Publications : 5

*** Technical Staff Information ***


Staff ID : e401
Name : Aneesh Kumar
Phone Number : 9902207630
Salary : 30000
Skills : Computer Operator

*** Contract Basis Staff Information ***


Staff ID : emp1001
Name : Darshan
Phone Number : 9447769846
Salary : 20000
Contract Period : 6

Laboratory Program 5:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 23


Aim: Introduce concepts of method overloading, constructor overloading, overriding.

Program: Write a java program demonstrating Method overloading and Constructor overloading.

A) Method Overloading
If a class of a Java program has a plural number of methods, and all of them have the same name but
different parameters (with a change in type or number of arguments), and programmers can use them
to perform a similar form of functions, then it is known as method overloading.
Here is the list of rules by which we can implement method overloading in Java. They are as follows:
1. The method name must be the same.
2. Parameters must be different, i.e., each overloaded method must take a unique list of parameter types.
We can change the parameters in one of the following three ways:
Data type of parameters
Example: void add (int a, int b) // There are two parameters, a and b with data type int.
void add (int a, float b) // Here, two parameters a, and b with types int and float.
Number of parameters
Example: void sum (int a, int b) // Two parameters, a and b with data type int.
void sum (int a, int b, int c) // Three parameters a, b, and c with data type int.
Sequence of data type of parameters
Example: void sub (int a, double b)
void sub (double a, float a)
3. Access modifiers can be anything or different.
4. Return type can be anything or different.
5. Exception thrown can be anything.
6. The implementation does not matter in this case. A method can have any kind of logic.

Algorithm:
Step 1: Create a Class - ComputeArea
Step 2: Create a function to compute area of circle - area (double r) - that will take radius as
argument.
Step 3: Create a function to compute area of square - area (float r) - that will take side as argument.
Step 4: Create a function compute area of rectangle - area (float len,float wid) - that will take length
and width as arguments.
Step 5: Create an object C of class ComputeArea
Step 6: To Compute area of circle.
`Read radius as double data type.
Call function - C.area to compute area and pass radius as the argument.
Display the calculate area.
Step 7: To Compute area of Square.
`Read side as float data type.
Call function - C.area to compute area and pass side as the argument.
Display the calculate area.
Step 8: To Compute area of Rectangle.
`Read length and width as float data type.
Call function - C.area to compute area and pass length and width as the

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 24


argument.
Display the calculate area.

Source Code:

import java.util.*;
class ComputeArea
{
void area(double r)
{
double area;
area=3.142*r*r;
System.out.println("Area of Circle :"+area+" Sq units");
}
void area(float side)
{
double res;
res=Math.pow(side,2);
System.out.println("Area of Square="+res+" Sq units");
}
void area(float len,float wid)
{
double res=len*wid;
System.out.println("Area of Rectangle "+res+" Sq units");
}

public static void main(String[] args)


{
Scanner s=new Scanner(System.in);
ComputeArea C=new ComputeArea();
System.out.println("Enter radius of circle");
double r=s.nextDouble();
C.area(r);
System.out.println("Enter side of square");
float x=s.nextFloat();
C.area(x);
System.out.println("Enter Length and width of rectangle:");
float l=s.nextFloat();
float w=s.nextFloat();
C.area(l, w);
}
}

Sample Output:

Enter radius of circle

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 25


5
Area of Circle :78.55 Sq units
Enter side of square
20
Area of Square=400.0 Sq units
Enter Length and width of rectangle:
10 20
Area of Rectangle 200.0 Sq units

public class Sum {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y)
{ return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output: 30
60
31.0

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 26


B) Constructor Overloading
A constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object. Every time an object is created using
the new () keyword, at least one constructor is called.
In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can
perform a different task.

Algorithm:
Step 1: Create a Class - Box
Step 2: Create a constructor Box with dimensions width, height and depth as parameters.
Save the dimensions in three different variables.
Step 3: Create a constructor Box with no dimensions.
Save -1 as the dimensions value in three different variables.
Step 4: Create a constructor Box for cube with dimensions length as parameters.
Save the dimensions in three different variables.
Step 5: Create a function volume to calculate the volume.
Step 6: To create Box-1
Create box mybox1 using constructor with depth, width and height.
Calculate the volume by calling the function and display it.
Step 7: To create Box-2
Create box mybox2 using constructor with unknown dimension.
Calculate the volume by calling the function and display it.
Step 8: To create Box-3
Create box mybox1 using constructor with length
Calculate the volume by calling the function and display it.

Source Code:

public class Box {

double width;
double height;
double depth;

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = -1;
height = -1;

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 27


depth = -1;
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
public static void main(String[] args) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of Box 1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of Box with unknown dimensions is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of Cube is " + vol);
}

Sample Output:

Volume of Box 1 is 3000.0


Volume of Box with unknown dimensions is -1.0
Volume of Cube is 343.0

Laboratory Program 6:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 28


Aim: Introduce the concept of Abstraction, packages.
Program: 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.

Data Abstraction is the property by virtue of which only the essential details are displayed to the
user. The trivial or the non-essential units are not displayed to the user. Ex: A car is viewed as a car
rather than its individual components.
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Algorithm:

Step 1: Create a package - CurrencyConversion


Create class currency with following functions.
Dollar to INR, INR to Dollar
EURO to INR, EURO to INR
Yen to INR, INR to Yen
Step 2: Create a package - TimeConversion
Create class Timer with following functions.
hour to minutes, Minutes to Hours
Minutes to seconds, seconds to minutes
Hour to seconds, seconds to hours
Step 3: Create a package - DistanceConversion
Create class Distance with following functions.
Miles to KM, KM to Miles
KM to Meters, Meters to KM
Miles to Meters, Meters to Miles
Step 4: Import CurrencyConversion package
Import TimeConversion package
Import DistanceConversion package.
Step 5: Create Converter Class
Create objects of three classes
Create a menu to select from many options for conversion.
Step 6: Using switch statement - perform the appropriate conversions.

Source Code:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 29


//currency conversion package
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 * 79.58;
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 / 79.58;
System.out.println("Rupee = " + inr + " equal to Dollars= " + usd);
}

public void eurotorupee() {


System.out.println("Enter euro to convert into Rupees:");
euro = in.nextInt();
inr = euro * 81.35;
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 / 81.35);
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.59;
System.out.println("YEN= " + yen + " equal to INR= " + inr);
}

public void rupeetoyen() {

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 30


System.out.println("Enter Rupees to convert into Yen:");
inr = in.nextInt();
yen = (inr * 0.59);
System.out.println("INR= " + inr + " equal to YEN " + yen);
}
}

//time conversion package

package timeconversion;

import java.util.*;

public class timer {


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() {


System.out.println("enter the no of hours");

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 31


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

//distanceconversion package

package distanceconversion;

import java.util.*;

public class distance {


double km, m, miles;
Scanner sc = new Scanner(System.in);

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");
}
}

//Main Converter Class

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 32


import currencyconversion.*;
import distanceconversion.*;
import java.util.*;
import timeconversion.*;

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();
while(true) {
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 ");
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("15.Exit");
System.out.println("Enter your 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;

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 33


case 6:
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;
case 13:
t.secondstohours();
break;
case 14:
t.minutestohours();
break;
case 15:
System.exit(1);
}

}
}
}

Sample Output:

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

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 34


10.kilometer to miles
11.Hours to Minutes
12.Hours to Seconds
13.Seconds to Hours
14.Minutes to Hours
15.Exit
Enter your choice
1
Enter dollars to convert into Rupees:
2
Dollar = 2.0 equal to INR= 159.16

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
15.Exit
Enter your choice
2
Enter Rupee to convert into Dollars:
700
Rupee = 700.0 equal to Dollars= 8.796179944709726

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

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 35


15.Exit
Enter your choice
3
Enter euro to convert into Rupees:
4
Euro = 4.0 equal to INR= 325.4

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
15.Exit
Enter your choice
4
Enter Rupees to convert into Euro:
876
Rupee = 876.0 equal to Euro= 10.768285187461586

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
15.Exit
Enter your choice
5
Enter yen to convert into Rupees:
34

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 36


YEN= 34.0 equal to INR= 57.6271186440678

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
15.Exit
Enter your choice
6
Enter Rupees to convert into Yen:
56
INR= 56.0 equal to YEN 33.04

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
15.Exit
Enter your choice
7
Enter in meter 56980
56980.0m equal to 56.98kilometres

1.Dollar to rupee
2.Rupee to dollar
3.Euro to rupee
4.Rupee to Euro

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 37


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
15.Exit
Enter your choice
8
Enter in km 67
67.0km equal to 67000.0metres

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
15.Exit
Enter your choice
9
Enter in miles 3
3.0 miles equal to 4.82802 kilometres

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

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 38


12.Hours to Seconds
13.Seconds to Hours
14.Minutes to Hours
15.Exit
Enter your choice
10
Enter in km 1.6
1.6km equal to 0.9941936miles

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
15.Exit
Enter your choice
11
enter the no of hours
4
Minutes: 240

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
15.Exit
Enter your choice
12

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 39


enter the no of hours
5
Minutes: 18000

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
15.Exit
Enter your choice
13
Enter the number of seconds: 56498
Hours: 15
Minutes: 41
Seconds: 38

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
15.Exit
Enter your choice
14
Enter the number of minutes: 6960
Hours: 116
Minutes: 0

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 40


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
15.Exit
Enter your choice
15

Laboratory Program 07:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 41


Aim: Introduction to abstract classes, abstract methods, and Interface in java
Program: 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 ().

Abstract Classes are considered as those classes that hide the Method Implementation details from the
user and show only the Method Functionality. They are declared using the keyword abstract. These
methods can include Abstract and Non-Abstract methods in them.
Rules for using Abstract Classes in Java
To implement an Abstract Class in Java, we need to follow the rules as described below:

• An abstract class must be declared using the abstract keyword.


• Abstract classes can include abstract and non-abstract methods.
• An Abstract Class cannot be instantiated.
• They can include constructors and static methods.
• An Abstract Class includes final methods.

Abstract Method: A method declared using the abstract keyword within an abstract class and does
not have a definition (implementation) is called an abstract method.
o An abstract method does not have a body (implementation), they just have a method signature
(declaration). The class which extends the abstract class implements the abstract methods.
o If a non-abstract (concrete) class extends an abstract class, then the class must implement all the
abstract methods of that abstract class. If not, the concrete class has to be declared as abstract as
well.
o As the abstract methods just have the signature, it needs to have semicolon (;) at the end.

An Interface in Java programming language is defined as an abstract type used to specify the behaviour
of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and
abstract methods.
The interface in Java is a mechanism to achieve abstraction.

Algorithm:
Step 1: Create an interface Resume with abstract method biodata ()
Step 2: Create class Teacher that implements Resume Interface.
Define the function biodata () that reads and prints Name,DOB, Age, BLood Group.
Qualifications experience and achievements.
Step 3: Create class Student that implements Resume Interface.
Define the function biodata () that reads and prints Name,DOB, Age, BLood Group.
Discipline, Branch, Sem, Section.
Step 4: Create objects of class Teacher and Student
Call biodata functions of teacher and student objects.

Source Code:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 42


import java.util.*;

interface Resume {
void biodata();
}

class Teacher implements Resume {

@Override
public void biodata() {
String name, dob, age, bg, qualifctn;
Scanner s = new Scanner(System.in);
System.out.println("Enter Name, Date of Birth (DD/MM/YYYY), Age, Blood Group of
Teacher");
name = s.nextLine();
dob = s.nextLine();
age = s.nextLine();
bg = s.nextLine();
System.out.println("Enter the qualifications, experience in years, achievements");
qualifctn = s.nextLine();
String exp = s.nextLine();
String achievement = s.nextLine();

System.out.println("\n\nResume of The Teacher");


System.out.println(" Name: " + name + "\nDate of Birth: " + dob + "\nAge: " + age + " \nBlood
Group: " + bg+ "\nQualifications: " + qualifctn + "\nExperience in years: " + exp + "\nAchievements:
" + achievement);

class Student implements Resume {

@Override
public void biodata() {
String name, dob, age, bg;
Scanner s = new Scanner(System.in);
System.out.println("Enter Name, Date of Birth (DD/MM/YYYY), Age, Blood Group of Student");
name = s.nextLine();
dob = s.nextLine();
age = s.nextLine();
bg = s.nextLine();

System.out.println("Enter the Discipline i.Branch ii.Sem iii.Section");


String branch = s.nextLine();
String sem = s.nextLine();

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 43


String sec = s.nextLine();
System.out.println("Enter the Results i.percentage ii.CGPA");
float p = s.nextFloat();
float c = s.nextFloat();
System.out.println("\n\nResume of The Student");
System.out.println("Name: " + name + "\nDate of Birth: " + dob + "\nAge: " + age + " \nBlood
Group: " + bg + "\nResults\nPercentage: " + p + "\nCGPA: " + c + "\nDiscipline Details:\nBranch: " +
branch + "\nSemester: " + sem + "\nSection: " + sec);

public class MainClass {


public static void main(String args[]) {
Teacher t = new Teacher();
Student s=new Student();
t.biodata();
s.biodata();

Sample Output:

Enter Name, Date of Birth (DD/MM/YYYY), Age, Blood Group of Teacher


Govinda Adiga
09/06/1962
60
O-
Enter the qualifications, experience in years, achievements
Masters in Tech,Ph.D
32
State Best Teacher Award

Resume of The Teacher Name: Govinda Adiga


Date of Birth: 09/06/1962
Age: 60
Blood Group: O-
Qualifications: Masters in Tech,Ph.D
Experience in years: 32
Achievements: State Best Teacher Award

Enter Name, Date of Birth (DD/MM/YYYY), Age, Blood Group of Student


Nikitha
17/11/2002

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 44


19
AB-
Enter the Discipline i.Branch ii.Sem iii.Section
CSE
4
A
Enter the Results i.percentage ii.CGPA
76.48
8.34

Resume of The Student


Name: Nikitha
Date of Birth: 17/11/2002
Age: 19
Blood Group: AB-
Results
Percentage: 76.48
CGPA: 8.34
Discipline Details:
Branch: CSE
Semester: 4
Section: A

Laboratory Program 08:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 45


Aim: Demonstrate creation of threads using Thread class and Runnable interface, multithreaded
programming.
Program: 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.

Thread in Java is the direction or path that is taken while a program is being executed. Generally, all
the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution.

A runnable interface is an interface that contains a single method. The Java program defines this single
method in java.Lang package and calls it upon the execution of the thread class. It provides a template
for objects that a class can implement using Threads. You can implement the runnable interface in
Java in one of the following ways:
• Using subclass thread
• Overriding the run () method

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light -
weight processes within a process.
Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface

Algorithm:
Step 1: Create FirstThread Class extending Thread class
Step 2: Create run () function in the FirstThread Class
Create SecondThread and start the thread
Create ThirdThread and start the thread.
Step 3: Create SecondThread implementing Runnable
Create run () function and calculate square of a number.
Step 4: Create ThirdThread implementing Runnable
Create run () function and calculate cube of a number.
Step 5: Create the first thread FirstThread and start the Thread.

Source Code:

import java.util.*;
class FirstThread extends Thread
{
public void run()
{
int num=0;
Random r=new Random();
try{
for(int i=0;i<5;i++)
{

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 46


num=r.nextInt(100);
System.out.println("First thread : Genereated number is "+num);
Thread t2=new Thread(new SecondThread(num));
t2.start();
Thread t3=new Thread(new ThirdThread(num));
t3.start();
Thread.sleep(1000);
}
}
catch(InterruptedException e) //or Exception
{
System.out.println(e.getMessage());
}
}
}
class SecondThread implements Runnable
{
public int x;
public SecondThread(int x)
{
this.x=x;
}
public void run()
{
System.out.println("Second Thread: Square of the number is "+x*x);

}
}
class ThirdThread implements Runnable
{
public int x;
public ThirdThread(int x)
{
this.x=x;
}
public void run()
{
System.out.println("Third Thread : Cube of the number is "+x*x*x);
}
}
public class MultiThread
{
public static void main(String args[])
{
FirstThread f=new FirstThread();
f.start();
}

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 47


}

Sample Output:

First thread : Genereated number is 14


Second Thread: Square of the number is 196
Third Thread : Cube of the number is 2744
First thread : Genereated number is 75
Second Thread: Square of the number is 5625
Third Thread : Cube of the number is 421875
First thread : Genereated number is 44
Second Thread: Square of the number is 1936
Third Thread : Cube of the number is 85184
First thread : Genereated number is 16
Second Thread: Square of the number is 256
Third Thread : Cube of the number is 4096
First thread : Genereated number is 74
Second Thread: Square of the number is 5476
Third Thread : Cube of the number is 405224

Laboratory Program 9:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 48


Aim: Introduce java Collections.
Program: Write a program to perform string operations using Array List. 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.

The Collection in Java is a framework that provides an architecture to store and manipulate the group
of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.

Algorithm:
Step 1: Start
Step 2: Create the class arraylistexample. Create the object for the arraylist class.
Step 3: Display the options to the user for performing string handling.
Step 4: Use the method add () to append the string at the end and to insert the string at the particular
index.
Step 5: The function sort () is used to sort the elements in the array list.
Step 6: The function indexof() is used to search whether the element is in the array list or not.
Step 7: The function startsWith () is used to find whether the element starts with the specified character.
Step 8: The function remove () is used to remove the element from the arraylist.
Step 9: The function size () is used to determine the number of elements in the array list.
Step 10: Stop

Source Code:

import java.util.*;
import java.io.*;
public class arraylistexample {
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 5.Display\t" );
System.out.println("Enter the choice ");
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1:
{

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 49


System.out.println("Enter the string ");
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))
{
System.out.println(str1);
}
}
break;
}
case 5:
{
System.out.println("The array list has following elements:"+obj);
break;
}
}
System.out.println("enter 0 to break and 1 to continue");

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 50


ch=Integer.parseInt(in.readLine());
}while(ch==1);
}

Sample Output:

STRING MANIPULATION
******************************
1. Append at end 2.Insert at particular index 3.Search
4.List string that starting with letter 5. Display
Enter the choice
1
Enter the string
FIRST
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. Display
Enter the choice
2
Enter the string
SECOND
Specify the index/position to insert
2
The array list has following elements: [FIRST, SECOND]
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. Display
Enter the choice
3
Enter the string to search
SECOND
Index of: SECOND is 1
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. Display
Enter the choice

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 51


4
Enter the character to List string that starts with specified character
F
FIRST
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. Display
Enter the choice
4
Enter the character to List string that starts with specified character
3
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. Display
Enter the choice
5
The array list has following elements: [FIRST, SECOND]
enter 0 to break and 1 to continue
0

Laboratory Program 10:

Aim: Exception handling in java, introduction to throwable class, throw, throws, finally.
Program: Write a Java program to read two integers a and b. Compute a/b and print, when b is not

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 52


zero. Raise an exception when b is equal to zero.

The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so
that the normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IO
Exception, SQL Exception, Remote Exception, etc.
The Throwable class is the superclass of every error and exception in the Java language. Only objects
that are one of the subclasses this class are thrown by any “Java Virtual Machine” or may be thrown
by the Java throw statement.
throw: The throw keyword is used to transfer control from the try block to the catch block.
throws: The throws keyword is used for exception handling without try & catch block. It specifies
the exceptions that a method can throw to the caller and does not handle itself.
finally: It is executed after the catch block. We use it to put some common code when there are
multiple catch blocks.
Algorithm:
Step 1: Start
Step 2: Create a class RaiseException.
Step 3: Read integer value a,b
Step 4: Use Exception handler try and catch block
Step 5: Perform, Result =a/b
Step 6: No exception, display Result otherwise display the name of exception
Step 7: Stop

Source Code:

import java.util.Scanner;
public class RaiseException
{
public static void main(String args[])
{
int a,b,result;
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of A and B");
a=s.nextInt();
b=s.nextInt();

try{
result=a/b;
System.out.println("Result = "+result);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 53


Sample Output:
Enter the value of A and B
20
2
Result = 10

Enter the value of A and B


20
0
java.lang.ArithmeticException: / by zero

Laboratory Program 11:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 54


Aim: Introduce File operations in java.
Program: 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.

In Java, a File is an abstract data type. A named location used to store related information is known as
a File. There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and Deleting a File.

Algorithm:
Step 1: Start
Step 2: Create a class Filedemo. Get the file name from user
Step 3: Use the file methods and display the information about file
Step 4: use exists () method to find file is exist or not
Step 5: use canRead() method is used to check if the file can read
Step 6: use canWrite() method is used to check can write to file
Step 7: use isDirectory() method is used to display whether it is a directory or not.
Step 8: use isFile() method is used to display whether it is a file or not.
Step 9: use lastModified() method is used to display the last modified information.
Step 10: use length() method is used to display the size of file.
Step 11: use delete() method is used to delete the file.
Step 12: Stop

Source Code:

import java.io.*;
import java.util.*;
public class Filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 55


else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}
Sample Output:

Enter the file name


Box.java
*****************
FILE INFORMATION
*****************
NAME OF THE FILE Box.java
PATH OF THE FILE Box.java
PARENTnull
THE FILE EXISTS
THE FILE CAN BE READ
WRITE OPERATION IS PERMITTED
NOT A DIRECTORY
IT IS A FILE
File last modified 1662575597947
LENGTH OF THE FILE 1432

Laboratory Program 12:

Aim: Introduce java Applet, awt, swings.


Programs:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 56


A) Develop an applet that displays a simple message in centre of the screen.
B) Develop a simple calculator using Swings.

A) Develop an applet that displays a simple message in centre of the screen.


Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many platforms, including Linux, Windows, Mac
OS etc.
AWT stands for Abstract Window Toolkit.

• It is a set of native user interface components.


• It is very robust in nature.
• It includes various editing tools like graphics tool and imaging tools.
• It uses native window-system controls.
• It provides functionality to include shapes, colours and font classes.

Algorithm:
Step 1: Start
Step 2: Define the class SimpleApplet which extends applet
Step 3: Define the method init() by set foreground color as yellow
Step 4: Define the method paint ()
Step 5: Call the method drawstring to display the message
Step 6: Stop

Source Code:

import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet{

public static void init()


{
setForeground(Color.yellow);
}
public static void paint(Graphics g)
{
g.drawString(" Hello World ",80,40);
}
}

Sample Output:

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 57


B) Develop a simple calculator using Swings.
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Swing offers much-improved functionality over AWT, new components, expanded compo-
nents features, excellent event handling with drag and drop support. Swing is Provided to Design a
Graphical User Interfaces
• Swing can be used to build (Develop) The Standalone swing GUI Apps Also as Servlets and
Applets
• Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT
• Swing is Entirely written in Java
• Java Swing Components are Platform-independent And The Swing Components are light-
weight
• Swing Supports Pluggable look and feels And Swing provides more powerful components
Algorithm:
Step 1: Start
Step 2: Define the class calculator which extends applet and implements ActionListner
Step 3: Initialize s0,s1,s2 as string
Step 4: Declare Add, Sub, Mul, Div as Button
Step 5: Declare opr1, opr2, ans as TextField
Step 6: Define the function init()
Step 7: Initialize Add, Sub, Mul, Div, opr1, opr2, ans
Step 8: Set the Layout
Step 9: Call the method add by passing the parameters Add, Sub, Mul, Div, opr1, opr2, ans
seperately
Step 10: Add ActionListener to Add, Sub, Mul, Div, opr1, opr2, ans
Step 11: Define the method actionPerformed()
Step 12: Perform the operations for the buttons Add, Sub, Mul, Div
Step 13: Call the method repaint()
Step 14: Define the method paint()
Step 15: Stop

Source Code:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 58


class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

// default constructor
calculator()
{
s0 = s1 = s2 = "";
}

// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


calculator c = new calculator();

// create a textfield
l = new JTextField(16);

// set the textfield to non editable


l.setEditable(false);

// create number buttons and some operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

// create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 59


b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");

// create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

// create a panel
JPanel p = new JPanel();

// add action listeners


bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 60


p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);

f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 61


else if (s.charAt(0) == '=') {

double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// set the value of text


l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = Double.toString(te);

s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// convert it to string
s0 = Double.toString(te);

// place the operator


s1 = s;

// make the operand blank

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 62


s2 = "";
}

// set the value of text


l.setText(s0 + s1 + s2);
}
}
}
Sample Output:

Viva Questions:

Basics/variables/methods
1. What is JDK/JRE/JVM?
2. What is byte code file?

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 63


3. What is platform independent?
4. What is WORA principle?
5. What is keyword?
6. What is variable?
7. What happens if the variable is final?
8. Can we reassign final variables?
9. What is a method? & it's advantages.
10. Writing methods by passing/returning arguments from/to methods
11. Can we use local variable without assigning a value?

Classes & Objects


1. What is a class writing the class template?
2. What is an object?
3. What is byte code file? How many byte code files will be generated after compiling source
file
4. What will be the name of byte code file?
5. Command used to compile & run java program
6. Can I declare local variable as static?
7. Does java allow global variable?
8. How many types of variables do java supports?
9. How to access static & non static members explain with an example.
10. When to declare data member as static & non static.

Blocks
1. What is block and how many types of blocks available
2. Difference between block & method
3. When static block will execute?
4. When non-static block will execute?
5. How many times static block will execute?
6. How many times non-static block will execute?
7. Can I initialize static data member inside non-static block?
8. Can I initialize non-static member inside static block?

Constructors
1. What is a constructor? Why is it used for?
2. When constructors will be executed? Explain
3. When to go for argument constructor? Explain with an example
4. WAP to demonstrate constructor overloading & what are its advantages.
5. Does the constructor allow return type? If we give what happens
6. Can the constructor be static?
7. Can the constructor be final?
8. What are the access modifiers allowed for constructor?
9. What happens when we create an object explain series of steps

Method overloading
1. What is method overloading explain with an example?
2. Can we overload static methods? WAP to overload main method.
3. Explain how to pass arguments to main method explain.

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 64


4. WAP to overload non-static methods.
5. What are the advantages of method overloading?

Inheritance
1. What is inheritance & what are its advantages
2. Explain types of inheritance.
3. Explain why multiple inheritance is not allowed in java?
4. What is this keyword? Why is it used for? Explain with an example
5. What is super keyword? Why is it used for? Explain with an example
6. Explain constructor calling with an example. What are its advantages?
7. Explain constructor chaining with an example? Why constructor chaining required?
8. Difference between this, super & this (), super ().
9. What is the first statement inside default constructor?
10. What happens if a class is declared as final? Example for final class
11. Explain diamond ring problem.
12. Is Object class a final? Justify
13. Explain what happens when we instantiate subclass.
Packages
1. What is a package? How to create it?
2. Where to write package creation statement?
3. Can one source file contain many packages creation statements?
4. When to use import? Explain with an example
5. Can one source file contain many import statements?
6. In which order package & import keyword should exist in a source file?
7. Explain access modifiers provided by java
8. What is data hiding? How to achieve it?
9. What is encapsulation?
10. What is jar file? Where is rt.jar present? What it contains?
11. Does default member gets inherited across the package
12. Can I access public members outside the package if the class is default?
13. Can I declare a class as private? What access modifiers can I provide for a class
14. What is the name of byte code file of inner class

abstract method & abstract class


1. What is abstract method?

2. What is abstract class?


3. Where we provide definition for the abstract methods? What if we failed to provide?
4. When to declare a method abstract?
5. When to go for abstract class?
6. Can abstract class be final? Why?
7. Can i declare static method as abstract? Why?
8. Can i change the access modifiers while providing implementation? For the abstract methods.
9. Can the abstract class be instantiated? Why
10. Does abstract class allows constructor? If yes, explain with an Example it's usage
11. Does abstract class allows static members? If yes, how to access them? Write an example.
12. Can i declare private method as abstract? Why?
13. Advantages of abstract class

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 65


Interface
1. What is an interface, write the template
2. Can an interface extend from another interface? Write an example
3. Can an interface extend from more than 1 interface? Write an example
4. What is marker interface? Examples.
5. What is functional interface? Examples
6. Does interface allows concrete methods?
7. Difference between abstract class & interface?
8. When to go for interface? When to go for abstract class?
9. Can one interface have multiple implementation classes? Write an example
10. Advantages of interfaces.
11. Explain the importance of interface type reference var.
Typecasting
1. What is type casting? Explain data typecasting with example.
2. What is narrowing? Why narrowing should be done by user explicitly.
3. What is widening? Why compiler will do it implicitly
4. Explain class typecasting with an example.
5. What is up casting? What is down casting?
2. What is the advantage of class type casting, Explain with an example?
3. Explain instanceof operator with an example?
6. What is return type of instanceof?
7. What is generalization & specialization explain with an example.
8. When we get ClassCastException?

Method Overriding
1. What is overriding? Justify how overriding is runtime polymorphism
2. Difference between overloading & overriding
3. Which methods cannot be overridden?
4. Can we override final methods?
5. Can we override static methods?
6. Can we change the access modifier while overriding method?
7. Can we change the return type while overriding method?
8. Can we override abstract method?
9. Can we override concrete method as abstract? Justify its advantages.
10. What is polymorphism? Explain its types with example
11. When to go for overriding? Explain
12. Can we override constructor? Why?
13. While overriding, why co-variant type changes allowed & why not contra variant?
14. Difference between compile time & run time polymorphism

Java Bean Class


1. What is java bean class? Write an example
2. What are getters & setters? Write the syntax of it.

Private Constructor & Singleton Class


1. What is the default access modifier of constructor?
2. Can the constructor be private? Then, how to create an object. Explain with an example
3. What is singleton class? Write an example

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 66


4. Explain how to achieve constructor chaining in singleton class.
5. Advantages of singleton class

Object class & its methods


1. What is object class? Where is it present?
2. Is Object class final? Justify
3. Mention the methods Object class
4. Which methods of Object class cannot be overridden
5. Explain the behavior of toString(), hashCode() & equals(Oject obj) .
6. WAP to compare whether two mobiles are same or not w.r.t name, price & ram. Program
should also display states of an object
7. WAP to compare whether two cars are same or not w.r.t name, price & color. Program should
also display states of an object
8. WAP to compare whether two watches are same or not. Program should also display states
of an object
9. What is the difference between class & Class?
10. How to identify fully qualified name of the class when we have the object.

String class & its methods


1. What is String class? Where is it present?
2. What is the relationship between String & Object class?
3. What methods of Object class overridden in String class & how?
4. Explain constructors of String class.
5. How to convert array of characters to String?
6. What is immutable? Why String is immutable?
7. Justify how String is immutable.
8. What are the advantages & disadvantages of immutable
9. What is difference between String, StringBuilder & StringBuffer?
10. Explain when the objects will be created in SCP & heap memory?
11. Which methods Object class overridden in StringBuffer & StringBuilder?
12. What is the difference between final & immutable?
13. Why String is final?
14. Why do you think there are two ways of creating object of String class
15. How to create our own immutable class

Exception Handling
1. What is exception? Why to handle it?
2. If user don’t handle exception, then who will handle?
3. What’s benefit of user handling exception?
4. Why we shouldn’t allow default exception handler to handle exception
5. Explain exception hierarchy in java
6. How many handlers does java provides to handle exception
7. Explain try catch block with an example
8. What statements we should write in the try block?
9. Explain what happens when exception occurs in the try block
10. Does catch block execute always?
11. Can one try block have multiple catch blocks? If yes which catch block will execute? What
happens if the corresponding catch block not found?

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 67


12. Can we write generalized catch block & specialized catch block together?
13. How many exceptions occur in single try block? How to handle more than one exception?
14. Explain multiple try catch blocks.
15. What is the use of throw keyword
16. Explain the difference between JVM creating an exception object & user creating an excep-
tion object?
17. Explain exception propagation? & when exception object will propagate?
18. What is checked exception & unchecked exception?
19. When to use throws? Explain with an example.
20. Difference between checked exception & unchecked exception?
21. Difference between throw & throws
22. Difference between throw & Throwable
23. What is the importance of finally block? Explain with an example.
24. Difference between final, finally & finalize()
25. WAP to demonstrate custom checked exception
26. WAP to demonstrate custom unchecked exception

Collection Framework Library


1. What is collection? & why to use collection?
2. Difference between array & collection
3. What is collection framework library & where is it present
4. Explain classes & interfaces available in collection framework library
5. Explain Collection (I) methods.
6. What is Collection & Collections
7. Explain the properties of List(I)
8. Explain the implementation classes of List(I)
9. Explain how the objects will be stored in ArrayList collection
10. Difference between ArrayList & LinkedList
11. When ArrayList is best choice
12. When LinkedList is best choice
13. Difference between List(I) & Set(I)
14. Explain the properties of Set(I)
15. Difference between HashSet & LinkedHashSet
16. Explain the cursors of java collection framework library
17. Explain the working behavior of Iterator(I) & ListIterator(I)
18. Difference between Enumeration(I), Iterator(I) & ListIterator(I)
19. Explain the properties SortedSet(I)
20. Explain the properties of TreeSet.
21. Explain Map(I) methods
22. What is an entry?
23. Difference between HashMap & HashTable

Threads
1. What is a process?
2. What is a thread?
3. What is the difference between thread & process?
4. How to create a thread in java?
5. Does thread implement their own stack, if yes how?

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 68


6. Which way of creating thread is good? By extending thread class or by Implementing
Runnable(I)
7. How can you ensure all threads that started from main must end in order in which they started
and also main should end in last?
8. Difference between start () & run () method
9. What is thread safe?
10. What is race condition? How can we solve it?
11. What is thread synchronization? How to achieve it?
12. Can we start the running thread again?
13. Can we start the dead thread again?
14. How threads communicate between each other?
15. Why wait (), notify () and notifyAll () are in Object class and not in Thread class?
16. What are daemon threads?
17. Difference between yield() & join() method
18. Difference between sleep() & wait() method
19. Difference between class level lock & object level lock?
20. Explain thread life cycle?

DEPT. OF CS&E, CANARA ENGINEERING COLLEGE, MANGALURU 69

You might also like