Java Lab Manual
Java Lab Manual
LAB MANUAL
Prepared by
i
INSTITUTE OF AERONAUTICAL ENGINEERING
(Autonomous)
Dundigal, Hyderabad - 500 043
ii
PROGRAM SPECIFIC OUTCOMES (PSO'S)
PSO – I Professional Skills: The ability to understand, analyze and develop computer programs in the
areas related to algorithms, system software, multimedia, web design, big data analytics, and
networking for efficient design of computer-based systems of varying complexity.
PSO – II Problem-Solving Skills: The ability to apply standard practices and strategies in software
project development using open-ended programming environments to deliver a quality product
for business success.
PSO – III Successful Career and Entrepreneurship: The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an
entrepreneur, and a zest for higher studies.
iii
INSTITUTE OF AERONAUTICAL ENGINEERING
(Autonomous)
Dundigal, Hyderabad - 500 043
Program
Program Outcomes Specific
S. No Experiment
Attained Outcomes
Attained
PO1, PO2, PO5
1. BASIC PROGRAMS PSO2
iv
INSTITUTE OF AERONAUTICAL ENGINEERING
(Autonomous)
Dundigal, Hyderabad - 500 043
Program
Program Outcomes Specific
Course Outcomes
Objectives
PSO PSO PSO
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
1 2 3
√ √ √ √
I
√ √ √ √ √
II
√ √ √ √ √
III
√ √ √ √ √
IV
v
SYLLABUS:
LIST OF EXPERIMENTS
WEEK-1 BASIC PROGRAM
1. Try debug step by step with small program of about 10 to 15 lines which contains at least one if
else condition and a for loop.
2. Write a java program that prints all real solutions to the quadratic equation ax 2+bx+c=0. Read in
a, b, c and use the quadratic formula.
3. The Fibonacci sequence is defined by the following rule. The first two values in the sequence are
1 and 1. Every subsequent value is the sum of the two values preceding it. Write a java program
that uses both recursive and non recursive functions.
4. Write a java program for sorting a given list of names in ascending order.
WEEK-2 POLYMORPHISM, INHERITANCE
1. Design a class to represent a bank account. Which include contains account number, name of the
depositor, type of the account, balance amount in the account. Use constructors to assign initial
values, to Deposit an amount, to Withdraw amount after checking balance, to display name and
balance. .(Hint: constructor overloading).
2. Design a class to represent a bank account. Which include contains account number, name of the
depositor, type of the account, balance amount in the account. Define Methods, to assign initial
values, to Deposit an amount, to Withdraw amount after checking balance, to display name and
balance.(Hint: method overloading).
vi
WEEK-3 ABSTRACT CLASS, INTERFACE
1. Write a java program to create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only
the method print Area () that prints the area of the given shape.
2. Write a java program to create an interface named Shape that contains empty method named Area
() and Perimeter(). Provide two classes named Triangle and Circle such that each one of the
classes implements Shape. Each one of the classes contains only the method Area () and
Perimeter().that prints the area and perimeter() of the given shape.
WEEK-4 EXCEPTIONS
1. You will be given two integers x and y as input, you have to compute x/y. Implement a class
which raise an exception if x and y are not signed integers or if y is zero.
3. Write a program that creates a user interface to perform integer division. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the
Result field when the Divide button is clicked. If Num1 and Num2 were not integers, the program
would throw a Number Format Exception. If Num2 were zero, the program would throw an
Arithmetic Exception Display the exception in a message dialog box.
WEEK-5 MULTITHREADING
WEEK-5
2. Write a java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread computes
the square of the number and prints. If the value is odd, the third thread will print the value of
cube of the number.
vii
2. Write a java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (/t). It takes
0name or phone number as input and prints the corresponding other value from the hash table.
Hint: Use hash tables.
4. Write a java program t hat takes tab separated data (one record per line) from a text file and insert
them into a database.
WEEK-8 EVENT HANDLING, AWT
1. Write a java program that simulates a traffic light. The program lets the user select one of three
lights: Red, Yellow or Green with radio buttons. On selecting a button an appropriate message
with “STOP” or “READY” or ”GO” should appear above the buttons in selected color. Initially,
there is no message shown.
2. Write a java program that handles all mouse events and shows the event name at the center of the
window when a mouse event is fired. Use adapter classes.
2. Suppose that table named table.txt is stored in a text file. The first line in the file is the header,
and the remaining lines correspond to rows in the table. The elements are separated by commas.
Write a java program to display the table using labels in grid layout.
WEEK-10 APPLETS
1. Develop an applet that displays a simple message.
2. Develop an applet that receives an integer in one text field and computes its factorial value and
returns it in another text field, when the button named “compute” is clicked.(Hint: Applet).
ADDITIONAL PROGRAMS
1. Design a class to represent a Student details include the Student ID, Name of the Student, Branch,
year, location and college. Assign initial values using constructor. Calculate average of marks of
6 subjects and calculate attendance percentage.
2. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse,
Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism
3. Write a program that creates three threads. First thread displays “Good Morning” every one
second, the second thread displays “Hello” every two seconds and the third thread displays
“Welcome” every three seconds.
4. Write an Applet that computes the payment of a loan on the amount of the loan, the interest rate
viii
and the number of months. It takes one parameter from the browser. Monthly; if true, the interest
rate is per month, otherwise the interest rate is annual.
5. Write a java programs to find factorial of a number. user is allowed to enter a number into the text
field whose factorial is to be determined. On pressing the button the value of the text field is
firstly converted into integer and then processed to find its factorial. The result will get displayed
in another text field.(Hint: use swings).
Reference Books:
1. P. J. Deitel, H. M. Deitel, “Java for Programmers”, Pearson Education, PHI, 4th Edition, 2007.
2. P. Radha Krishna, “Object Oriented Programming through Java”, Universities Press, 2nd Edition, 2007
3. Bruce Eckel, “Thinking in Java”, Pearson Education, 4th Edition, 2006.
4. Sachin Malhotra, Saurabh Chaudhary, “Programming in Java”, Oxford University Press, 5 th Edition,
2010.
Web References:
1. www.niecdelhi.ac.in
2. https://www.linkedin.com/in/achin-jain-85061412
3. www.rank1infotech.com
SOFTWARE AND HARDWARE REQUIREMENTS FOR A BATCH OF 36 STUDENTS:
HARDWARE: Intel Desktop Systems: 36 nos
Printers: 02
SOFTWARE: System Software: Microsoft Windows 7 Academic Get Genuine Legalization License
Application Software‟s: MS Office, Antivirus (Symantec Endpoint Protection 12.1.5)
ix
INDEX
PAGE
S.NO LIST OF EXPERIMENTS
NO
BASIC PROGRAMS
Write a java program that prints all real solutions to the quadratic
2. 5
WEEK-1 equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula.
The Fibonacci sequence is defined by the following rule. The first two
values in the sequence are 1 and 1. Every subsequent value is the sum
3. 8
of the two values preceding it. Write a java program that uses both
recursive and non recursive functions.
POLYMORPHISM, INHERITANCE
a
1. Design a class to represent a bank account. Which include contains
.
account number, name of the depositor, type of the account, balance
amount in the account. Use constructors to assign initial values, to 15
Deposit an amount, to Withdraw amount after checking balance, to
display name and balance. .(Hint: constructor overloading).
WEEK-2 b
2. Design a class to represent a bank account. Which include contains
.
account number, name of the depositor, type of the account, balance
amount in the account. Define Methods, to assign initial values, to 19
Deposit an amount, to Withdraw amount after checking balance, to
display name and balance.(Hint: method overloading).
3. c
Write a java program to implement method overriding. 22
.
1. a
Write a java program to create an abstract class named Shape that
WEEK-3 .
contains two integers and an empty method named print Area ().
Provide three classes named Rectangle, Triangle and Circle such that
24
each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given
shape.
x
2. b
Write a java program to create an interface named Shape that contains
.
empty method named Area () and Perimeter (). Provide two classes
named Triangle and Circle such that each one of the classes implements 26
Shape. Each one of the classes contains only the method Area () and
Perimeter ().that prints the area and perimeter () of the given shape.
EXCEPTIONS
1. You
a will be given two integers x and y as input, you have to compute 30
.
x/y. Implement a class which raise an exception if x and y are not
signed integers or if y is zero.
2. Write
b a java program to implement user defined exceptions.
32
WEEK-4 .
3. Write
c a program that creates a user interface to perform integer
.
division. The user enters two numbers in the text fields, Num1 and
Num2. The division of Num1 and Num2 is displayed in the Result field
when the Divide button is clicked. If Num1 and Num2 were not 34
integers, the program would throw a Number Format Exception. If
Num2 were zero, the program would throw an Arithmetic Exception
Display the exception in a message dialog box.
MULTITHREADING
a
1. Write a java program that implements thread class methods.
37
.
b
2. Write a java program that implements a multi-thread application that
WEEK-5
. three threads. First thread generates random integer every 1 second
has
and if the value is even, second thread computes the square of the 39
number and prints. If the value is odd, the third thread will print the
value of cube of the number.
c
3. Write a java program that implements producer consumer program.
43
.
FILES
a
1. Write a java program that reads a file name from the user, and then
WEEK-6 .
displays information about whether the file exists, whether the file is
46
readable, whether the file is writable, the type of file and the length of
the file in bytes.
b
2. Write a java program that displays the number of characters, lines and
48
.
words in a text file.
xi
c
3. Write a java program that reads a file and displays the file on the screen
50
.
with line number before each line.
JDBC
1. a
Write a java program that connects to a database using JDBC and does
52
.
add, delete, modify and retrieve operations.
2. b
Write a java program that loads names and phone numbers from a text
. where the data is organized as one line per record and each field in
file
WEEK-7 a record are separated by a tab (/t). It takes a name or phone number as 57
input and prints the corresponding other value from the hash table.
Hint: Use hash tables.
3. c
60
.
Implement the above program with database instead of a text file.
4. d
Write a java program t hat takes tab separated data (one record per line)
64
.
from a text file and insert them into a database.
a
1. Write a java program that simulates a traffic light. The program lets the
.
user select one of three lights: Red, Yellow or Green with radio buttons.
On selecting a button an appropriate message with “STOP” or 66
“READY” or ”GO” should appear above the buttons in selected color.
WEEK-8 Initially, there is no message shown.
b
2. Write a java program that handles all mouse events and shows the event
.
name at the center of the window when a mouse event is fired. Use 70
adapter classes.
c
3. Write a java program to demonstrate the key event handlers.
73
.
1. Write
a a java program that works as a simple calculator. Use a grid
.
layout to arrange buttons for the digits and for the +,-,*, % operations.
75
Add a text field to display the result. Handle any possible exception like
WEEK-9 divided by zero.
2. Suppose
b that table named table.txt is stored in a text file. The first line
.
in the file is the header, and the remaining lines correspond to rows in
the table. The elements are separated by commas. Write a java program 83
to display the table using labels in grid layout.
xii
APPLETS
1. a
Develop an applet that displays a simple message.
85
WEEK-10 .
2. b
Develop an applet that receives an integer in one text field and
.
computes its factorial value and returns it in another text field, when the 87
button named “compute” is clicked.(Hint: Applet).
ADDITIONAL PROGRAMS
1. Design
a a class to represent a Student details include the Student ID,
.
Name of the Student, Branch, year, location and college. Assign initial
89
values using constructor. Calculate average of marks of 6 subjects and
calculate attendance percentage.
2. Develop
b with suitable hierarchy, classes for Point, Shape, Rectangle,
.
Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test 91
application to demonstrate dynamic polymorphism.
3. Write
a. c an Applet that computes the payment of a loan on the amount of
.
the loan, the interest rate and the number of months. It takes one
94
parameter from the browser. Monthly; if true, the interest rate is per
month, otherwise the interest rate is annual.
b.
4. Write
d a program that creates three threads. First thread displays “Good
Morning”
. every one second, the second thread displays “Hello” every
two seconds and the third thread displays “Welcome” every three 97
seconds.
5. Write
e a java programs to find factorial of a number. user is allowed to
.
enter a number into the text field whose factorial is to be determined.
On pressing the button the value of the text field is firstly converted 100
into integer and then processed to find its factorial. The result will get
displayed in another text field.(Hint: use swings).
xiii
WEEK-1: BASIC PROGRAMS
EXPERIMENT-1.1
1.1.1 OBJECTIVE:
To debug step by step with small program of about 10 to 15 lines which contains at least one if else
condition and a for loop.
1.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB.
}
}
1
1.1.5 OUTPUT:
2
3
1.1.6 PRE LAB VIVA QUESTIONS:
1. Difference between header files and import packages?
2. What is the difference between procedural and object-oriented programs?
3. What are Encapsulation, Inheritance and Polymorphism?
4. What is OOPs?
4
EXPERIMENT-1.2
1.2.1 OBJECTIVE:
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. If the discriminate b2-4ac is negative, display a message stating that
there are no real solutions.
1.2.2 RESOURCES:
COMPLIATION:
EXCEUTION:
C:\java roots
import java.util.*;
class roots
{
public static void main(String args[])
{
double r1,r2;
System.out.println("Enter a,b,c of the equation ax2+bx+c=0");
Scanner as=new Scanner (System.in);
int a=as.nextInt();
int b=as.nextInt();
int c=as.nextInt();
int d=b*b-4*a*c;
if(d<0)
{
System.out.println("There are no solutions");
5
}
if(d==0)
{
System.out.println("The roots are real and equal");
r1=r2=-b/(2.0*a);
System.out.println("The roots are "+r1+" and "+r2);
}
if(d>0)
{
System.out.println("The roots are real");
}
if(d>0)
{
System.out.println("The roots are real");
r1=(-b+Math.sqrt(d))/(2.0*a);
r2=(-b-Math.sqrt(d))/(2.0*a);
System.out.println("The roots are "+r1+" and "+r2);
}
}
}
1.2.5OUTPUT:
6
1.2.7 POST LAB VIVA QUESTIONS:
1. Define variable?
2. What is instance variable?
3. Define class variable?
4. What is an expression?
7
EXPERIMENT-1.3
1.3.1 OBJECTIVE:
The Fibonacci sequence is defined by the following rule: The first two values in the sequence are 1 and 1.
Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both
recursive and non recursive functions to print the nth value in the Fibonacci sequence.
1.3.2 RESOURCES:
COMPLIATION:
EXCEUTION:
C:\java Fibnon
import java.util.*;
class Fibnon
{
public static void main(String args[])
{
int n,n1;
Random as=new Random();
n=as.nextInt(10);
fib1 as1=new fib1 ();
n1=as1.fibc(n);
System.out.println("The "+n+"th fibonacci number is "+n1);
}
}
class fib1
8
{
int a=1,b=1;
int fib;
int fibc(int n)
{
System.out.print(a+" "+b+" ");
for(int i=1;i<=n-2;i++)
{
fib=a+b;
System.out.print(fib+" ");
a=b;
b=fib;
}
return fib;
}
}
1.3.5OUTPUT:
Or
import java.util.Scanner;
import java.io.*;
class Fibonacci
{
int a1,a2,a3,num,i;
9
int fibRec(int x)
{
if(x==0)
return 0;
else if(x==1)
return 1;
else
return (fibRec(x-1)+fibRec(x-2));
}
int fibNonRec(int y)
{
a1=1;
a2=1;
num=y;
for(i=3;i<=num;i++)
{
a3=a1+a2;
System.out.println(a3);
a1=a2;
a2=a3;
}
return a3;
}
}
class Fib
{
public static void main(String args[]) throws IOException
{
System.out.println("enter n value");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Compile:javac Fib.java
Run:java Fib
OUTPUT:
enter n value
5
011235
The nth value with recursive:5
2
10
3
5
The nth value with non-recursive: 5
1. Define method?
2. How method are called?
3. How static methods are called?
4. Define constructor?
11
EXPERIMENT-1.4
1.4.1 OBJECTIVE:
Read array of numbers through command line and sort in ascending order.
1.4.2 RESOURCES:
1. Create a class and pass array numbers through command line arguments.
2. And give these values to array.
3. And sort the array using any sorting methods and print the array.
COMPLIATION:
EXCEUTION:
C:\java JavaApplication2
12
a[i]=Integer.parseInt(args[i]);
System.out.print(a[i]);
if(a[i]>a[k])
int temp;
temp=a[i];
a[i]=a[k];
a[k]=a[i];
for(int i=0;i<args.length;i++)
System.out.print(a[i]);
13
1.4.5OUTPUT:
14
WEEK-2: POLYMORPHISM, INHERITANCE
EXPERIMENT-2.1
2.1.1 OBJECTIVE:
Design a class to represent a bank account. Which include contains account number, name of the
depositor, type of the account, balance amount in the account. Use constructors to assign initial values, to
Deposit an amount, to Withdraw amount after checking balance, to display name and balance. .(Hint:
constructor overloading).
2.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
import java.util.Scanner;
class BankAccount
int acno;
String name;
String type;
int bal;
acno=a;
name=b;
type=c;
15
bal=d;
void Deposit(int a)
bal=bal+a;
void Withdraw(int a)
bal=bal-a;
if(bal<0)
System.out.println("cannot withdraw");
bal=bal=a;
else
void Display()
System.out.println("Name is"+name);
System.out.println("Balance is"+bal);
class Bank1
16
public statis void main(String args[])
System.out.println("Enter acno,name,type,bal");
ba.BankAccount(s.nextInt(),s.next(),s.next(),s.nextInt());
ba.Deposit(s.nextInt());
ba.Withdraw(s.nextInt());
ba.Display();
2.1.6 OUTPUT:
17
2.1.6 PRE LAB VIVA QUESTIONS:
1. Describe constructors with parameter and without parameter?
2. Define scanner class?
3. What is the method to read string?
4. What is the method to int,char,float?
18
EXPERIMENT-2.2
2.2.1 OBJECTIVE:
Design a class to represent a bank account. Which include contains account number, name of the
depositor, type of the account, balance amount in the account. Define Methods, to assign initial
values, to Deposit an amount, to Withdraw amount after checking balance, to display name and
balance.(Hint: method overloading).
2.2.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
import java.util.Scanner;
class BankAccount
{
int acno;
String name;
String type;
int bal;
void setData(int a,String b,String c,int d)
{
acno=a;
name=b;
type=c;
bal=d;
}
void Deposit(int a)
{
System.out.println("Balance before deposit is"+bal);
bal=bal+a;
System.out.println("Balance after deposit is"+bal);
}
void Withdraw(int a)
{
System.out.println("Balance before withdrawal is"+bal);
bal=bal-a;
if(bal<0)
{
System.out.println("cannot withdraw");
19
bal=bal=a;
}
else
System.out.println("Balance after withdrawal is"+bal);
}
void Display
{
System.out.println("Name is"+name);
System.out.println("Balance is"+bal);
}
}
class Bank
{
public statis void main(String args[])
{
BankAccount ba=new BankAccount();
Scanner s=new Scanner(System.in);
System.out.println("Enter acno,name,type,bal");
ba.setData(s.nextInt(),s.next(),s.next(),s.nextInt());
System.out.println("enter the amount to deposit");
ba.Deposit(s.nextInt());
System.out.println("enter the amount to withdraw");
ba.Withdraw(s.nextInt());
ba.Display();
}
}
2.2.5 OUTPUT:
20
2.2.6 PRE LAB VIVA QUESTIONS
1 What is method overloading?
2 Can same methods present in different classes?
3 How to call methods?
4 Describe final class?
21
EXPERIMENT-2.3
2.3.1 OBJECTIVE:
2.3.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
// Method overriding.
class MODemo{
int i, j;
MODemo (int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends MODemo {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
22
2.3.5 OUTPUT:
i and j:1 2
k: 3
23
WEEK-3: ABSTRACT CLASS, INTERFACE
Experiment 3.1
3.1.1 OBJECTIVE:
To create an abstract class named shape that contains two integers and an empty method named printArea
.Provide three classes named Rectangle ,Triangle and Circle subclass that each one of the classes extends
the Class Shape .Each one of the classes contains only the method printArea() that prints the area of
Shape.
3.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
24
public static void main(String[] args) {
// TODO code application logic here
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
r.printArea();
System.out.println("-------------------------------------");
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
t.printArea();
System.out.println("-------------------------------------");
Circle c = new Circle();
c.x = 2;
c.printArea();
System.out.println("-------------------------------------");
}
}
25
EXPERIMENT 3.2
3.2.1 OBJECTIVE:
Write a java program to create an interface named Shape that contains empty method named Area () and
perimeter(). Provide two classes named Triangle and Circle such that each one of the classes implement
Shape. Each one of the classes contains only the method Area () and perimeter().that prints the area and
perimeter() of the given shape.
3.2.2 RESOURCES :
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
27
}
}
public class If {
public static void main(String[] args) {
System.out.println("****Implementing circle ****");
Circle1 c=new Circle1(10.5);
c.area();
c.perimeter();
c.show();
c.display();
s=(Shape) c;//Explicit type castingis done because circle1 class is higher than shape interface
s.area();
s.perimeter();
// s.display(); not possible to represent this statment because reference variables refers only abstract
methods in the interface.
t.area();
t.perimeter();
t.show();
1.2.5 OUTPUT:
area of circle346.185
perimeter of circle65.94
****This is circle****
28
PI value3.14
area of circle346.185
perimeter of circle65.94
area of Triangle11.55
perimeter of Triangle76.23
****This is triangle****
29
WEEK-4: EXCEPTIONS
EXPERIMENT 4.1
4.1.1 OBJECTIVE:
You will be given two integers x and y as input, you have to compute x/y. Implement a class which raise
an exception if x and y are not signed integers or if y is zero.
4.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB .
1. Create user defined exception class named as NumberException, which extends Exception class.
2. In Number Exception class print the statement exception due to crossed 32 bit.
3. Create a class Throw Exception which contains a static method and throws the NumberException.
4. This method read two arguments, define a method such that it will check the range of numbers is
with in the 32 bit range or not. if not throw the exception.
package javaapplication1;
import java.util.Scanner;
z=x/y;
System.out.println("result="+z);
}
catch(NumberException e)
{
}
catch(ArithmeticException e)
{
System.out.println("divide by zero");
}
}
}
4.1.5 OUTPUT:
31
EXPERIMENT 4.2
4.2.1 OBJECTIVE:
Write a java program on user defined exceptions.
4.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
/*Here we have an Account class, which is representing a bank account where you can deposit and
withdraw money, but what will happen if you want to withdraw money which exceeds your bank
balance? You will not be allowed, and this is where user defined exception comes into the picture. We
have created a custom exception called NotSufficientFundException to handle this scenario. This will
help you to show a more meaningful message to user and programmer. */
/**
* Java class to represent a Bank account which holds your balance and provide wi
*/
public class Account {
32
public int balance() {
return balance;
}
4.1.5 OUTPUT:
Current balance : 1000
Withdrawing $200
Current balance : 800
Exception in thread "main" NotSufficientFundException: Current balance 800 is less than requested
amount 1000
at Account.withdraw(Testing.java:68)
at Testing.main(Testing.java:51)
33
EXPERIMENT-4.3
4.3.1 OBJECTIVE:
To creates User Interface to perform Integer Divisons. The user enters two numbers in text fields, Num1
and Num2.The division of Num1 and Num2 is displayed in the result field when the divide button
clicked. If Num1 or Num2 were not integer, the program would throw a NumberFormatException, If
Num2 is Zero, and the program would throw an Athematic Exception. Display the Exception in message
box.
4.3.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame implements ActionListener {
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b1;
A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter Number1");
add(l1);
tf1 = new JTextField(10);
add(tf1);
l2 = new JLabel("Enter Number2");
add(l2);
tf2 = new JTextField(10);
add(tf2);
l3 = new JLabel("Result");
add(l3);
tf3 = new JTextField(10);
34
add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
try {
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
throw new ArithmeticException(" Divide by Zero Error");
float c = (float) a / b;
tf3.setText(String.valueOf(c));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}
public class JavaApplication9
{
public static void main(String[] args)
{
A a = new A();
}
}
4.3.5 OUTPUT:
35
4.3.6 PRE LAB VIVA QUESTIONS:
36
WEEK-5: MULTITHREADING
EXPERIMENT-5.1
5.1.1 OBJECTIVE:
Write a java program that implements thread class methods.
5.1.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0.is required, 1GB RAM, Hard Disk 80 GB
try{
t1.join();
}catch(Exception e){System.out.println(e);}
37
t2.start();
t3.start();
t1.setName("Sonoo ");
System.out.println("After changing name of t1:"+t1.getName());
}
}
5.1.5 OUTPUT:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
38
EXPERIMENT-5.2
5.2.1OBJECTIVE:
To implements a multithread application that has three threads .First thread generates random integer for
every second and if the value is even, second thread computes the square of number and prints .If the
value is odd, the third thread will print the value of cube of number.
5.2.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0.is required, 1GB RAM, Hard Disk 80 GB
40
5.2.5 OUTPUT:
41
5.2.7 POST LAB VIVA QUESTIONS:
1. What is multithreading and what are the methods for inter-thread communication and what is
the class in which these methods are defined?
2. When you will synchronize a piece of your code?
3. What is daemon thread and which method is used to create the daemon thread?
4. What is deadlock?
42
Experiment 5.3
5.3.1 OBJECTIVE:
Write a java program that correct implements of producer consumer program.
5.3.2 RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB.
43
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
5.2.3 OUTPUT:
Put:1 Got:1
Put:2 Got:2
44
Put:3 Got:3
Put:4 Got:4
Put:5 Got:5
Put:6 Got:6
Put:7 Got:7
Put:8 Got:8
Put:9 Got:9
45
WEEK-6: FILES
Experiment 6.1
6.1.1 OBJECTIVE
Write a Java program that reads a file name from the user, and then displays information about whether the file
exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in
bytes.
6.1.2 RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
46
6.1.3 OUTPUT:
1. What is file?
2. How to create file input stream?
3. What is character stream?
4. What is byte stream?
47
Experiment 6.2
6.2.1 OBJECTIVE
Java program that displays the number of characters, lines and words in a text file.
6.2.2 RESOURCES:
}
catch(IOException ie)
{
return;
}
System.out.println(lines+" "+words+" "+chars);
}
}
This is II CSE
1 4 32
49
Experiment 6.3
6.3.1 OBJECTIVE:
Write a Java program that reads a file and displays the file on the screen, with a line number before each line.
6.3.2 RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
class linenum
{
public static void main(String[] args)throws IOException
{
FileInputStream fil;
LineNumberInputStream line;
int i;
try
{
fil=new FileInputStream(args[0]);
line=new LineNumberInputStream(fil);
}
catch(FileNotFoundException e)
{
System.out.println("No such file found");
return;
}
do
{
i=line.read();
if(i=='\n')
{
System.out.println();
System.out.print(line.getLineNumber()+" ");
}
else
System.out.print((char)i);
}while(i!=-1);
fil.close();
line.close();
}
50
}
6.3.5 OUT PUT:
Demo.java
class Demo
1{
2 public static void main(java Demo beta gamma delta)
3{
4 int n = 1 ;
5 System.out.println(“The word is ” + args[ n ] );
6}
7}
8?
51
WEEK -7: JDBC
EXPERIMENT-7.1
7.1.1 OBJECTIVE:
To connects to database using JDBC does add ,delete ,modify and retrieve operations.
7.1.2 RESOURCES:
52
System.out.println("----------------");
String opt = "";
String htno = "", sname = "", mobile = "", sql = "";
Scanner sc = new Scanner(System.in);
while (opt != "5")
{
System.out.println("Enter Your Option");
opt = sc.next();
switch (opt)
{
case "1":
{
System.out.println("Enter Htno");
htno = sc.next();
System.out.println("Enter Name");
sname = sc.next();
System.out.println("Enter Mobile");
mobile = sc.next();
sql = "insert into stu values(" + "'" + htno + "'" + "," + "'" + sname + "'" + "," + "'" +
mobile + "'" + ")";
if (st.executeUpdate(sql) > 0)
{
System.out.println("Record Inserted");
}
}
break;
case "2":
{
System.out.println("Enter Htno to Update");
htno = sc.next();
System.out.println("Enter Name");
sname = sc.next();
System.out.println("Enter Mobile");
mobile = sc.next();
sql = "update stu set sname=" + "'" + sname + "'" + "," + "mobile=" + "'" + mobile +
"'" + " where htno='" + htno + "'";
if (st.executeUpdate(sql) > 0) {
System.out.println("Record Updated");
}
else
{
System.out.println("Operation Failed");
}
}
break;
case "3":
{
System.out.println("Enter Htno to delete");
htno = sc.next();
sql = "delete from stu where Htno=" + "'" + htno + "'";
53
if (st.executeUpdate(sql) > 0) {
System.out.println("Record deleted");
} else {
System.out.println("Operation Failed");
}
}
break;
case "4": {
sql = "select * from stu";
rs = st.executeQuery(sql);
System.out.println("Htno\tSname\tMobile");
while (rs.next()) {
System.out.println(rs.getString("Htno") + "\t" + rs.getString("SName") + "\t" +
rs.getString("mobile"));
}
rs.close();
}
break;
case "5":
{
opt = "5";
System.out.println("Thank You");
st.close();
cn.close();
}
break;
default: {
System.out.println("Choose Option between 1 and 5 only"); }
}
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
54
7.1.5 OUTPUT:
55
7.1.6 PRE LAB VIVA QUESTIONS
1. What is JDBC?
2. What are drivers available?
3. What is the difference between JDBC and ODBC?
4. What is stored procedure?
56
EXPERIMENT-7.2
7.2.1 OBJECTIVE:
Write a java program that loads names and phone numbers from the text file where data is organized as one
line per record and each field in record are separated by a tab(\t).It takes a name or phone number as input and
prints corresponding other value from hash table(hint: use Hash Table).
7.2.2 RESOURCES:
1. Create a text file which contains names and phone numbers separated by a tab
2. Using buffer reader the file has to be read and the content has to be moved to hash table using put method.
3. Whenever a name is given the corresponding phone number from hash table has to be displayed
import java.util.*;
import java.io.*;
public class PhoneDictionary
{
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("D:\\jp\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("Welcome TO Siddhartha Institute of Engg. & Technology");
System.out.println("Student Phone numbers are");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("iare");
System.out.println("MENU");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
57
while (opt != "3")
{
System.out.println("Enter Your Option (1,2,3): ");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else
{
System.out.println("Not Found");
}
break;
case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
}
}
else
{
System.out.println("Not Found");
}
break;
case "3":
opt = "3";
System.out.println("Menu Successfully Exited");
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}}}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}}}
58
INPUT:
Loads names and phone numbers from the text file named ph.txt
7.2.5 OUPUT:
D:\JP>java PhoneDictionary
iare
Student Phone numbers are
P.RaghuNandan:8977332085
P.Ronith:9052277577
Y.Srinish:9849039239
Y.Snikitha:9849098490
P.Rishikesh:9848098480
Iare
MENU
1.Search by Name
2.Search by Mobile
3.Exit
Enter Your Option( 1,2,3):
1
Iare
22
Enter Name
P.RaghuNandan
Mobile is 8977332085
Enter Your Option( 1,2,3):
2
Enter mobile
9849098490
Name is Y.Snikitha
Enter Your Option 1,2,3
3
Menu Successfully Exited
59
EXPERIMENT-7.3
7.3.1 OBJECTIVE:
7.3.2 RESOURCES:
1. Create a text file which contains names and phone numbers separated by a tab
2. Using buffer reader the file has to be read and the content has to be moved to hash table using put method.
3. Whenever a name is given the corresponding phone number from hash table has to be displayed
import java.sql.*;
import java.util.*;
public class PhoneDB
{
public static void main(String[] args)
{
Connection cn;
Statement st;
ResultSet rs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn = DriverManager.getConnection("jdbc:odbc:siet","siet","siet");
System.out.println("Data Base Connected");
st = cn.createStatement();
rs = st.executeQuery("select * from phone");
Hashtable<String, String> ht = new Hashtable<String, String>();
System.out.println("IARE");
System.out.println("Student Phone numbers are");
while (rs.next())
{
ht.put(rs.getString(1), rs.getString(2));
System.out.println(rs.getString(1) + ":" + rs.getString(2));
}
rs.close();
st.close();
cn.close();
System.out.println("-----------------------------------------------------");
System.out.println("Welcome IARE");
System.out.println("Main Menu");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
60
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("-----------------------");
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
} else {
System.out.println("Not Found");
}
break;
case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
break;
case "3":
opt = "3";
System.out.println("Menu Successfully Exited");
break;
default:
System.out.println("Choose Option betwen 1 and Three");
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
61
7.3.4 INPUT from database Table in Oracle:
7.3.5 OUTPUT:
D:\JP>javac PhoneDB.java
D:\JP>java PhoneDB
Data Base Connected
Student Phone numbers are
P.Raghu:8977332085
Ramu:9849098490
Hari:9877335566
Jayadev:9052778877
Harika:9849044556
-----------------------------------------------------
Main Menu
1.Search by Name
2.Search by Mobile
3.Exit
Enter Your Option 1,2,3
1
Enter Name
Jayadev
Mobile is 9052778877
-----------------------
Enter Your Option 1,2,3
2
Enter mobile
8977332085
Name is P.Raghu
-----------------------
Enter Your Option 1,2,3
3
Menu Successfully Exited
62
7.3.6 PRE LAB VIVA QUESTIONS:
1. What are the JDBC API components?
2. What are the JDBC statements?
3. What is the difference between Statement and PreparedStatement interface?
4. How can we execute stored procedures and functions?
63
EXPERIMENT 7.4
7.4.1 OBJECTIVE:
Write a Java Program that takes tab separated data (one record line) from a text file and insert them into a
database.
7.4.2 RESOURCES:
1. Create a text file which contains names and phone numbers separated by a tab
2. Using buffer reader the file has to be read and the content has to be moved to hash table using put method.
3. Whenever a name is given the corresponding phone number from hash table has to be displayed
import java.sql.*;
import java.io.*;
import java.util.*;
public class Tbltodb
{
public static void main(String[] args)
{
Connection cn;
Statement st;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:siet","siet","siet");
st=cn.createStatement();
String sql="";
FileInputStream fin=new FileInputStream("D:\\JP\\emp.txt");
Scanner sc=new Scanner(fin);
String[] arrayList;
String a="";
int i=0;
while(sc.hasNext())
{
a=sc.nextLine();
arrayList =a.split("\\s+");
sql="insert into employee
values("+"'"+arrayList[0]+"','"+arrayList[1]+"','"+arrayList[2]+"')";
st.execute(sql);
i++;
System.out.println(arrayList[0]+":"+arrayList[1]+":"+arrayList[2]);
}
64
System.out.println(i+" Records are inserted");
st.close();
cn.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
7.4.5 OUTPUT:
D:\JP>javac Tbltodb.java
D:\JP>java Tbltodb
CSE1001:P.Raghu:8977332085
CSE1002:G.Uday:9849677889
CSE1003:Kavitha:8949088993
CSE1004:Swetha:7805805805
4 Records are inserted
After Inserted records in the Data Base Emplyee table as
Sql>select * from employee;
Siddhartha Institute of Engg. & Tech. Java Programming Record
65
WEEK-8: EVENT Handling and AWT
EXPERIMENT-8.1
8.1.1 OBJECTIVE:
To simulate a Traffic Light. The program lets the user select one of three lights: red, yellow or Green with
radio buttons. On selecting radio button, an appropriate message with “stop” or “Ready” or “GO” should
appear above the button in selected color. Initially, there is no message Shown.
8.1.2 RESOURCES:
68
8.1.6 PRE LAB VIVA QUESTIONS:
1. What is a layout manager and what are different types of layout managers available in java
AWT?
2. How are the elements of different layouts organized?
3. What is Garbage Collection and how to call it explicitly?
4. What is the difference between Integer and int?
69
EXPERIMENT-8.2
8.2.1 OBJECTIVE:
To handle all mouse events and show event name at the center of the window when the mouse event is
fired.(Use Adapter Classes)
8.2.2 RESOURCES:
71
8.2.6 PRE LAB VIVA QUESTIONS:
1. What are different types of events?
2. How do we create mouse events?
3. What are different types of mouse events?
4. What are different types of objects created?
72
EXPERIMENT-8.3
8.3.1 OBJECTIVE:
Write a Java program to demonstrate the key event handlers.
8.3.2 RESOURCES:
74
WEEK-9: FILES
EXPERIMENT-9.1
9.1.1 OBJECTIVE:
To develop a program that works as simple calculator .Uses grid layout to arrange buttons for the digits
and for the +,-,*, % operations. Add text field to display the results, Handle any possible exceptions like
divide by zero.
9.1.2 RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
ex.getMessage());
}
}
79
break;
case "%":
{
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc
{
public static void main(String[] args)
{
A a = new A();
}
}
80
9.1.5 INPUT AND OUTPUT:
81
9.1.6 PRE LAB VIVA QUESTIONS:
1. what is awt and swing?
2. how do we create a jbutton object?
3. what is a data type?
4. what is the purpose of break statement in switch case?
82
EXPERIMENT-9.2
9.2.1 OBJECTIVE:
To display a table using Label in Grid Layout.Suppose that a table named Table.txt is stored in a text file.
The First line in the file is the header, and the remaining lines correspond rows in table. The elements are
separated by commas.
9.2.2 RESOURCES:
JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
try
{
FileInputStream fin = new FileInputStream("D:\\emp.txt");
84
WEEK-10: APPLETS
EXPERIMENT-10.1
10.1.1 OBJECTIVE:
To develop an Applet in java that displays a Simple Message
10.1.2 RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
85
10.1.6 INPUT AND OUTPUT:
86
EXPERIMENT-10.2
10.2.1 OBJECTIVE:
To develop an Applet in java that receives an integer in one Text Field, and computes its Factorial value
and returns it in another text Field, when button named “Compute” is clicked.
10.2.2 RESOURCES:
JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
87
add(tf2);
}
public void actionPerformed(ActionEvent ae)
{
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0)
{
f = f * n;
n--;
}
tf2.setText(String.valueOf(f));
}
}
88
ADDITIONAL PROGRAMS
EXPERIMENT-1
1.1 OBJECTIVE:
Design a class to represent a Student details. Include the Student ID, name of the Student, branch, year and
assign initial values, calculate average of marks of 6 subjects, calculate attendance percentage.
1.2 RESOURCES:
import java.util.Scanner;
class Student
{
int id;
String name;
String branch;
int year;
void getData(int a,String b,String c,int d)
{
id=a;
name=b;
branch=c;
year=d;
}
void Avg(int a,int b,int c,int d,int e,int f)
{
float avg;
avg=(a=b+c=d+e+f)/6;
System.out.println("Average is"+avg);
}
void Percentage(int a,int b)
{
float per;
per=(a/b)*100;
System.out.println("Percentage is"+per);
}
}
89
class Execute
{
public static void main(String args[])
{
Student st=new Student();
Scanner s=new Scanner(System.in);
System.out.println("enter ID,name,branch,year");
st.getData(s.nextInt(),s.next(),s.next(),s.nextInt());
System.out.println("enter 6 subject marks");
st.Avg(s.nextInt(),s.nextInt(),s.nextInt(),s.nextInt(),s.nextInt(),s.nextInt());
System.out.println("enter the present and total working days");
s.Percentage(s.nextInt(),s.nextInt());
}
}
1.5 OUTPUT:
1. Define variable?
2. Define instance and static variable?
3. Define method and static method?
4. Define final variable?
1.7 POST LAB VIVA QUESTIONS:
90
EXPERIMENT-2
2.1 OBJECTIVE:
Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle,
Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism
2.2 RESOURCES:
2.4PROGRAM LOGIC:
2.3 PROGRAM:
package date;
public class day
{
int day,month,year,y,m,tot_day=0;
int day_mon[]={31,28,31,30,31,30,31,31,30,31,30,31};
String week[]={"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
public void days(int a,int b,int c)
{
valid(a,b,c);
day=a;
month=b;year=c;
for(y=0;y<year;y++)< div="">
if(y%4==0)
tot_day+=366;
else
tot_day+=365;
if(month>2 && year%4==0)
day_mon[1]=29;
for(m=0;m<(month-1);m++)
tot_day+=day_mon[m];
tot_day+=day;
System.out.println(day+"-"+month+"-"+year+" this is :"+"="+week[(tot_day+4)%7]);
}
public void valid(int dd,int mm,int yy)
{
if(yy<1)
{
System.out.println("invalid....");
System.exit(0);
}
switch(mm)
{
case 1:
91
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(dd>31 || dd<1)
{
System.out.println("invalid......");
System.exit(0);
}
break;
case 4:
case 6:
case 9:
case 11:
if(dd>30 || dd<1)
{
System.out.println("invalid......");
System.exit(0);
}
break;
case 2:
if(yy%4!=0 && dd>=29 && dd<1)
{
System.out.println("invalid......");
System.exit(0);
}
else if(yy%4==0 || dd>28 || dd<1)
{
System.out.println("invalid......");
System.exit(0);
}break;
default:
System.out.println("invalid......");
System.exit(0);
}
}
}
Main program:
import date.*;
import java.io.*;
class chkd
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
day d=new day();
92
System.out.println("enter the date:(dd mm yyyy):");
int dd=Integer.parseInt(in.readLine());
int mm=Integer.parseInt(in.readLine());
int yy=Integer.parseInt(in.readLine());
d.days(dd,mm,yy);
}
}
</year;y++)<>
1.3 OUPUT:
C:\j2sdk1.4.0\bin>javac chkd.java
Note: chkd.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\j2sdk1.4.0\bin>java chkd
enter the date:(dd mm yyyy):
30
04
1989
30-4-1989 this is :=sunday
C:\j2sdk1.4.0\bin>java chkd
enter the date:(dd mm yyyy):
30
02
2000
invalid......
1. Define class?
2. Define method overriding?
3. What is dynamic dispatch method?
4. Define reference variable?
2.7 POST LAB VIVA QUESTIONS:
93
EXPERIMENT-3
3.1 OBJECTIVE:
Write a program that creates three threads. First thread displays “Good Morning” every one second, the
second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three
seconds.
3.2 RESOURCES:
95
3.4 OUTPUT:
96
EXPERIMENT-4
4.1 OBJECTIVE:
Write an Applet that computes the payment of a loan based on the amount of the loan, the interest rate and
the number of months. It takes one parameter from the browser: Monthly rate; if true, the interest rate is
per month, otherwise the interest rate is annual.
4.2 RESOURCES:
98
4.4 INPUT & OUTPUT:
99
EXPERIMENT-5
5.1 OBJECTIVE:
Write a java programs to find factorial of a number. user is allowed to enter a number into the text field
whose factorial is to be determined. On pressing the button the value of the text field is firstly converted
into integer and then processed to find its factorial. The result will get displayed in another text
field.(Hint: use swings).
5.2 RESOURCES:
a. PROGRAM LOGIC:
import java.applet.*;
import java.swing.*;
import java.awt.event.*;
import java.awt.*;
/*<applet code="Factorial" width=500 height=500> </applet> */
public class FactorialApplet extends Applet implements ActionListener
{
Label l1,l2;
TextField t1,t2;
Button b1,b2;
public void init()
{
l1=new Label("Enter a value: ");
l2=new Label("Result:");
t1=new TextField(10);
t2=new TextField(10);
b1=new Button("Calculate");
b2=new Button("Clear");
add(l1);
add(t1);
add(b1);
add(b2);
add(l2);
add(t2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
100
int n=Integer.parseInt(t1.getText());
int fact=1;
if(ae.getSource()==b1)
{
if(n==0||n==1)
{
fact=1;
t2.setText(String.valueOf(fact));
}
else
{
for(int i=1;i<=n;i++)
fact=fact*i;
}
t2.setText(String.valueOf(fact));
}
else if(ae.getSource()==b2)
{
t1.setText("");
t2.setText("");
}
}
}
101
5.5 OUTPUT:
102