Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
com
LAB
Ex. No :1
Aim :
To write a java program to print the individual digits of a 3 digit number.
Algorithm:
1. Get any 3 digit integer as input
2. Find the last digit by n%10 and store it in r;
3. Print value of r
4. Reduce n by n/10;
5. Repeat this until n not equal to 0
Program:
/* Program to print the individual digits of a 3-digit number */
import java.io.*;
class SumDigit
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
int n;
System.out.print("Enter the number:");
n=Integer.parseInt(din.readLine());
System.out.println("The digits in the number are);
while(n!=0)
{
int r=n%10; /* Find the last digit */
n=n/10; /* Reduce the number */
System.out.println(r);
}
}
}
1
examkey.wordpress.com
LAB
Output:
D:\java>javac Digits.java
D:\java>java Digits 729
The number is 729
The digits in the number are
**************************
9
2
7
D:\java>
Viva Questions:
What are command line arguments?
The values that are passed to the main method from the command line while executing
the program are called as command line arguments.
What are the various types of operators available in java?
Arithmetic operator, Relational operator, Logical operator, Bitwise operator,Increment
and decrement operator, Assignment operator, Conditional operator and Special operator.
What is a ternary operator?
The operator that takes three arguments is called as ternary operator. The conditional
operator is the only ternary operator available in java.
What is the use of Integer.parseInt() method?
This method is used to convert the String object into integer value.
What is called as a Boolean expression?
An expression that returns either true or false value is called a Boolean expression.
examkey.wordpress.com
LAB
Ex. No :2
Biggest Number
Aim:
To write a java program to read two integers and print the larger number followed by the
words is larger. If the numbers are equal print the message These numbers are equal.
Agorithm:
1. Import the package java.io*
2. Read the value in the variable a and b
3. check whether a>b if it is true print a is larger
4. else check b>a if it is true print b is larger
5. else print a is equal to b
Program:
import java.io.*;
class Large
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
int a,b;
System.out.print("Enter the value of a:");
a=Integer.parseInt(din.readLine());
System.out.print("Enter the value of b:");
b=Integer.parseInt(din.readLine());
System.out.println("a="+a+"\t\tb="+b);
if(a==b)
System.out.println("These numbers are equal");
else if(a>b)
System.out.println(a+ " is larger");
3
examkey.wordpress.com
LAB
else
System.out.println(b+" is larger");
}
}
Output 1:
D:\java>javac Large.java
D:\java>java Large
Enter the value of a:45
Enter the value of b:34
a=45 b=34
45 is larger
Viva Questions:
What is a control structure?
Control structures are statements that are used to change the flow of the program based
on some condition.
What are the two types of control structures?
Decision making statements and Looping statements
What are decision making statements?
The statements that are used to execute only a block of code and leaving others based on
the condition.
What are the various decision making statements available in java?
Simple if, if..else, nested if..else, else if ladder and switch statement.
examkey.wordpress.com
LAB
Ex. No :3
Armstrong Nnumber
Aim:
3
Initialize sum=0
3.
4.
Program:
import java.io.*;
class Armstrong
{
public static void main(String args[])throws IOException
{
System.out.println("Armstrong numbers");
System.out.println("*****************");
for(int i=100;i<=999;i++)
{
int n=i,sum=0;
while(n!=0)
{
int r=n%10;
sum=sum+(int)Math.pow(r,3);
n=n/10;
}
if(sum==i)
System.out.println(i);
5
examkey.wordpress.com
LAB
}
}
}
Output:
D:\java>javac Armstrong.java
D:\java>java Armstrong
Armstrong numbers
*****************
153
370
371
407
Viva Question:
What is the use looping statement?
The looping statement is used to execute a block of repeatedly until the condition is true.
What are the various looping statements available in java?
While, do.. while and for statements.
What is the difference between while and do..while?
In case of while statement the block of code will not be executed atleast once if
the condition is false at the first run.
In case of do..while statement the block of code will be executed atleast once if
the condition is false at the first run.
examkey.wordpress.com
LAB
System.out.print("a["+i+"]:");
a[i]=Integer.parseInt(din.readLine());
}
big=a[0]; small=a[0];
for(int i=1;i<n;i++)
{
if(a[i]>big)
big=a[i];
if(a[i]<small)
7
examkey.wordpress.com
LAB
}
System.out.println("\nThe elements in the array");
for(int i=0;i<n;i++)
System.out.print("\t"+a[i]);
System.out.println("\nThe biggest element in the array is "+big);
System.out.println("The smallest element in the array is "+small);
}}
Output:
D:\java>javac ArrBig.java
D:\java>java ArrBig
Enter number of terms in the array:5
Enter array element:
a[0]:56
a[1]:78
a[2]:12
a[3]:4
a[4]:89
The elements in the array
56 78 12 4 89
The biggest element in the array is 89
The smallest element in the array is 4
Viva Questions:
Define array-An array is a collection of elements of same data type referred by a common
name. The elements are of the array are stored in consecutive memory locatons.
Types of arrays-One dimensional array, two dimensional array and multidimensional arrays.
How to declare a two dimensional array?
Datatype arrayname[][]=new datatype[ row size][column size]
How the individual elements of an array can be accessed?
The individual elements can be accessed using the index. The index of the first element
starts with 0.
examkey.wordpress.com
LAB
Ex.No.5
String
Aim:
To write a java program that creates a string object and initializes it with your
name and performs the following operations
a) To find the length of the string object using appropriate String method.
b) To find whether the character a is present in the string. If yes find the
number of times a appear in the name and the location where it appears
Algorithm:
1. Initialize the string object
2. Find the length of the string
3. Find the number of occurrence of character a
4. Print the location of the occurence
Program:
class StringDemo
{
public static void main(String args[])
{
String name="Java Programming";
int count=0;
System.out.println("The given name is "+name);
System.out.println("The length of name is "+name.length());
if(name.indexOf('a')<0)
System.out.println("The character 'a' is not present in my name");
else
{
System.out.println("The character 'a' is present in the locations");
int loc=0;
while(loc<name.lastIndexOf('a'))
9
examkey.wordpress.com
LAB
{
int x=name.indexOf('a',loc);
System.out.println(x);
loc=x+1;
count++;
}
System.out.println("The character 'a' is present "+count+" times");
}
}
}
Output:
D:\java>javac StringDemo.java
D:\java>java StringDemo
The given name is Java Programming
The length of name is16
The character 'a' is present in the locations
1
3
10
The character 'a' is present 3 times
D:\java>
10
examkey.wordpress.com
LAB
Given
the following attributes: Regno(int), Name(string), Marks in subjects(Integer Array), Total (int).
Algorithm:
1. Initialize 5 student register no,name and marks of 3 subjects
2. Find the total marks of each student
3. Print the register no,name and marks and total of 5 students
Program:
import java.io.*;
/* Student class */
class Student
{
int regno,total;
String name;
int mark[]=new int[3];
void readinput() throws IOException
{
BufferedReader
din=new
InputStreamReader(System.in));
System.out.print("\nEnter the Reg.No: ");
regno=Integer.parseInt(din.readLine());
System.out.print("Enter the Name: ");
name=din.readLine();
System.out.print("Enter the Mark1: ");
mark[0]=Integer.parseInt(din.readLine());
System.out.print("Enter the Mark2: ");
mark[1]=Integer.parseInt(din.readLine());
System.out.print("Enter the Mark3: ");
mark[2]=Integer.parseInt(din.readLine());
total=mark[0]+mark[1]+mark[2];
}
BufferedReader(new
void display()
{
System.out.println(regno+"\t"+name+"\t"+mark[0]+"\t"+mark[1]+"\t"+ma
rk[2]+"\t"+total);
}
}
/* Main class */
class Mark
{
public static void main(String args[]) throws IOException
{
Student s[]=new Student[5];
for(int i=0;i<5;i++)
{
s[i]=new Student();
s[i].readinput();
}
System.out.println("\t\t\tMark List");
System.out.println("\t\t\t*********");
System.out.println("RegNo\tName\tMark1\tMark2\tMark3\tTotal");
for(int i=0;i<5;i++)
s[i].display();
}
}
Output:
D:\java>javac Mark.java
D:\java>java Mark
Enter the Reg.No: 1
Enter the Name: Balu
Enter the Mark1: 67
Enter the Mark2: 90
Enter the Mark3: 56
Enter the Reg.No: 2
Enter the Name: Geetha
Enter the Mark1: 87
Enter the Mark2: 79
Name
Balu
67
90
56 213
Geetha
87
79
92 258
Vimal
87
60
71 218
Fancy
92
89
86 267
Sriram
78 90
91
259
examkey.wordpress.com
LAB
/* Main class */
class TwoInterface
{
public static void main(String args[])
{
Demo d=new Demo();
d.display();
}
}
Output:
D:\java>javac TwoInterface.java
D:\java>java TwoInterface
X in inteface One =12
Y in interface Two=10
X+Y= 22
Viva Questions:
What is an interface?
Interface is just like a class which contains final variables and public abstract methods. It
is used to implement multiple inheritance in java.
What is an abstract method?
The method which has only declaration in the super class and defined in the subclass is
known as abstract method.
Syntax for defining an interface
interface interfacename
{
}
How to implement interface?
The abstract methods should be implemented in a class to use the interface in our
program.
class className extends superclassname implements interface1, interface2,
{
}
examkey.wordpress.com
LAB
super(mg);
}
}
/* Main class */
class UserExcep
{
public static void main(String args[])throws IOException
{
BufferedReader
bin=new
BufferedReader(new
InputStreamReader(System.in));
int a,b;
System.out.print("Enter the value of A:");
a=Integer.parseInt(bin.readLine());
16
examkey.wordpress.com
LAB
int c=a+b;
if(c>99)
throw new MyException("The numbers are too big");
System.out.println(a+"+"+b+"="+c);
}
catch(MyException e)
{
}
}
}
Output:
D:\java>javac UserExcep.java
D:\java>java UserExcep
Enter the value of A:56
Enter the value of B:34
56+34=90
C:\javapgm>java UserExcep
Enter the value of A:56
Enter the value of B:90
The sum of numbers should be less than 99
The numbers are too big
Viva Questions:
What is an exception?
An exception means errors that occur during execution of the program that
disrupts normal flow of the program.
What are the steps in handling exception?
The following are the tasks in handling exceptions
17
18
examkey.wordpress.com
LAB
examkey.wordpress.com
LAB
if (s.equals("*")) break;
myarr=s.getBytes();
91
fout.write(myarr);
fout.write('\n');
}
fout.close();
System.out.println("The file is created");
}
}
Output:
D:\java>javac FileWriteDemo.java
D:\java>java FileWriteDemo
Enter the contents of the sample.txt file. Give * in new line to end
Sample file created
*
The file is created
Checking the created file
D:\java>type sample.txt
Sample file created
D:\java>
20
examkey.wordpress.com
LAB
Ex.No :10
Aim:
To write a java program to copy one file to another.
Algorithm:
1. Import the package java.io.*
2. Initialize two strings
3. Get the source file and store it in one string
4. Copy the source file into another file
Program:
import java.io.*;
class FileCopyDemo
{
public static void main(String srgs[])
{
String infile,outfile;
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
try
{
fout.write(myarr);
}
21
System.out.println(e.getMessage());
}
}
Output:
1. D:\java>javac FileCopyDemo.java
D:\java>java FileCopyDemo
Enter the name of the file to be copied:sample.txt
Enter the name of the new file :sa.txt
The file sample.txt is copied to sa.txt
2. Verifying the copied file
Viva Question:
What is a file?
The file is a collection of information.
What are the properties specified by the File class in java?
The File class abstracts properties like size, permission, time and date of creation and
modification.
What are streams?
Streams are logical entities that re linked with data source/ destination
What are input streams and output stream?
Input streams are used to read data from a keyboard, a disk file or from memory buffer.
Output streams are used to write data to a disk file, memory buffer or display screen etc.
How are streams classified according to the type of data?
The streams are classified into byte streams and character streams based on the
type of data they read or write.
Byte streams read and write bytes.
Character streams read and write characters and strings.
22
examkey.wordpress.com
LAB
Ex. No :1 Vectors
Aim:
To write a menu based java program that accepts a shopping list of four items
from the command line and store in a Vector and perform operations
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements
5. To add an item at the end of the vector
Algorithm:
1. Import the package java.io.* and java.util.
2. Receive four input from the command line and store it in the vector
3. Using Switch statement, do all vector operations
4. Perform the operation by using vector.
Program:
import java.io.*;
import java.util.*;
class DemoVector
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
Vector v=new Vector();
int ch;
for(int i=0;i<4;i++)
v.addElement(args[i]);
System.out.println("\nThe items in the shopping list");
23
examkey.wordpress.com
LAB
System.out.println("\n**********************");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
do
{
System.out.println("\n\t\t\tMenu");
System.out.println("\t\t\t******");
System.out.println("\t\t1. To add an item at a specific
location in the list.");
System.out.println("\t\t2. To delete an item in the list.");
System.out.println("\t\t3. To print the contents of the
vector.");
System.out.println("\t\t4. To delete all elements.");
System.out.println("\t\t5. To add an item at the end of the
vector.");
System.out.println("\t\t6. Exit");
System.out.print("\n\n\tEnter your choice:");
ch=Integer.parseInt(din.readLine());
switch(ch)
{
case 1:
System.out.print("\nEnter the item to be added to the list:");
String s=din.readLine();
System.out.print("\nEnter the position to be inserted:");
int pos=Integer.parseInt(din.readLine());
v.insertElementAt(s,pos);
break;
case 2:
System.out.print("\nEnter the item to be deleted from the
list:");
s=din.readLine();
24
examkey.wordpress.com
LAB
v.removeElement(s);
break;
case 3:
if(v.isEmpty())
System.out.println("The shopping list is empty");
else
{
System.out.println("\nThe items in the shopping
list");
System.out.println("\n**********************");
or(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
break;
case 4:
v.removeAllElements();
break;
case 5:
System.out.print("\nEnter the item to be
aded to the list:");
s=din.readLine();
v.addElement(s);
break;
}
}while(ch<=5);
}
}
Output:
D:\java>javac DemoVector.java
D:\java>java DemoVector LuxSoap Rin HairOil Rice
The items in the shopping list
25
examkey.wordpress.com
LAB
**********************
LuxSoap
Rin
HairOil
Rice
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:1
Enter the item to be added to the list:Dhal
Enter the position to be inserted:2
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:3
The items in the shopping list
**********************
LuxSoap
Rin
Dhal
HairOil
26
examkey.wordpress.com
LAB
Rice
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:5
Enter the item to be added to the list:ToothPaste
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:3
The items in the shopping list
**********************
LuxSoap
Rin
Dhal
HairOil
Rice
ToothPaste
Menu
******
1. To add an item at a specific location in the list.
27
examkey.wordpress.com
LAB
examkey.wordpress.com
LAB
29
examkey.wordpress.com
LAB
Ex.No.2. StringBuffer
Aim :
1. To write a java program to create a StringBuffer object and illustrate how to append
characters and to display the capacity and length of the string buffer
2. Create a StringBuffer object and illustrate how to insert characters at the beginning.
3. Create a StringBuffer object and illustrate the operations of the append() and
reverse() methods.
Algorithm:
1. Initialize the string
2. Find the length of the string
3. Insert the character at the beginning
4. Reverse the string and print
Program :
Class StringBuffer
{
Public static void main(String args[])
{
}
}
OUTPUT
Length 6
Capacity 22
RAJ RAM
C.RAJ RAM
30
examkey.wordpress.com
LAB
Aim:
To write a program in java with a class Rectangle with the data fields width, length, area
and colour. The length, width and area are of double type and colour is of string type.The
methods are get_length(), get_width(), get_colour() and find_area().
Create two objects of Rectangle and compare their area and colour. If the area and colour
both are the same for the objects then display Matching Rectangles, otherwise display Nonmatching Rectangle.
Algorithm:
1. Initialize length and breadth,color of rectangles
2. Get input for 2 rectangles from the user
3. Find matching between rectangles
4. Print the status whether it is matching or not
Program:
/* Program in Java to compare the values in two objects*/
import java.io.*;
/* Rectangle class */
class Rectangle
{
private double length,width,area;
private String colour;
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
void get_length()throws IOException
{
System.out.print("Enter the length:");
length=Double.parseDouble(din.readLine());
31
examkey.wordpress.com
LAB
}
void get_width()throws IOException
{
System.out.print("Enter the width:");
width=Double.parseDouble(din.readLine());
}
void get_colour()throws IOException
{
System.out.print("Enter the colour:");
colour=din.readLine();
}
double find_area()
{
area=length*width;
return area;
}
String put_colour()
{
return colour;
}
}
/* Main class */
class MatchRect
{
public static void main(String args[])throws IOException
{
Rectangle r1,r2;
r1=new Rectangle();
r2=new Rectangle();
System.out.println("Enter the data for Rectangle 1:");
r1.get_length();
32
examkey.wordpress.com
LAB
r1.get_width();
r1.get_colour();
System.out.println("Enter the data for Rectangle 2:");
r2.get_length();
r2.get_width();
r2.get_colour();
String c1=r1.put_colour();
String c2=r2.put_colour();
if ((r1.find_area()==r2.find_area()) && (c1.compareTo(c2)==0))
System.out.println("\n\tMatching Rectangles");
else
System.out.println("\n\tNon-Matching Rectangles");
}
}
Output:
D:\java>javac MatchRect.java
D:\java>java MatchRect
Enter the data for Rectangle 1:
Enter the length:6
Enter the width:5
Enter the colour:Pink
Enter the data for Rectangle 2:
Enter the length:5
Enter the width:6
Enter the colour:Pink
Matching Rectangles
D:\java>javac MatchRect.java
D:\java>java MatchRect
Enter the data for Rectangle 1:
Enter the length:5
Enter the width:5
33
examkey.wordpress.com
LAB
34
examkey.wordpress.com
LAB
Ex. No :4
Aim:
To write a java program to define a class that represent Complex numbers with
constructor to enable an object of this class to be initialized when it is declared and a default
constructor when no argument is provided and define methods to do the following by passing
objects as arguments
a) Addition of two Complex numbers
b) Subtraction of two Complex numbers
c) Printing the Complex numbers in the form (a, b).
Algorithm:
1. Initialize two complex number
2. Find the sum of the two complex number
3. Find the subract of the two complex number
4. Print the complex number in form(a,b)
Program:
/* passing object as parameters */
class Complex
{
int r,i;
Complex()
{
r=i=0;
}
Complex(int a,int b)
{
r=a;
35
examkey.wordpress.com
LAB
i=b;
}
void display( )
{
System.out.println("("+r+","+i+")");
}
Complex add(Complex c1,Complex c2)
{
Complex c3=new Complex();
c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i;
return c3;
}
Complex sub(Complex c1,Complex c2)
{
Complex c3=new Complex();
c3.r=c1.r-c2.r;
c3.i=c1.i-c2.i;
return c3;
}
}
/* Main class */
class CompNum
{
public static void main(String args[])
{
Complex x1,x2,x3,x4;
x1=new Complex(7,5);
x2=new Complex(4,3);
x3=new Complex();
x4=new Complex();
36
examkey.wordpress.com
LAB
x3=x1.add (x1,x2);
x4=x1.sub(x1,x2);
System.out.print("The first number :");
x1.display();
System.out.print("The second number :");
x2.display();
System.out.print("The sum :");
x3.display();
System.out.print("The difference :");
x4.display();
}
}
Output:
D:\java>javac CompNum.java
D:\java>java CompNum
The first number :(7,5)
The second number :(4,3)
The sum :(11,8)
The difference :(3,2)
Viva Questions:
What is a constructor?
Constructors are
The
examkey.wordpress.com
LAB
Ex . No: 5 Inheritanceng.
Aim:
To write a java program to create a Player class and inherit three classes Cricket_Player,
Football_Palyer and Hockey_Player.
Algorithm:
1. Import the package java.io.*
2. Create a class player as a base class
3. Inherit Cricket,football,hockey classes from the player class.
Program
/* Hierarchical Inheritance */
/* Super class */
class Player
{
String name;
Player(String n) //Constructor
{
name=n;
}
void display()
{
System.out.println("Player name:"+name);
}
}
/*Sub class 1*/
class Cricket_Player extends Player
{
String pos;
Cricket_Player(String n,String s)
{
38
examkey.wordpress.com
LAB
examkey.wordpress.com
LAB
{
super(n); //Calling super class constructor
pos=s;
}
void print()
{
System.out.println("\n\n\tHockey Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Main class */
class DemoInher
{
public static void main(String args[])
{
Cricket_Player c=new Cricket_Player("Kumble","Bowler");
Football_Player f=new Football_Player("Anand","Football
receiver");
Hockey_Player h=new Hockey_Player("Parzan","Defence man");
c.print();
f.print();
h.print();
}
}
Output:
D:\java>javac DemoInher.java
D:\java>java DemoInher
Cricket Player
Player name:Kumble
Category :Bowler
40
examkey.wordpress.com
LAB
Football Player
Player name:Anand
Category :Football receiver
Hockey Player
Player name:Parzan
Category :Defence man
D:\java>
Viva Questions:
What is inheritance?
Inheritance is the process of deriving a new class from an existing class. The newly
created class is called sub class and the already existing class is called super class.
What are the types of inheritance?
Single inheritance: One super class and single sub class.
Multiple inheritance: More than one super class and single subclass.
Hierarchial inheritance: one super class and more than one subclass.
Multilevel inheritance : Deriving a sub class from another sub class
Explain multiple inheritance in java?
In java we can have only one super class for a sub class so we cannot directly implement
multiple inheritance. We use the concept of Interface which allows us to
extend more than one super class.
Syntax for deriving a sub class
class subclassName extends superclassname
{
//define the members
}
41
examkey.wordpress.com
LAB
Ex. No :6Packages
Aim:
To write a java program to create a package for Book details giving Book name, Author
name, price and year of publishing.
Program:
Step1:
Create a subdirectory inside the root directory which has the same name as the package
you are going to create.
D:\JAVA>md book
Step2:
Create the class of your package with the first statement as the package statement and
save the file with .java extension in the directory created.
/* BookDetails class in package Book */
package book;
public class BookDetails
{
String name,author;
float price;
int year;
public BookDetails(String n,String a,float p,int y)
{
name=n;
author=a;
price=p;
year=y;
}
public void display()
{
42
examkey.wordpress.com
LAB
43
examkey.wordpress.com
LAB
Step 6:
Compile and execute the program.
Output:
D:\java>javac BookDemo.java
D:\java>java BookDemo
Book Name :Java Programming
Book Author :Balguruswamy
Book Price :Rs 190.0
Year of Publishing:2007
D:\java>
Viva questions:
What is package?
Package is a collection of interfaces and classes.
How a package can be created?
A package can be created using the package statement.
How a package can be imported into the program?
A package can be imported using the import statement.
44
examkey.wordpress.com
LAB
Scrollbar red,green,blue;
Label l1,l2,l3;
Color col=Color.pink;
int r,g,b;
public void init()
{
setBackground(Color.white);
l1=new Label("Red");
l2=new Label("Green");
l3=new Label("Blue");
red=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
green=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
blue=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
45
examkey.wordpress.com
LAB
setLayout(new FlowLayout());
add(l1);
add(red);
add(l2);
add(green);
add(l3);
add (blue);
red.addAdjustmentListener(this);
green.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
r=red.getValue();
g=green.getValue();
b=blue.getValue();
col=new Color(r,g,b);
repaint();
}
public void paint(Graphics g)
{
g.setColor(col);
g.fillRect(150,100,100,70);
showStatus("Adjust the Scroll bars to change the color of the
Rectangle");
}
}
Output
46
examkey.wordpress.com
LAB
Aim :
To write an applet program for creating a simple calculator to perform Addition,
Subtraction, Multiplication and Division using Button, Label and TextField component.
Algorithm:
1. Import the package Java.awt.*, java.awt.event.*;
2. Create a class that extends Applet
3. Create two text boxes to enter number
4. Create check box group which contains add, sub, mul, div check boxes.
5. Create a OK button
6. Do the appropriate operations according to the selected check boxes
Program:
/* Calculator using applet */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="calci.class" width=400 height=250 > </applet> */
47
examkey.wordpress.com
LAB
examkey.wordpress.com
LAB
butpan.add(oprpan);
add("North",tf);
add("Center",butpan);
reg1=reg2=0.0;
operator=" ";
tf.setText("0");
isNew=true;
for(int i=0;i<12;i++) //Registering the Listeners
b1[i].addActionListener(this);
for(int i=0;i<5;i++)
b2[i].addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String cmd=e.getActionCommand();
if(cmd.equals("C")) // Clearing the registers
{
reg1=0.0;
reg2=0.0;
operator="";
tf.setText("0");
isNew=true;
}
else if(isNumber(cmd))
{
if(isNew)
text=cmd;
else
text=tf.getText()+cmd;
tf.setText(text);
isNew=false;
49
examkey.wordpress.com
LAB
}
else if(isOperator(cmd))
{
String val=tf.getText();
reg2=Double.parseDouble(val);
reg1=calculation(operator,reg1,reg2);
Double temp=new Double(reg1);
text=temp.toString();
tf.setText(text);
operator=cmd;
isNew=true;
}
}
/*Method to check whether the button pressed is a number*/
boolean isNumber(String s)
{
for(int i=0;i<11;i++)
{
if (s.equals(num[i]) )
return true;
}
return false;
}
/*Method to check whether the button pressed is a operator*/
boolean isOperator(String s)
{
for(int i=0;i<5;i++)
{
if (s.equals(opt[i]) )
return true;
}
50
examkey.wordpress.com
LAB
return false;
}
/*Method to perform calculation and return the value*/
double calculation(String op,double r1,double r2)
{
if (op.equals("+"))
reg1=reg1+reg2;
else if (op.equals("-"))
reg1=reg1-reg2;
else if (op.equals("*"))
reg1=reg1*reg2;
else if (op.equals("/"))
reg1=reg1/reg2;
else
reg1=reg2;
return reg1;
}
}
Output:
51
examkey.wordpress.com
LAB
Ex. No :9
Aim :
To write an applet program to draw a bar chart for the following details:
Algorithm:
1. Import the package Java.awt.*, java.awt.event.*;
2. Write the Applet within comment tag in that pass some argument
3. Create a class that extends Applet
4. Draw the bar chart by using the value received by the argument
Program:
Applet Program:
/* Applet to draw a bar chart */
import java.applet.* ;
import java.awt.*;
public class BarChart extends Applet
52
examkey.wordpress.com
LAB
{
int n=0;
String label[];
int value[];
public void init()
{
try
{
n= Integer.parseInt(getParameter("columns"));
label= new String[n];
value= new int[n];
label[0]= getParameter("label1");
label[1]= getParameter("label2");
label[2]= getParameter("label3");
label[3]= getParameter("label4");
value[0]= Integer.parseInt(getParameter("m1"));
value[1]= Integer.parseInt(getParameter("m2"));
value[2]= Integer.parseInt(getParameter("m3"));
value[3]= Integer.parseInt(getParameter("m4"));
}
catch(NumberFormatException e)
{
}
}
public void paint(Graphics g)
{
String msg=label[0];
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawLine(100,50,100,350);
53
examkey.wordpress.com
LAB
g.drawLine(100,350,300,350);
g.setColor(Color.blue);
g.drawString(label[i],40,145+(50*i));
g.setColor(Color.green);
g.fillRect(100,125+(50*i),value[i] ,30);
showStatus("Bar chart Applet");
}
}
}
54
examkey.wordpress.com
LAB
Viva Questions:
What is an applet?
Applet is a small interactive java programs that are used for web application.
What are the two packages that are needed to create an applet?
Java.awt and java.applet
What is an applet tag?
Applet tag is an HTML tag that is used to run the java applets.
What is an event?
Events is an interruption given to the running program using input devices such
as mouse, keyboard etc.
What package is needed to handle an event?
java.awt.event
What is the purpose of Scrollbar class?
Scroll bars provide a user interface that is used to scroll through a range of
integer values and also provide methods to read and set these values.
What are the steps needed to handle the event?
1. Import java.awt.event
2. Implement the corresponding Event Listener interfaces
3. Register the Event Listeners with the event source.
4. Override the appropriate methods of the listener interfaces.
examkey.wordpress.com
Aim:
To write a java program for generating two threads, one for generating even number and
one for generating odd number.
Algorithm:
1. Create the classes even,odd that extends Thread
2. Even Thread class is used to print even number
3. Odd Thread class is used to print odd number
4. In the main program start two thread
Program:
class even extends Thread
{
public void run()
{
for(int i=0;i<=10;i+=2)
{
System.out.println("Even numbers"+i);
}
}
}
56
examkey.wordpress.com
LAB
examkey.wordpress.com
LAB
Viva Questions:
What is thread?
A thread is a single sequential flow of control within a program.
What is multithreading?
Multithreading is the process of running more than one thread at a time.
What are the two ways of creating thread?
A thread can be created by extending Thread class or implementing Runnable
interface.
What are the steps in creating and running thread?
Declare a class that extends Thread class.
Implement the run( ) method that is responsible for executing the sequence of
code that the thread will execute.
Create a thread object in the main class and call the start( ) method to initiate
execution.
58
examkey.wordpress.com
LAB
59