Ooc Lab Manual
Ooc Lab Manual
MISION
Course Objectives:
2 .Analyze the necessity for Object Oriented Programming paradigm over structured
programming and become familiar with the fundamental concepts in OOP.
3 .Demonstrate the ability to design and develop java programs, analyze, and interpret object
oriented data and document results.
4 . Apply the concepts of multiprogramming, exception/event handling, abstraction to develop
robust programs.
5. Develop user friendly applications using File I/O and GUI concepts.
PEO 1 : To provide our graduates with a strong foundation in mathematics, programming, scientific
and engineering fundamentals necessary to formulate, analyze and solve IT related engineering
problems, and to prepare them for higher learning.
PROGRAM OUTCOMES(POs):
5.Modern tool usage : Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations
6.The engineer and society : Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice
7.Environment and sustainability : Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development
8.Ethics : Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice
9.Individual and team work : Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings
10.Communication : Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions
PSO 1 : To understand and develop programs in core areas of Computer Science & Engineering
related to data structures and algorithms, web design, database management system, machine
Learning and Networking to provide solutions for real world problems.
PSO 3 : To cultivate ethical skills and cater the needs of industry and society with the
knowledge of management and entrepreneurship, energy and environment, principles of
software engineering and universal human value courses.
CO PO Mapping:
CO-PSO Mapping:
EXPERIMENT LIST
PART A
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 and Phone Write a Java program to create n Student objects and print the USN, Name, Branch,
and Phone of these objects with suitable headings.
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.
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.
12. Develop an applet that displays a simple message in center of the screen. Develop a simple
calculator using Swings.
Eclipse:
Eclipse is an integrated development environment (IDE) for Java and other programming languages like
C, C++, PHP, and Ruby etc. Development environment provided by Eclipse includes the Eclipse Java
development tools (JDT) for Java, Eclipse CDT for C/C++, and Eclipse PDT for PHP, among others.
This tutorial will teach you how to use Eclipse in your day-2-day life while developing any software
project using Eclipse IDE. We will give special emphasis on Java project.
The New Java Project wizard can be used to create a new java project. There are many ways to open
this wizard −
The New Java Project Wizard has two pages. On the first page −
You can use the New Java Class wizard to create a Java class. The Java Class wizard can be invoked in
different ways −
Before bringing up the New Java Class wizard, if possible, select the package in which the class is to be
created so that the wizard can automatically fill in the package name for you.
The easiest way to install eclipse IDE is to download and run the installer. To download the
Eclipse installer, go to this url and select the installer executable as per your operating system
platform.
Then, select the closest mirror site to download the required package.
For Windows users, select the folder, e.g., C:/Users/[username]/Downloads to download the
installer.
For Mac users, select the folder /Users/[username]/Downloads.
Here, “[username]” represents the username of the operating system you are using.
After the download is completed, execute the Eclipse installer. You may need to extract the
content if you use Mac or Linux.
You would also get a security warning for executing a file downloaded from the Internet. Verify
if the publisher is the Eclipse Foundation and choose to continue with the file’s execution as you
can trust this source.
When the installer prompts you to choose the installation location, keep this as your default user
directory and begin the installation process. Windows users can also create start menu entries
and desktop shortcuts.
Step 4 - Launching the Eclipse IDE
After the installation is complete, go to the local folder on your system where you installed the
application in the previous step. Find the executable file for the Eclipse IDE and run it to launch
the IDE.
During the first run, Eclipse asks users to specify a folder to create the workspace for their
projects. After this is provided, the Eclipse IDE gets launched. This completes the installation
process.
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: root=
root=-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.
PROGRAM:
Import java.util.Scanner;
public class Quadratic
{
Public static void main(String[]args)
{
Output:
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
PROGRAM:
import java.util.*;
public class
Student
{
String usn,name,branch;
long phone;
void displayStudent()
{
System.out.println("**********************");
System.out.println("USN= "+usn);
System.out.println("NAME= "+name);
System.out.println("BRANCH= "+branch);
System.out.println("PHONE NUMBER= "+phone);
System.out.println("**********************");
}
for(int i=0;i<n;i++)
st[i]=new Student(); for(int
j=0;j<n;j++)
{
}
for( int m=0;m<n;m++)
{
System.out.format("Student %d details are\n",m+1);
st[m].displayStudent();
}
}
}
OUTPUT:
3.A. Write a program to check prime number
B.Write a program for Arithmetic calculator using switch case menu
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.
PROGRAM :3A
Output:
3. B.Write a program for Arithmetic calculator using switch case menu
import java.util.*;
class Switch
{
public static void main(String[] args)
{
Scanner inp = new Scanner(System.in);
System.out.println("Enter the Operator (+,-,*,/) : ");
char operator = inp.next().charAt(0);
System.out.println("Enter the First Operand : ");
double first = inp.nextDouble();
System.out.println("Enter the Second Operand : ");
double second = inp.nextDouble();
double result = 0;
switch(operator)
{
case '+':
result = first + second;
System.out.println("The Result is : "+first+" "+operator+" "+second+" = "+result); break;
case '-':
result = first - second;
System.out.println("The Result is : \n "+first+" "+operator+" "+second+" = "+result); break;
case '*':
result = first * second;
System.out.println("The Result is : "+first+" "+operator+" "+second+" = "+result); break;
case '/':
result = first / second;
System.out.println("The Result is : \n "+first+" "+operator+" "+second+" = "+result); break;
default :
System.out.println("Invalid Operator"); break;
}
}
}
OUTPUT:
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.
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
PROGRAM:
import java.util.Scanner;
class Staff
{
String staffId;
String name;
long phone;
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
{
String domain;
int n;
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: ");
n = scanner.nextInt();
System.out.println("\n");
}
public void display()
{
super.display();
System.out.println("Domain: " + domain);
System.out.println("Publications:"+n);
System.out.println("\n");
}
}
class Technical extends Staff
{
String skill;
public void accept()
{
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter technical Skills: ");
skill = scanner.nextLine();
System.out.println("\n");
}
public void display()
{
super.display();
System.out.println("Technical Skills: " + skill);
System.out.println("\n");
}
}
class Contract extends Staff
{
int period;
public void accept()
{
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Period: ");
period = scanner.nextInt();
System.out.println("\n");
}
public void display()
{
super.display();
System.out.println("Contract Period: " + period);
}
}
class Four
{
public static void main(String[] args)
Teaching teaching = new Teaching(); System.out.println("Enter
the details of Teaching Staff"); teaching.accept();
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
Demonstrating Method overloading
class MOverloading
{
/
/adding two integer numbers
int add(int a, int b)
{
int sum = a+b; return sum;
}
OUTPUT:
5B. Constructor Overloading
Public class Constructor
{
int id;
String name;
Constructor()
{
System.out.println("This is Default constructor");
System.out.println("Student Id: "+id+"\nStudentName: "+name);
}
Constructor(int i, String n)
{
System.out.println("This is Parameterized Constructor:");
id = i;
name=n;
System.out.println("Student Id:"+id+"\nStudentName:"+name);
}
Public static void main(String[]args)
{
Constructor s=new Constructor();
Constructor student=newConstructor(10,"David");
}
}
Output:
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: Introduce the concept of Abstraction, 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
PROGRAM:
CurrencyC.java
package cc;
import java.util.*;
{
double inr,usd;
double euro,yen;
{
System.out.println("Enter dollars to convert into Rupees:");
usd=in.nextInt();
inr=usd*81.83;
System.out.println("Dollar ="+usd+" equal to INR="+inr);
System.out.println("\n");
}
public void rupeetodollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();
usd=inr/81.83;
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*79.06;
System.out.println("Euro ="+euro+" equal to INR="+inr);
System.out.println("\n");
}
public void rupeetoeuro()
{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();
euro=(inr/79.06);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
System.out.println("\n public void yentoruppe()
{
System.out.println("Enter Yen to convert into Rupees:"); yen=in.nextInt();
inr=yen*0.57;
System.out.println("Yen ="+yen+" equal to INR="+inr); System.out.println("\n");
}
public void ruppetoyen()
{
System.out.println("Enter Rupees to convert into Yen:"); inr=in.nextInt();
yen=(inr/0.57);
System.out.println("INR="+inr +"equal to YEN"+yen); System.out.println("\n");
}
}
DistanceC.Java
package dc;
import java.util.*;
{
double km,m,miles;
{
System.out.println("Enter the distance in meter"); m=in.nextDouble();
km=(m/1000);
System.out.println(m+"m" +" is equal to "+km+"km"); System.out.println("\n");
}
public void kmtom()
{
System.out.println("Enter the distance in Kilometer"); km=in.nextDouble();
m=km*1000;
System.out.println(km+"km" +" is equal to "+m+"m"); System.out.println("\n");
}
public void milestokm()
{
System.out.println("Enter the distance in miles"); miles=in.nextDouble();
km=(miles*1.60934);
System.out.println(miles+"miles" +" is equal to "+km+"km");
System.out.println("\n");
}
public void kmtomiles()
{
System.out.println("Enter the distance in km");
km=in.nextDouble();
miles=(km*0.621371);
System.out.println(km+"km" +" is equal to "+miles+"miles");
}
}
TimeC.java
package tc;
import java.util.*;
{
int hours,seconds,minutes;
Scanner in = new Scanner(System.in);
public void hourstominutes()
{
System.out.println("Enter the no of Hours to convert into minutes");
hours=in.nextInt();
minutes=(hours*60);
System.out.println("Minutes: " + minutes);
}
public void minutestohours()
{
System.out.println("Enter the no of Minutes to convert into Hours");
minutes=in.nextInt();
hours=minutes/60;
System.out.println("Hours: " + hours);
}
public void hourstoseconds()
{
System.out.println("Enter the no of Hours to convert into Seconds");
hours=in.nextInt();
seconds=(hours*3600);
System.out.println("Seconds: " + seconds);
}
public void secondstohours()
{
System.out.println("Enter the no of Seconds to convert into Hours");
seconds=in.nextInt();
hours=seconds/3600;
System.out.println(seconds+"seconds"+ " is equal to "+hours+"hour");
}
}
Main Class:
import cc.*;
import dc.*;
import tc.*;
{
public static void main(String args[])
{
CurrencyC obj=new CurrencyC();
DistanceC obj1=new DistanceC();
obj.dollartorupee();
obj.rupeetodollar();
obj.eurotorupee();
obj.rupeetoeuro();
obj.yentoruppe();
obj.ruppetoyen();
obj1.mtokm();
obj1.kmtom();
obj1.milestokm();
obj1.kmtomiles();
obj2.hourstominutes();
obj2.minutestohours();
obj2.hourstoseconds();
obj2.secondstohours();
}
}
Output:
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
PROGRAM:
interface Resume
{
void biodata();
}
class Teacher implements Resume
{
String
name,qualification,achievements;
float experience;
public void biodata()
{
name="Rohan";
qualification="M.Tech"; achievements="Q1
publication"; experience=14.8f;
System.out.println("Teacher Resume");
System.out.println("Name : " +name);
System.out.println("Qualification : "+qualification);
System.out.println("Achievements : "+achievements);
System.out.println("Experience : "+experience);
}
}
class Student implements Resume
{
String
name,discipline;
float result;
public void biodata()
{
name="Rahul Sharma";
result=9.8f;
discipline="Computer Science and Engineering";
System.out.println("");
System.out.println("Student Resume");
System.out.println("Name : " +name);
System.out.println("Result : "+result+" cgpa");
System.out.println("Discipline : "+discipline);
}
}
OUTPUT:
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 computesthe square of the
number and prints; third thread will print the value of cube of the number.
Aim: Demonstrate creation of threads using Thread class and Runnable interface, multi-
threaded 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.
5.Inside the ‘run’ method of this class generate random number and pass this number to
constructor ‘Square’.
6.Call ‘run’ method in ‘Square’ class using t1.start() method to find the square of random number.
Inside the ‘run’ method of this class generate random number and pass this number to
constructor ‘Cube’.
7.Call ‘run’ method in ‘Cube’ class using t1.start() method to find the cube of
random number.
8.Create main class and call the method of Number class to display the output.
9.Stop
PROGRAM :
import
java.util.Random;
class Square extends
Thread
{
int x;
Square(int
n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
}
}
OUTPUT:
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
PROGRAM:
import java.util.*;
public class ArrayL
{
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
public void arraydisplay()
{
list.add("CSE");//Adding object in arraylist
list.add("ISE");
list.add("ME"); System.out.println("ArrayList
element are"); System.out.println(list);
System.out.println("");
}
public void appendatend()
{
System.out.println("Enter the element to append at end");
Scanner scob1=new Scanner(System.in);
String ele=scob1.next();
list.add(ele);
System.out.println(list);
System.out.println("");
}
public void insertatpos()
{
System.out.println("Enter the position and element to insert"); Scanner
scob1=new Scanner(System.in);
int posind=scob1.nextInt(); String
ele=scob1.next();
list.add(posind,ele);
System.out.println(list);
System.out.println("");
}
public void searchele()
{
System.out.println("Enter the Array element to search"); Scanner
scobj=new Scanner(System.in);
String arele=scobj.next(); int
in=list.indexOf(arele); if(in==-
1)
{
System.out.println("Element not found");
}
else
{
System.out.println(“Elements found at”,+in)
}
}
void print()
{
Scanner nip=new Scanner(System.in);
System.out.println("Enter the starting charecter to print strings"); char
inputc=nip.next().charAt(0);
String strc=Character.toString(inputc);
System.out.println("String starting with character "+strc);
for(int i=0;i<list.size();i++)
{
if(list.get(i).startsWith(strc))
{
System.out.println(list.get(i));
}
}
}
public static void main(String args[])
{
ArrayL obj=new ArrayL();
obj.arraydisplay();
obj.appendatend();
obj.insertatpos(); obj.searchele();
obj.print();
}
}
OUTPUT:
10. Write a Java program to read two integers a and b. Compute a/b and print, when bis 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.
PROGRAM:
import java.util.*;
public class TryP
{
int c;
void div(int a,int b)
{
try
{
c=a/b;
System.out.println("Result="+c)
;
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide by zero");
}
}
public static void main(String args[])
{
TryP obj=new TryP();
Scanner in=new Scanner(System.in);
System.out.println("Enter the values of a and
b"); int no1=in.nextInt();
int
no2=in.nextInt();
obj.div(no1,no2);
}
}
OUTPUT:
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
inJava
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 ‘File Demo’ 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
PROGRAM:
import java.io.File;
import java.util.Scanner;
class FileP
{
public static void main(String args[ ])
{
Scanner obj=new Scanner(System.in);
String fname=obj.next();
File f1 = new File(fname); System.out.println("File
Name: " + f1.getName()); f1.setWritable(false);
System.out.println(f1.exists() ? "File exists" : "File does not exist");
System.out.println(f1.canWrite() ? "File is writeable" : "File is not writeable");
System.out.println(f1.canRead() ? "File is readable" : "File is not readable");
String fileName = f1.toString();
int index = fileName.lastIndexOf('.');
if(index > 0)
{
{
else
S t.println("File type is " + type);
t
r
i System.out.println("File doesn't have type");
n }
g
t
y
p
e
f
i
l
e
N
a
m
e
.
s
u
b
s
t
r
i
n
g
(
i
n
d
e
x
1
)
;
S
y
s
t
e
m
.
o
u
System.out.println("File size: " + f1.length() + " Bytes");
}
}
12. A. Develop an applet that displays a simple message in center of the screen.
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.
PROGRAM:
import
java.applet.Applet;
import
java.awt.Graphics;
/*
<applet code="AppletP.class" width="300" height="300">
</applet>
*/
public class AppletP extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to applet",100,150);
}
}
OUTPUT:
12. B. Develop a simple calculator using Swings.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
t=new JTextField();
t.setBounds(30,10,165,35);
b0=new JButton("0");
b0.setBounds(30,50,45,40);
b1=new JButton("1");
b1.setBounds(70,50,45,40);
b2=new JButton("2");
b2.setBounds(110,50,45,40);
b3=new JButton("3");
b3.setBounds(150,50,45,40);
b4=new JButton("4");
b4.setBounds(30,90,45,40);
b5=new JButton("5");
b5.setBounds(70,90,45,40);
b6=new JButton("6");
b6.setBounds(110,90,45,40);
b7=new JButton("7");
b7.setBounds(150,90,45,40);
b8=new JButton("8");
b8.setBounds(30,130,45,40);
b9=new JButton("9");
b9.setBounds(70,130,45,40);
bdot=new JButton(".");
bdot.setBounds(110,130,45,40
); badd=new JButton("+");
badd.setBounds(150,130,45,40
);
bsub=new JButton("-");
bsub.setBounds(30,170,45,40);
bmul=new JButton("*");
bmul.setBounds(70,170,45,40);
bdiv=new JButton("/");
bdiv.setBounds(110,170,45,40);
beq=new JButton("=");
beq.setBounds(150,170,45,40);
bclr=new JButton("CLR");
bclr.setBounds(30,210,165,40
);
frame.add(t);
frame.add(b0);
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
frame.add(b6);
frame.add(b7);
frame.add(b8);
frame.add(b9);
frame.add(bdot)
;
frame.add(badd
);
frame.add(bsub
);
frame.add(bmul
);
frame.add(bdiv)
;
frame.add(beq);
frame.add(bclr);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
badd.addActionListener(this
);
OOP With Java Laboratory
21CSL35 21CSL35
bmul.addActionListener(this);
bdiv.addActionListener(this);
bdot.addActionListener(this);
beq.addActionListener(this);
bclr.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bclr)
{
t.setText("");
}
if(e.getSource()==b0)
{
t.setText(t.getText().concat("0"));
}
if(e.getSource()==b1)
{
t.setText(t.getText().concat("1"));
}
if(e.getSource()==b2)
{
t.setText(t.getText().concat("2"));
}
if(e.getSource()==b3)
{
t.setText(t.getText().concat("3"));
}
if(e.getSource()==b4)
{
t.setText(t.getText().concat("4"));
}
if(e.getSource()==b5)
{
t.setText(t.getText().concat("5"));
}
if(e.getSource()==b6)
{
t.setText(t.getText().concat("6"));
}
if(e.getSource()==b7)
{
t.setText(t.getText().concat("7"));
}
if(e.getSource()==b8)
{
t.setText(t.getText().concat("8"));
}
if(e.getSource()==b9)
t.setText(t.getText().concat("9"));
}
if(e.getSource()==bdot)
{
t.setText(t.getText().concat("."));
}
if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
op=1;
t.setText("");
}
if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
op=2;
t.setText("");
}
if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
op=3;
t.setText("");
}
if(e.getSource()==bdiv)
{
a=Double.parseDouble(t.getText());
op=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
switch(op)
{
case 1:res=a+b;
break;
case 2:res=a-b;
break;
case 3:res=a*b;
break;
case 4:res=a/b;
break;
}
t.setText(""+res);
}
}
}
OUTPUT: