You are on page 1of 51

Faculty of Engineering and Technology

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

LAB MANUAL
Programming with JAVA

Subject In-charge: Nidhi Gour


LIST OF EXPERIMENTS

1. Operators and Expressions


a. To write a java program to find the area of rectangle
b. To write a java program to find the result of the following expressions
i) (a<<2) + (b>>2)
ii) (b>0)
iii) (a+b*100) /10
iv) a & b
Assume a=10 and b=5
c. To write a java program to print the individual digits of a 3 digit number.

2. Decision Making Statements


a. 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”.
b.To write a java program to read an integer and find whether the number is odd or
even
c. To write a java program find the biggest of three integers.
3. Looping Statements
a. To write a java program to find the sum of digits of a given number
b. To write a java program to find the first 15 terms of Fibonacci sequence.
c. To write a java program to print the Armstrong numbers.
4. Array
a. To write a java program to find the largest and smallest number in an
array.
5. Strings
a. To write a java program that creates a string object and initializes it with
your name and performs the following operations
i) To find the length of the string object using appropriate String
method.
ii) 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

6. String Buffer
a. 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
b. To write a java program to create a StringBuffer object and illustrate how
to insert characters at the beginning
c. To write a java program to Create a StringBuffer object and illustrate the
operations of the append () and reverse () methods.
7. Classes and Objects
a. To write a java program to display total marks of 5 students using student
class. Given the following attributes: Regno(int), Name(string), Marks in
subjects(Integer Array), Total (int).

b. 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 “Non-matching Rectangle”.

8. Inheritance
a. write a java program to create a Player class and inherit three classes
Cricket_Player, Football_Palyer and Hockey_Player.
9. Interfaces
a. To write a java program to show how a class implements two interfaces.
b. To write a java program to show that the variables in an interface are
implicitly static and final and methods are automatically public
10. Packages
a. To write a java program to create a package for Book details giving Book
name, Author name, price and year of publishing.

11. Applets & AWT


a. To write a java applet program to change the color of a rectangle using
scroll bars to change the value of red, green and blue
b. To write an applet program for creating a simple calculator to perform
Addition, subtraction, Multiplication and Division using Button, Label and
TextField component.
12. Exception Handling
a. To write a java program to catch more than two exception
b. To write a java program to create our exception subclass that throws
exception if the sum of two integers is greater than 99.
13. Multithreading
a. To write a java program for generating two threads, one for generating
even number and one for generating odd number.
1. OPERATORS & EXPRESSION

(A) Aim: To write a java program to find the area of rectangle


Program:
/* Program to find area of rectangle */
import java.util.*;
class AreaRect
{
public static void main(String args[])
{
int len,bre,area;
Scanner sc= new Scanner(System.in);
len=sc.nextInt();
bre=sc.nextInt();
area=len*bre;
System.out.println("Length of Rectangle ="+len);
System.out.println("Breadth of Rectangle ="+bre);
System.out.println("Areaof Rectangle ="+area);
}
}
Output:
D:\java>javac AreaRect.java
D:\java>java AreaRect 12 6
Length of Rectangle =12
Breadth of Rectangle =6
Areaof Rectangle =72
D:\java>
(B)Aim: To write a java program to find the result of the following expressions
i)(a<<2) + (b>>2)
ii)(b>0)
iii)(a+b*100) /10
iv)a & b
Assume a=10 and b=5
Program:
class Operators
{
public static void main(String args[])
{
int a=10,b=5;
System.out.println("a ="+a);
System.out.println("b ="+b);
int r1= (a<<2) +(b>>2);
boolean r2=b>0;
int r3=( a + b * 100)/10;
int r4=a&b;
System.out.println("Result of(a<<2)+ (b>>2) is "+ r1);
System.out.println("Result of (b>0) is "+(b>0));
System.out.println("Result of ( a + b * 100) /10 is "+r3);
System.out.println("Result of (a & b) is "+ r4);
}
}
(C)Aim: To write a java program to print the individual digits of a 3 digit number.
Program:
/* Program to print the individual digits of a 3-digit number */
import java.util.*;
class Digits
{
public static void main(String args[])
{
int n,r;
Scanner sc=new Scanner(System.in);

n=sc.nextInt();
System.out.println("The number is "+ n);
System.out.println("The digits in the number are");
System.out.println("**************************");
r=n%10; /* Find the one's digit */
System.out.println(r);
n=n/10; /* Reduce the number */
r=n%10; /* Find the ten's digit */
System.out.println(r);
n=n/10; /* Reduce the number */
r=n%10; /* Find the hundred'slast digit */
System.out.println(r);
}
}
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>
2. DECISION MAKING STATEMENTS

(A)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”.

Program:
/* Program to find the largest number */
import java.util.*;
class Large
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter the value of a:");
a=sc.nextInt();
System.out.print("Enter the value of b:");
b= sc.nextInt();
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");
else
System.out.println(b+" is larger");
}
}
Output :
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
(B)Aim:To write a java program to read an integer and find whether the number is
odd or even.
Program:
/* Program to determines and prints whether it is odd or even. */
import java.util.*;
class Odd
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n;
System.out.print("Enter a number:");
n=sc.nextInt();
if(n%2==0)
System.out.println(n+" is an even number");
else
System.out.println(n+" is an odd number");
}
}Output 1:
D:\java>javac Odd.java
D:\java>java Odd
Enter a number: 56
56 is an even number
Output 2:
D:\java>java Odd
Enter a number: 67
67 is an odd number
(C)Aim: To write a java program find the biggest of three integers

Program:
/* Program to find the biggest of three integers */
import java.util.*;
class Big
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter number 1:");
a=sc.nextInt();
System.out.print("Enter number 2:");
b=sc.nextInt();
System.out.print("Enter number 3:");
c=sc.nextInt();
System.out.println("a="+a+"\t\tb="+b+"\t\tc="+c);
if (a>b)
{
if(a>c)
System.out.println(a+" is the biggest number");
else
System.out.println(c+" is the biggest number");
}
else
{
if(b>c)
System.out.println(b+" is the biggest number");
else
System.out.println(c+" is the biggest number");
}
}
} Output:
D:\java>javac Big.java
D:\java>java Big
Enter number 1:4
Enter number 2:5
Enter number 3:2
a=4 b=5 c=2
5 is the biggest number
3. LOOPING STATEMENTS

(A)Aim:To write a java program to find the sum of digits of a given number
Program:
/* Program to print the sum of digits of the given number*/
import java.util.*;
class SumDigit
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,sum=0;
System.out.print("Enter the number:");
n=sc.nextInt();
int m=n;
while(n!=0)
{
int r=n%10; /* Find the last digit */
sum=sum+r;
n=n/10; /* Reduce the number */
}
System.out.println("The sum of the digits in the number "+m+" is "+sum);
}
}
Output:
D:\java>javac SumDigit.java
D:\java>java SumDigit
Enter the number:5478
The sum of the digits in the number 5478 is 24
(B)Aim: To write a java program to find the first 15 terms of Fibonacci sequence.

Program:
/* First 15 terms of Fibonacci sequence */
class Fibo
{
public static void main(String args[])
{
int f1=0,f2=1,f3;
System.out.println("Fibonacci sequence ");
System.out.println("**************");
System.out.print("\t"+f1+"\t"+f2);
for(int i=3;i<=15;i++)
{
f3=f1+f2;
System.out.print("\t"+f3);
f1=f2;
f2=f3;
}
}
}
Output:
D:\java>javac Fibo.java
D:\java>java Fibo
Fibonacci sequence
****************
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
(C)Aim: To write a java program to print the Armstrong numbers.
Note:
Armstrong numbers are the three digit numbers whose sum of cubes of the digits
of the number is equal to the number itself.
Example:
153=13+53+33= 1 + 125 +27 =153 is an Armstrong number

Program:
/* Program to print the Armstrong numbers*/
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;
int 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);
}
}
}
Output:
D:\java>javac Armstrong.java
D:\java>java Armstrong
Armstrong numbers
*****************
153
370
371
407
4. ARRAYS

Aim:
To write a java program to find the largest and smallest number in an array.
Program:
/* Program to find the biggest and smallest number in the array */
import java.io.*;
class ArrBig
{
public static void main(String args[])throws IOException
{
int a[]=new int[20];
int n,big,small;
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of terms in the array:");
n=Integer.parseInt(din.readLine());
System.out.println("Enter array element:");
for(int i=0;i<n;i++)
{
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) small=a[i];
}
System.out.println("\nThe elements in the array");
System.out.println("***********************");
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
D:\java>
5. STRINGS

(A)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
Program:
/* Program to find whether the character ‘a’ is in your name or not; if yes find the
number of times ‘a’ appears in your name. Print locations of occurrences of ‘a’ */
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'))
{
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>
6. STRINGBUFFER

(A)Aim: 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

Program:
/* Program to create a StringBuffer object and illustrate how to append characters.
Display the capacity and length of the string buffer.*/
class StringBufferDemo1
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("Java");
System.out.println("The data in the string buffer:"+ s1);
System.out.println("Capacity of the Buffer :"+s1.capacity());
System.out.println("Length of buffer:"+s1.length());
s1.append("Programming");
System.out.println("The data in the StringBuffer after appending characters is
"+s1);
}
}
Output:
D:\java>javac StringBufferDemo1.java
D:\java>java StringBufferDemo1
The data in the string buffer:Java
Capacity of the Buffer :20
Length of buffer:4
The data in the StringBuffer after appending characters is JavaProgramming
D:\java>
(B)Aim :To write a java program to create a StringBuffer object and illustrate how
to
insert characters at the beginning
Program :
/* Program to create a StringBuffer object and illustrate how to insert characters at
the beginning.*/
class StringBufferDemo2
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("Java");
System.out.println("The data in the string buffer "+ s1);
s1.insert(0,"I Like ");
System.out.println("The data after inserting characters in the beginning is "+s1);
}
}
Output:
D:\java>javac StringBufferDemo2.java
D:\java>java StringBufferDemo2
The data in the string buffer Java
The data after inserting characters in the beginning is I Like Java
D:\java>
(C)Aim: To write a java program to Create a StringBuffer object and illustrate the
operations of the append() and reverse() methods.
Program:
/* Program toCreate a StringBuffer object and illustrate the operations of the
append() and reverse() methods..*/
class StringBufferDemo3
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("Java");
System.out.println("The data in the string buffer s1: "+ s1);
s1.append("Programming");
System.out.println("The data in the string buffer after appending characters to s1 :
"+s1);
s1.reverse();
System.out.println("The reverse of string s1 :"+s1);
}
}
Output:
D:\java>javac StringBufferDemo3.java
D:\java>java StringBufferDemo3
The data in the string buffer s1: Java
The data in the string buffer after append
ing characters to s1: JavaProgramming
The reverse of string s1 :gnimmargorPavaJ
D:\java>
7. CLASSES &OBJECTS

(A)Aim: To write a java program to display total marks of 5 students using student
class. Given the following attributes: Regno(int), Name(string), Marks in
subjects(Integer Array),Total (int).
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 BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the Reg.No: ");
regno=Integer.pars
eInt(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];
}
void display()
{
System.out.println(regno+"\t"+name+"\t"+mark[0]+"\t"+mark[1]+"\t"+mark[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
Enter the Mark3: 92
Enter the Reg.No: 3
Enter the Name: Vimal
Enter the Mark1: 87
Enter the Mark2: 60
Enter the Mark3: 71
Enter the Reg.No: 4
Enter the Name: Fancy
Enter the Mark1: 92
Enter the Mark2: 89
Enter the Mark3: 86
Enter the Reg.No: 5
Enter the Name: Janani
Enter the Mark1: 78
Enter the Mark2: 90
Enter the Mark3: 91
Mark List
*********
RegNo Name Mark1 Mark2 Mark3 Total
1 Balu 67 90 56 213
2 Geetha 87 79 92 258
3 Vimal 87 60 71 218
4 Fancy 92 89 86 267
5 Janani 78 90 91 259
(B)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 “Non-matching Rectangle”.
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());
}
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();
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
Enter the colour:Green
Enter the data for Rectangle 2:
Enter the length:5
Enter the width:5
Enter the colour:Pink
Non-Matching Rectangles
D:\java>
8. INHERITANCE

(A)Aim: To write a java program to create a Player class and inherit three classes
Cricket_Player, Football_Palyer and Hockey_Player.

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)
{
super(n); //Calling super class constructor
pos=s;
}
void print()
{
System.out.println("\n\n\tCricket Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Sub class 2 */
class Football_Player extends Player
{
String pos;
Football_Player(String n,String s)
{
super(n); //Calling super class constructor
pos=s;
}
void print()
{
System.out.println("\n\n\tFootball Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Sub class 3 */
class Hockey_Player extends Player
{
String pos;
Hockey_Player(String n,String s)
{
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
Football Player
Player name:Anand
Category :Football receiver
Hockey Player
Player name:Parzan
Category :Defence man
D:\java>
9. INTERFACES

(A)Aim: To write a java program to show how a class implements two interfaces.

Program:
/* Program to show a implementing two interfaces */
/* First interface */
interface One
{
int x=12;
}
/* Second interface */
interface Two
{
int y=10;
void display();
}
/* Class implementing the interfaces */
class Demo implements One,Two
{
public void display()
{
System.out.println("X in inteface One ="+x);
System.out.println("Y in interface Two="+y);
System.out.println("X+Y= "+(x+y));
}
}
/* 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
D:\java>

(B)Aim: To write a java program to show that the variables in an interface are
implicitly static and final and methods are automatically public

Program:
/* Program to show the variables in an interface are implicitly static and final and
methods are automatically public */
/* Interface */
interface One
{
int x=12;
void display();
}
/* Class implementing interface */
class Demo implements One
{
void display() //Default privilege
{
System.out.println("X="+x+"\nAdd 10 to x");
x=x+10;
}
}
/* Main class */
class InterDemo
{
public static void main(String args[])
{
Demo d=new Demo();
d.display();
}
}
Output:
D:\java>javac InterDemo.java
InterDemo.java:6: display() in Demo cannot implement display() in One;
attempting to assign weaker access privileges; was public
class Demo implements One
^
InterDemo.java:11: cannot assign a value to final variable x
x=x+10;
^
2 errors
D:\java>
In the above program the value of the variable x is not defined as final also the
display method is not declared to be public in the interface. But when we try to
change the value of x in the implementing class and assign default access privilege
to the display method the syntax error will occur which shows that the variables in
an interface are
implicitly static and final and the methods are public.
10.PACKAGES

(A)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()
{
System.out.println("Book Name :"+name);
System.out.println("Book Author :"+author);
System.out.println("Book Price :Rs "+price);
System.out.println("Year of Publishing:"+year);
}
}
Step 3:
Compile the java file
D:\java>cd book
D:\java\book>javac BookDetails.java
Step 4:
Return to root directory
C:\javapgm\book>cd..
D:\JAVA >
Step 5:
In the main program import the created package into the program using the import
statement and key in the program where we can create instances of the classes in
the package.

Save the program in the root directory


Main class:
/* Class that imports book package */
import book.*;
class BookDemo
{
public static void main(String args[])
{
BookDetails b=new BookDetail
s("Java Programming", "Balguruswamy",
190.00f, 2007);
b.display();
}
}
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>
11.APPLET & AWT

(A)Aim: To write a java applet program to change the color of a rectangle using
scroll bars to change the value of red, green and blue.

Program:
/* Colour using Scroll bar */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="Sbar.class" width=400 height=250 ></applet> */
public class Sbar extends Applet implements AdjustmentListener
{
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(Scro
llbar.HORIZONTAL,0,0,0,255);
blue=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
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");
}
}
(B)Aim: To write an applet program for creating a simple calculator to perform
Addition,
subtraction, Multiplication and Division using Button, Label and TextField
component.

Program:
/* Calculator using applet */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="calci.class" width=400 height=250 ></applet> */
public class calci extends Applet implements ActionListener
{
String num[]={"1","2","3","4","5","6","7","8","9",".","0","C"};
String opt[]={"+","-","*","/","="};
Button b1[],b2[];
Panel numpan,oprpan,butpan;
TextField tf=new TextField(20);
double reg1,reg2;
String text,operator;
boolean isNew;
public void init()
{
numpan=new Panel();
numpan.setLayout(new GridLayout(4,3));
b1=new Button[12];
for(int i=0;i<12;i++)
//Creating number buttons
{
b1[i]=new Button(num[i]);
numpan.add(b1[i]); }
oprpan=new Panel();
oprpan.setLayout(new GridLayout(5,1));
b2=new Button[5];
for(int i=0;i<5;i++)
//Creating operator buttons
{
b2[i]=new Button(opt[i]);
oprpan.add(b2[i]);
}
setLayout(new BorderLayout());
butpan=new Panel(new GridLayout(1,2));
butpan.add(numpan);
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;
}
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;
}
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:
(B)Aim: To write an applet program to draw a bar chart for the following details:

Subject Tamil English Maths Physics


Marks 78 85 98 56

Program:
Applet Program:
/* Applet to draw a bar chart */
import java.applet.* ;
import java.awt.*;
public class BarChart extends Applet
{
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);
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");
}
}
}
HTML files to pass parameter:
<HTML>
<BODY>
<APPLET CODE="BarChart.class" HEIGHT=400 WIDTH=500>
<PARAM name="columns" VALUE=4>
<PARAM name="label1" VALUE="Tamil">
<PARAM name="label2" VALUE="English">
<PARAM name="label3" VALUE="Maths">
<PARAM name="label4" VALUE="Physics">
<PARAM name="m1" VALUE="78">
<PARAM name="m2" VALUE="85">
<PARAM name="m3" VALUE="98">
<PARAM name="m4" VALUE="56">
</APPLET>
</BODY>
</HTML>
12.EXCEPTION HANDLING

(A)Aim:To write a java program to catch more than two exception

Program:
/* Exception handling Multiple catch block*/
class MultiExp
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
System.out.println(a+" / "+b+"="+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error occurred");
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Supply two arguments from the command line");
System.out.println(e);
}
catch(NumberFormatException e)
{
System.out.println("Not valid Integers");
System.out.println(e);
}
}
}
Output:
D:\java>javac MultiExp.java
D:\java>java MultiExp 12 6
12 / 6=2
C:\javapgm>java MultiExp 12
Supply two arguments from the command line
java.lang.ArrayIndexOutOfBoundsException
C:\javapgm>java MultiExp 12 a
Not valid Integers
java.lang.NumberFormatException: a
D:\java>
(B)Aim: To write a java program to create our exception subclass that throws
exception if the sum of two integers is greater than 99.

Program:
/* User defined exception class */
import java.io.*;
/* User defined exception class */
class MyException extends Exception
{
MyException(String mg)
{
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());
System.out.print("Enter the value of B:");
b=Integer.parseInt(bin.readLine());
try
{
int c=a+b;
if(c>99)
throw new MyException("The numbers are too big");
System.out.println(a+"+"+b+"="+c);
}
catch(MyException e)
{
System.out.println("The sum of numbers should be less than 99");
System.out.println(e.getMessage());
}
}
}
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
D:\java>
13.MULTITHREADING

(A)Aim: To write a java program for generating two threads, one for generating
even number and one for generating odd number.

Program:
/* Thread to generate even number and odd number */
class EvenThread extends Thread
/* Thread to generate even number */
{
EvenThread(String name)
{
super(name);
}
public void run()
{
try
{
for(int i=1;i<15;i++)
{
if (i%2==0)
System.out.println(getName()+"\t"+i);
Thread.sleep(1000);
}
System.out.println("Exit from thread "+getName());
}
catch(InterruptedException e)
{
System.out.println("Thread "+getName()+" Interrupted");
}
}}
/* Thread to generate odd number */
class OddThread extends Thread
{
OddThread(String name)
{
super(name);
}
public void run()
{
try
{
for(int i=1;i<15;i++)
{
if (i%2!=0)
System.out.println(getName()+"\t"+i);
Thread.sleep(500);
}
System.out.println("Exit from thread "+getName());
}
catch(InterruptedException e)
{
System.out.println("Thread "+getName()+" Interrupted");
}
}
}
/* Thread Demo */
class ThreadDemo
{
public static void main(String args[])
{
EvenThread e=new EvenThread("Even");
OddThread o=new OddThread("Odd");
e.start();
o.start();
}
}
Output:
D:\java>javac ThreadDemo.java
D:\java>java ThreadDemo
Odd 1
Even 2
Odd 3
Odd 5
Even 4
Odd 7
Odd 9
Even 6
Odd 11
Odd 13
Exit from thread Odd
Even 8
Even 10
Even 12
Even 14
Exit from thread Even

You might also like