Iare Oops Through Java Lab Manual Updated 0
Iare Oops Through Java Lab Manual Updated 0
Iare Oops Through Java Lab Manual Updated 0
LAB MANUAL
Prepared by
i
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
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 √ √ √ √ √
SYLLABUS:
LIST OF EXPERIMENTS
Week-1 BASIC PROGRAMS
a. 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.
b. 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.
c. 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.
Week-2 MATRICES, OVERLOADING, OVERRIDING
a. Write a java program to multiply two given matrices.
b. Write a java program to implement method overloading and constructors overloading.
c. Write a java program to implement method overriding.
Week-6 FILES
a. 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.
b. Write a java program that displays the number of characters, lines and words in a text file.
c. Write a java program that reads a file and displays the file on the screen with line number before each line.
Week-7 FILES
a. 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.
b. Write a java program that connects to a database using JDBC and does add, delete, modify and retrieve
operations.
Week-9 FILES
a. Write a java program that takes tab separated data (one record per line) from a text file and insert them into a
database.
b. Write a java program that prints the metadata of a given table.
Week-12 CALCULATOR
Write a java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the
+,-,*, % operations. Add a text field to display the result. Handle any possible exception like divided by zero.
Week-13 APPLET
a. Develop an applet that displays a simple message.
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 button named “compute” is clicked.
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
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 display 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, 5th Edition, 2010.
Web References:
1. http://vlab.co.in/ba_labs_all.php?id=2
2. http://www.javatpoint.com/java-programs
3. http://introcs.cs.princeton.edu/java/10elements/
Course Home Page:
INDEX
PAGE
S.NO LIST OF EXPERIMENTS NO
BASIC PROGRAMS
Write a java program that prints all real solutions to the quadratic
2.
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
WEEK-1
values in the sequence are 1 and 1. Every subsequent value is the sum
3. of the two values preceding it. Write a java program that uses both
recursive and non recursive functions.
INTERFACE
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
WEEK-4 1 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.
MULTITHREADING
Write a java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and if
1 the value is even, second thread computes the square of the number and
WEEK-5 prints. If the value is odd, the third thread will print the value of cube of
the number.
FILES
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
1
readable, whether the file is writable, the type of file and the length of
the file in bytes.
WEEK-6
Write a java program that displays the number of characters, lines and
2
words in a text file.
3 Write a java program that reads a file and displays the file on the screen
with line number before each line.
APPLETS
1. Develop an applet that displays a simple message.
WEEK-13 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 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 parameter from the
browser. Monthly; if true, the interest rate is per month, otherwise the interest
rate is annual.
4. 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.
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).
WEEK-1: BASIC PROGRAMS
EXPERIMENT-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.
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB.
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name „Testp‟.
3. Read n values from keyboard using a Scanner class.
4. Find the (n % i == 0) using dynamic initialization
5. Check the (n % i == 0) value using if condition.
SOURCE CODE:
import java.util.*;
}
}
1
OUTPUT:
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?
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.
RESOURCES:
PROGRAM LOGIC:
COMPLIATION:
EXCEUTION:
C:\java roots
SOURCE CODE:
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");
}
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);
}
}
}
OUTPUT:
1. Define variable?
2. What is instance variable?
3. Define class variable?
4. What is an expression?
EXPERIMENT-1.3
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.
RESOURCES:
PROGRAM LOGIC:
COMPLIATION:
EXCEUTION:
C:\java Fibnon
SOURCE CODE:
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);
}
}
9
class fib1
{
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;
}
}
OUTPUT:
Or
import java.util.Scanner;
import java.io.*;
class Fibonacci
{
int a1,a2,a3,num,i;
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
3
5
The nth value with non-recursive: 5
1. Define method?
2. How method is called?
3. How static methods are called?
4. Define constructor?
EXPERIMENT-1.4
OBJECTIVE:
Read array of numbers through command line and sort in ascending order.
RESOURCES:
PROGRAM LOGIC:
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
SOURCE CODE:
{
a[i]=Integer.parseInt(args[i]);
System.out.println("array before
+)
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]);
}
OUTPUT:
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
import java.util.Scanner;
class BankAccount
int acno;
String name;
String type;
int bal;
acno=a;
name=b;
type=c;
bal=d;
void Deposit(int a)
is"+bal); 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
{
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:
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?
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).
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE
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");
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();
}
}
OUTPUT:
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?
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
// 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
}
}
OUTPUT:
i and j:1 2
k: 3
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output:
MADAM
Is a palindrome
Experiment 3.3
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.
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
abstract class shape
public int x, y;
public abstract void printArea();
}
class Rectangle extends shape
{
public void printArea()
{
System.out.println("Area of Rectangle is " + x * y);
}
}
class Triangle extends shape
{
public void printArea()
{
System.out.println("Area of Triangle is " + (x * y) / 2);
}
}
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.
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
package pkgif;
interface Shape
{
double PI=3.14;
void area();
void perimeter();
}
interface Showable extends Shape
{
void show();
}
abstract class Circle implements Shape
{
double r;
Circle(double r)
{
this.r=r;
}
public void area()
{
System.out.println("area of circle"+PI*r*r);
}
}
class Circle1 extends Circle implements Shape, Showable
{
Circle1(double r)
{
super(r);
}
public void area()
{
System.out.println("area of circle"+PI*r*r);
}
public void perimeter()
{
System.out.println("perimeter of circle"+2*PI*r);
}
public void show()
{
System.out.println("****This is circle****");
}
void display()
{
System.out.println("PI value"+Shape.PI);
}
}
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();
System.out.println("***by reference
variable***"); Shape s;
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****
PI value3.14
area of circle346.185
perimeter of circle65.94
area of Triangle11.55
perimeter of Triangle76.23
****This is triangle****
EXPERIMENT 4.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.
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB .
PROGRAM LOGIC:
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.
SOURCE CODE:
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");
}
}
}
OUTPUT:
OBJECTIVE:
Write a java program on user defined exceptions.
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
/*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. */
{
Account acct = new Account();
System.out.println("Current balance : " + acct.balance());
System.out.println("Withdrawing $200");
acct.withdraw(200);
System.out.println("Current balance : " + acct.balance());
acct.withdraw(1000);
/**
* Java class to represent a Bank account which holds your balance and provide wi
*/
public class Account
{ private int balance =
1000;
public int balance()
{ return balance;
}
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
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);
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();
}
}
OUTPUT:
PRE LAB VIVA QUESTIONS:
Week – 5 Multithreading
OBJECTIVE:
Write a java program that implements Thread class methods.
RESOURCES:
Net Beans 8.0.2, JDK 7.0.is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name „TestMethod1 extends Thread‟.
3. Create thread objects and call thread class methods with thread object.
4. Pass the objects of our class to thread class .
5. Call the start method.
SOURCE CODE:
try{ t1.jo
in();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
t1.setName("Sonoo");
System.out.println("After changing name of t1:"+t1.getName());
}
}
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
RESOURCES:
Net Beans 8.0.2, JDK 7.0.is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
import java.util.*;
import java.io.*;
RESOURCES:
Net Beans 8.0.2, JDK 7.0 is required, 1GB RAM, Hard Disk 80 GB.
SOURCE CODE:
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
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
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
RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
SOURCE CODE
import java.util.*;
import java.io.*;
import java.io.File;
class file
{
public static void main(String args[])throws IOException
{
String s=args[0];
File f=new File(s);
if(f.exists())
{
System.out.println("File exists");
System.out.println("File type is "+f.getAbsolutePath());
System.out.println("File is readable "+f.canRead( ));
System.out.println("File is writeable "+f.canWrite());
System.out.println("File length is "+f.length());
}
else
{
System.out.println("File doesnot exist");
}
}
}
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?
RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
SOURCE CODE
import java.io.*;
class wordcount
{
public static int words=0;
public static int lines=0;
public static int chars=0;
public static void wc(InputStreamReader isr)throws IOException
{
int c=0;
boolean lastwhite=true;
while((c=isr.read())!=-1)
{
chars++;
if(c=='\n')
lines++;
if(c=='\t' || c==' ' || c=='\n')
++words;
if(chars!=0)
++chars;
}
}
public static void main(String[] args)
{
FileReader fr;
try
{
if(args.length==0)
{
wc(new InputStreamReader(System.in));
}
els
e
{ for(int i=0;i<args.length;i++)
{
fr=new FileReader(args[i]);
wc(fr);
}
}
}
catch(IOException ie)
{
return;
}
System.out.println(lines+" "+words+" "+chars);
}
}
OUT PUT:
This is II CSE
1 4 32
RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE
import java.io.*;
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();
}
}
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 }
6}
8?
EXPERIMENT-7.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 Write a java program to display the table using labels in Grid layout.
RESOURCES:
JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name A implements ItemListener.
3. Create the FileInputStream object.
4. Create the Scanner object delimited by comma.
5. Close the Jframe.
SOURCE CODE:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
import java.sql.*;
import javax.sql.*;
import java.util.*;
public class CRUD
{
public static void main(String[] args)
{
Connection cn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/IARE", "root", "98765432");
st = cn.createStatement();
System.out.println("Welcome To Institute of Aeronautical Engineering
College"); System.out.println("------MENU ");
System.out.println("1.Insert");
System.out.println("2.EDIT");
System.out.println("3.Delete");
System.out.println("4.Display");
System.out.println("5.Exit");
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 + "'";
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());
}
}
}
OUTPUT:
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?
EXPERIMENT-8.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).
RESOURCES:
Net Beans 8.0.2, JDK7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
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
SOURCE CODE:
import java.util.*;
import java.io.*;
public class PhoneDictionary
{
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("D:\\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 Institute of Aeronautical Engineering");
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);
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;
}
}
}
{
System.out.println(ex.getMessage());
}
}
}
INPUT:
Loads names and phone numbers from the text file named ph.txt
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
RESOURCES:
PROGRAM LOGIC:
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
SOURCE CODE:
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");
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());
}
}
}
INPUT from database Table in Oracle:
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
EXPERIMENT: 9.1
OBJECTIVE:
Write a Java Program that takes tab separated data (one record line) from a text file and insert them into a
database.
RESOURCES:
PROGRAM LOGIC:
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
SOURCE CODE:
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:\\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]);
}
System.out.println(i+" Records are inserted");
st.close();
cn.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
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;
Institute of Aeronautical Engineering Java Programming Record
OBJECTIVE:
Write a Java Program that prints the meta data of a given table.
14.2 RESOURCES:
14.4 PROCEDURE:
EXPERIMENT-10.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.
RESOURCES:
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name A implements ItemListener.
3. Create the ButtonGroup ,JRadiobuttons,JPanel.
4. Add to the JFrame
5. Register the components to the Jframe.
6. Close the Jframe.
SOURCE CODE:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ItemListener
{
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 60);
l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2 = new JLabel("Select Lights");
p1.add(l2);
JRadioButton r1 = new JRadioButton("Red Light");
r1.setBackground(Color.red);
p1.add(r1);
r1.addItemListener(this);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(this);
JRadioButton r3 = new JRadioButton("Green Light");
r3.setBackground(Color.GREEN);
p1.add(r3);
r3.addItemListener(this);
add(p1);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
setVisible(true);
}
public void itemStateChanged(ItemEvent i)
{
JRadioButton jb = (JRadioButton) i.getSource();
switch (jb.getText())
{
case "Red Light":
{
l1.setText("STOP");
l1.setForeground(Color.RED);
}
break;
case "Yellow Light":
{
l1.setText("Ready");
l1.setForeground(Color.YELLOW);
}
break;
case "Green Light":
{
l1.setText("GO");
l1.setForeground(Color.GREEN);
}
break;
}
}
}
public class TLights
{
public static void main(String[] args)
{
A a = new A();
}
}
77
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?
78
WEEK-11: MOUSE EVENTS
EXPERIMENT-11.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)
RESOURCES:
PROGRAM LOGIC:
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class A extends JFrame implements MouseListener
{
JLabel l1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
public class Mevents { public static void main(String[] args) {
A a = new A();
}
}
RESOURCES:
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener{ Label l;
TextArea area;
KeyListenerExample(){
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{ l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{ l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{ l.setText("Key Typed");
}
public static void main(String[] args)
{ new KeyListenerExample();
}
}
EXPERIMENT-9.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.
RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
OBJECTIVE:
To develop an Applet in java that displays a Simple Message
RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Simple extends Applet.
3. Declare the Font class object.
4. Set the font.
5. Call the setFont method and drawString method g.setFont(font); g.drawString(“String", 50, 50);
SOURCE CODE:
import java.applet.Applet;
import java.awt.*;
/*
<applet code="Simple.class" width=300 height=300>
</applet>
*/
RESOURCES:
JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Fact‟ extends Applet which implements ActionListener.
3. Declare the Label,TextField, Button variables.
4. Call init method
5. Call the setLayout method, setLayout(g);
6. Create the HTML file for applet tag.
SOURCE CODE:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Fact.class" width=300 height=300>
</applet>
*/
public class Fact extends Applet implements ActionListener
{
Label l1, l2, l3;
TextField tf1, tf2;
Button b1;
public void init()
{
setSize(400, 200);
FlowLayout g = new
FlowLayout(); setLayout(g);
l1 = new Label("Enter Value");
l1.setForeground(Color.BLUE);
add(l1);
tf1 = new TextField(5);
tf1.setText("0");
add(tf1);
b1 = new Button("Compute");
b1.addActionListener(this);
add(b1);
l3 = new Label();
add(l3);
l2 = new Label("factorial: ");
l2.setForeground(Color.BLUE);
add(l2);
tf2 = new TextField(5);
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));
}
}
EXPERIMENT-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.
RESOURCES:
PROGRAM LOGIC:
1. Create a class for student, which contains student ID, name, branch, year.
2. Define methods in that class to assign intial values, to calculate average of marks, to
calculate percentage.
SOURCE CODE:
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);
}
}
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");
st.Percentage(s.nextInt(), s.nextInt());
}
}
OUTPUT:
1. Define variable?
2. Define instance and static variable?
3. Define method and static method?
4. Define final variable?
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
RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM:
class
point{ void
show(){
System.out.println("This is the Point Base class");
}
}
class shape extends
point{ void display(){
System.out.println("Different shapes can be developed
with different number of points");
}
}
class rectangle extends
shape{ int l,b;
void getdata(int x,int y)
{ l=x;b=y;
}
void area()
{ System.out.println("Length:"+l);
System.out.println("Breadth:"+b);
System.out.println("Area:"+(l*b));
}
}
class square extends
shape{ int a;
void gdata(int x){
a=x;
}
void area()
{ System.out.println("Side:"+a);
System.out.println("Area:"+(a*a));
}
}
class circle extends
shape{ int r;
void get(int x){
r=x;
}
92
void area(){
93
System.out.println("Radius:"+r);
System.out.println("Area:"+(3.14*r*r));
}
}
class triangle extends
shape{ int b,h;
void tdata(int x,int y)
{ b=x;h=y;
}
void area()
{ System.out.println("Base:"+b);
System.out.println("Height:"+h);
System.out.println("Area:"+(0.5*b*h));
}
}
class ShapeTest{
public static void main(String args[])
{ rectangle r = new rectangle();
square s = new square();
circle c = new circle();
triangle t = new triangle();
r.show();
s.display();
System.out.println("");
System.out.println("Rectangle:");
System.out.println();
r.getdata(12,6);
r.area();
System.out.println("");
System.out.println("Square:");
System.out.println();
s.gdata(7);
s.area();
System.out.println("");
System.out.println("Circle:");
System.out.println();
c.get(5);
c.area();
System.out.println("");
System.out.println("Triangle:");
System.out.println();
t.tdata(4,7);
t.area();
}
}
1.3 OUPUT:
1. Define class?
2. Define method overriding?
3. What is dynamic dispatch method?
4. Define reference variable?
RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
1. Create three classes naed by one, second, three.
2. All these three classes will implement Runnable interfaces
3. One class thread will print Goodmorning for every one second.sleep this thread for 1000 seconds.
4. Second class thread will print Hello for every two second.sleep this thread for 2000 seconds.
5. Third class thread will print World for every three second.sleep this thread for 3000 seconds.
SOURCE CODE:
public class JavaApplication1
{
public static void main(String[] args)
{
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
}
}
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.
RESOURCES:
Net Beans, JDK1.7.0 is required, 1GB RAM, Hard Disk 80 GB
PROGRAM LOGIC:
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
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).
RESOURCES:
a. PROGRAM LOGIC:
SOURCE CODE:
import java.applet.*;
import javax.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)
{
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("");
}
}
}
OUTPUT:
PRE LAB VIVA QUESTIONS: