Lab Manual - OOC - 21CSL35 (Final)
Lab Manual - OOC - 21CSL35 (Final)
LABORATORY MANUAL
PREPARED BY
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.
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.
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
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.
CO 5. Develop user friendly applications using File I/O and GUI concepts.
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.
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
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.
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();
Sample Output:
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.
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();
Sample Output:
Aim: Discuss the various Decision-making statements, loop constructs in java Program:
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
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;
Sample Output:
3B. Write a program for Arithmetic calculator using switch case menu
The switch statement selects one of many code blocks to be executed:
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;
}
}
}
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
Laboratory Program 4:
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
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:
}
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);
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
Laboratory Program 5:
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
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");
}
Sample Output:
// 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
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:
double width;
double height;
double depth;
Sample Output:
Laboratory Program 6:
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:
Source Code:
import java.util.*;
package timeconversion;
import java.util.*;
//distanceconversion package
package distanceconversion;
import java.util.*;
class converter {
}
}
}
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
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
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
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
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
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
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
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:
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:
interface Resume {
void biodata();
}
@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();
@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();
Sample Output:
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++)
{
}
}
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();
}
Sample Output:
Laboratory Program 9:
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:
{
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
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
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);
}
}
}
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 ");
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{
Sample Output:
Source Code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
// create a textfield
static JTextField l;
// 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 textfield
l = new JTextField(16);
// equals button
beq1 = new JButton("=");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
double 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;
// convert it to string
s0 = Double.toString(te);
Viva Questions:
Basics/variables/methods
1. What is JDK/JRE/JVM?
2. What is byte code file?
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.
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
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
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?
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?