[Go to site: main page, start]

0% found this document useful (0 votes)
3 views57 pages

Java Programming Lab Manual (R21)

The document is a Java Programming Lab manual containing various exercises that cover fundamental programming concepts such as quadratic equations, prime number checks, binary search, bubble sort, palindrome checks, class and object creation, inheritance, polymorphism, and exception handling. Each exercise includes a description of the task and a corresponding Java program to demonstrate the implementation of the concepts. The manual serves as a practical guide for students to practice Java programming through hands-on coding examples.

Uploaded by

sravani b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views57 pages

Java Programming Lab Manual (R21)

The document is a Java Programming Lab manual containing various exercises that cover fundamental programming concepts such as quadratic equations, prime number checks, binary search, bubble sort, palindrome checks, class and object creation, inheritance, polymorphism, and exception handling. Each exercise includes a description of the task and a corresponding Java program to demonstrate the implementation of the concepts. The manual serves as a practical guide for students to practice Java programming through hands-on coding examples.

Uploaded by

sravani b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming Lab

Manual –R21

Exercise - 1 (Basics)
1. Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate
the discriminate D and basing on value of D, describe the nature of root.
Program:
import [Link];
public class Quadratic
{
public static void main(String[] args)
{
int a, b, c;
double root1, root2, d;
Scanner s = new Scanner([Link]);
[Link]("Given quadratic equation:ax^2 + bx + c");
[Link]("Enter a:");
a = [Link]();
[Link]("Enter b:");
b = [Link]();
[Link]("Enter c:");
c = [Link]();
[Link]("Given quadratic equation:"+a+"x^2 + "+b+"x + "+c);
d = b * b - 4 * a * c;
if(d > 0)
{
root1 = (-b + [Link](d)) / (2 * a);
root2 = (-b - [Link](d)) / (2 * a);
[Link]("roots are real and different roots");
[Link]("root1 = %.2f and root2 = %.2f", root1 , root2);
}
else if(d == 0)
{
root1 = root2 = -b / (2 * a);
[Link]("roots are real and equal roots");

[Link]("root1 = root2 = %.2f;", root1);


}
else
{
double realPart = -b / (2 *a);
double imaginaryPart = [Link](-d) / (2 * a);
[Link]("roots are imaginary");
[Link]("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart,
realPart, imaginaryPart);
}
}
}
Output:
2) Write a Java Program to find the given number is prime number or not.
Program:
import [Link];
public class Prime
{
public static void main(String[] args)
{
int num, i, count=0;
Scanner s = new Scanner([Link]);

[Link]("Enter a Number: ");


num = [Link]();

for(i=2; i<num; i++)


{
if(num%i == 0)
{
count++;
break;
}
}

if(count==0)
[Link]("\nIt is a Prime Number.");
else
[Link]("\nIt is not a Prime Number.");
}
}

Output:

Exercise - 2 (Operations, Expressions, Control-flow, Strings)


[Link] a JAVA program to search for an element in a given list of elements using binary
search mechanism.
Program:
import [Link];
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner([Link]);
[Link]("Enter number of elements:");
num = [Link]();
array = new int[num];
[Link]("Enter " + num + " integers");
for (counter = 0; counter < num; counter++)
array[counter] = [Link]();
[Link]("Enter the search value:");
item = [Link]();
first = 0;
last = num - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
[Link](item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
[Link](item + " is not found.\n");
}
}

Output:
[Link] a JAVA program to sort for an element in a given list of elements using bubble sort
Program:
import [Link];
public class BubbleSort
{
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Enter the number of elements");
int n=[Link]();
int array[] = new int[n];
for (int c = 0; c < n; c++)
{
[Link]("Enter element"+(c+1));
array[c] = [Link]();
}
[Link]("Array Before Bubble Sort");
for(int i=0; i < n; i++)
{
[Link](array[i] + " ");
}
[Link]();
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(array[j-1] > array[j])
{
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
[Link]("Array After Bubble Sort");
for(int i=0; i <n; i++)
{
[Link](array[i] + " ");
}
} }

Output:

3) Write a JAVA program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome
Program:
import [Link];
class CheckPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner([Link]);

[Link]("Enter a string:");
str = [Link]();
int length = [Link]();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + [Link](i);

if ([Link](rev))
[Link](str+" is a palindrome");
else
[Link](str+" is not a palindrome");

}
}
Output:

Exercise - 3 (Class, Objects, Constructor)


[Link] a program to create a class Student with data ‘name, city and age’ along with method
printData to display the data. Create the two objects s1 ,s2 to declare and access the values.
Program:
class Student
{
String name, city;
int age;
static int m;
void printData()
{
[Link]("Student name = "+name);
[Link]("Student city = "+city);
[Link]("Student age = "+age);
}
}
class Stest
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
[Link]="Amit";
[Link]="Dehradun";
[Link]=22;
[Link]="Kapil";
[Link]="Delhi";
[Link]=23;
[Link]();
[Link]();
s1.m=20;
s2.m=22;
Student.m=27;
[Link]("s1.m = "+s1.m);
[Link]("s2.m = "+s2.m);
[Link]("Student.m ="+Student.m);
}
}

Output:
[Link] a program in JAVA to demonstrate the method and constructor overloading.

Program:
class Cs
{
int p,q;
public Cs()
{}
public Cs(int x, int y)
{
p=x;
q=y;
}
public int add(int i, int j)
{
return (i+j);
}
public int add(int i, int j, int k)
{
return (i+j+k);
}
public float add(float f1, float f2)
{
return (f1+f2);
}
public void printData()
{
[Link]("p = "+p);
[Link](" q = "+q);
}
}
class ConstructorOverloading
{
public static void main(String args[])
{
int x=2, y=3, z=4;
Cs c=new Cs();
Cs c1=new Cs(x, z );
[Link]();
float m=7.2F, n=5.2F;
int k=[Link](x,y);
int t=[Link](x,y,z);
float ft=[Link](m, n);
[Link]("k = "+k);
[Link]("t = "+t);
[Link]("ft = "+ft);
}}

Output:

3 Write a program in JAVA to create a class Bird also declares the different parameterized
constructor to display the name of Birds.
Program:
class Bird
{
int age;
String name;
Bird()
{
[Link]("this is the perrot");
}
Bird(String x)
{
name=x;
[Link]("this is the "+name);
}
Bird(int y,String z)
{
age=y;
name=z;
[Link]("this is the "+age+"years\t"+name);
}
public static void main(String arr[])
{
Bird a=new Bird();
Bird b=new Bird("maina");
Bird c=new Bird(20,"sparrow");
}
}
Output:

Exercise - 4 (Inheritance, Method Overriding)


1. Write a JAVA program to implement Single Inheritance.

Program:

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}

Output:

[Link] a JAVA program to implement multi level Inheritance


Program:
class Car{
public Car()
{
[Link]("Class Car");
}
public void vehicleType()
{
[Link]("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
[Link]("Class Maruti");
}
public void brand()
{
[Link]("Brand: Maruti");
}
public void speed()
{
[Link]("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
[Link]("Maruti Model: 800");
}
public void speed()
{
[Link]("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
[Link]();
[Link]();
[Link]();
}
}

Output:

[Link] a java program for abstract class to find areas of different shapes
Program:
import [Link];
abstract class CalcArea {
abstract void findTriangle(double b, double h);
abstract void findRectangle(double l, double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}
class FindArea extends CalcArea {
void findTriangle(double b, double h)
{
double area = (b*h)/2;
[Link]("Area of Triangle: "+area);
}
void findRectangle(double l, double b)
{
double area = l*b;
[Link]("Area of Rectangle: "+area);
}
void findSquare(double s)
{
double area = s*s;
[Link]("Area of Square: "+area);
}
void findCircle(double r)
{
double area = 3.14*r*r;
[Link]("Area of Circle: "+area);
}
}

class Area {
public static void main(String args[])
{
double l, b, h, r, s;
FindArea ob = new FindArea();
Scanner get = new Scanner([Link]);
[Link]("\nEnter Base & Vertical Height of Triangle: ");
b = [Link]();
h = [Link]();
[Link](b, h);
[Link]("\nEnter Length & Breadth of Rectangle: ");
l = [Link]();
b = [Link]();
[Link](l, b);
[Link]("\nEnter Side of a Square: ");
s = [Link]();
[Link](s);
[Link]("\nEnter Radius of Circle: ");
r = [Link]();
[Link](r);
}
}

Output:
4. write a java program implements Runtime polymorphism (Method Overriding)
Program:

class Bike{
void run(){[Link]("running");}
}
class Splender extends Bike{
void run(){[Link]("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
[Link]();
}
}
Output:

Exercise - 5 (Array List & Exception)


[Link] Java Program to Perform String Operations Using Arraylist. Write Functions for the
following
a. Append
b. Insert
c. Search
d. List all string starts with given letter
Program:

import [Link].*;
import [Link].*;
public class ArrayListExample
{
public static void main(String args[])throws IOException
{
ArrayList<String> obj = new ArrayList<String>();
DataInputStream in=new DataInputStream([Link]);
int c,ch;
int i,j;
String str,str1;
do
{
[Link]("STRING MANIPULATION");
[Link]("******************************");
[Link](" 1. Append at end \t [Link] at particular index \t [Link] \t");
[Link]( "[Link] string that starting with letter \t");
[Link]("[Link] \t [Link] \t [Link]\t [Link]\t" );
[Link]("Enter the choice ");
c=[Link]([Link]());
switch(c)
{
case 1:
{
[Link]("Enter the string ");
str=[Link]();
[Link](str);
break;
}
case 2:
{
[Link]("Enter the string ");
str=[Link]();
[Link]("Specify the index/position to insert");
i=[Link]([Link]());
[Link](i-1,str);
[Link]("The array list has following elements:"+obj);
break;
}
case 3:
{
[Link]("Enter the string to search ");
str=[Link]();
j=[Link](str);
if(j==-1)
[Link]("Element not found");
else
[Link]("Index of:"+str+"is"+j);
break;
}
case 4:
{
[Link]("Enter the character to List string that starts with specified character");
str=[Link]();
for(i=0;i<([Link]()-1);i++)
{
str1=[Link](i);
if([Link](str))
{
[Link](str1);
}
}
break;
}
case 5:
{
[Link]("Size of the list "+[Link]());
break;
}
case 6:
{
[Link]("Enter the element to remove");
str=[Link]();
if([Link](str))
{
[Link]("Element Removed"+str);
}
else
{
[Link]("Element not present");
}
break;
}
case 7:
{
[Link](obj);
[Link]("The array list has following elements:"+obj);
break;
}
case 8:
{
[Link]("The array list has following elements:"+obj);
break;
}
}
[Link]("enter 0 to break and 1 to continue");
ch=[Link]([Link]());
}while(ch==1);
}
}

Output:
[Link] a JAVA program that describes exception handling mechanism
Program:
class ExDemo1
{
public static void main(String args[])
{
method1();
}
static void method1()
{
[Link]("In method1, calling method2");
method2();
[Link]("Returned from method2");
}
static void method2()
{
[Link]("In method2 calling method3");
try
{
method3();
}
catch( Exception e)
{
[Link]("Exception Handeled");
}
[Link]("Returned from method3");
}
static void method3()
{
[Link]("In method3");
int a=20, b=0;
int c=a/b;
[Link](" Method3 exits");
}
}
Output:
[Link] a JAVA program Illustrating Multiple catch clauses
Program:
import [Link].*;
public class MultipleCatchBlocks {
public static void main(String args[]){
Scanner scanner = new Scanner([Link]);
[Link]("Enter the divisor to divide 100 : ");
int divisor = [Link]();
try{
int[] array=new int[10];
int result = 100/divisor;
array[10]=result;
}catch(ArithmeticException e){
[Link]("Arithmetic exception has occurred");
}catch(ArrayIndexOutOfBoundsException e){
[Link]("Array Index Out Of Bounds Exception has occurred");
}catch(Exception e){
[Link]("Common exception has occurred");
}
}
}
Output:
Exercise – 6 (User defined Exception)
[Link] a JAVA program for creation of Illustrating throw
Program:
class ThrowDemo
{
public static void main( String args[])
{
method1();
}
static void method1()
{
[Link](" In method1, calling method2");
method2();
}
static void method2()
{
[Link]("In method2, calling method3");
try
{
method3();
}
catch(Exception e)
{
[Link]("Exception Handled:"+e);
}
[Link]("Returned from method3");
}
static void method3()
{
[Link]("In method3");
throw new ArithmeticException("Testing Throw");
//This line is internally commented. If not, it results in compile time error, as it leads un reachable
code.
// [Link]("Method3 exits");
}
}
Output:

[Link] a JAVA program for creation of Illustrating finally


Program:
We can illustarate finally key word by using 3 cases
Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally block execute after
the try block.
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block, and finally block
executes after the catch block.
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so finally block execute
after the try block and after the execution of finally block program terminate abnormally, But
finally block execute fine.

Example for case 3:


import [Link].*;

class GFG {
public static void main(String[] args)
{
try {
[Link]("Inside try block");

// Throw an Arithmetic exception


[Link](34 / 0);
}

// Can not accept Arithmetic type exception


// Only accept Null Pointer type Exception
catch (NullPointerException e) {

[Link](
"catch : exception not handled.");
}

// Always execute
finally {

[Link](
"finally : i will execute always.");
}
// This will not execute
[Link]("i want to run");
}
}

Output:

3. Write a JAVA program for creation of Java Built-in Exceptions

Program:
import [Link].*;
class AE
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
}
catch(ArithmeticException e)
{
[Link] ("Can't divide a number by 0");
}
try {
String a = null; //null value
[Link]([Link](0));
} catch(NullPointerException e) {
[Link]("NullPointerException..");
}
try {
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element
[Link](c);
}
catch(StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
try {

// Following file does not exist


File file = new File("C://[Link]");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
[Link]("File does not exist");
}
try {
// "akki" is not a number
int num = [Link] ("akki") ;

[Link](num);
} catch(NumberFormatException e) {
[Link]("Number format exception");
}
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
[Link] ("Array Index is Out Of Bounds");
}
}
}

Output:
[Link] a JAVA program for creation of User Defined Exception

Program:
class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
super("Invalid Age Exception ...... try valid age");
}
}
class ExceptionTest
{
public void process(int age)throws InvalidAgeException
{
if(age > 110)
{
throw new InvalidAgeException();
}
else
{
[Link]("process success");
}
}
}
public class ExceptionDemo
{
public static void main(String args[])throws InvalidAgeException
{
int Age=115;
ExceptionTest test=new ExceptionTest();
[Link](Age);
}
}

Output:
Exercise – 7 (Threads)

[Link] a JAVA program that creates threads by extending Thread class .First thread
display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds
and the third display “Welcome” every 3 seconds ,(Repeat the same by implementing
Runnable).

Program:

class GoodMorning extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
try{ [Link](1000);
}
catch(Exception e){} [Link]("GoodMorning");
}
}
}
class Hello extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{ [Link](2000);
}
catch(Exception e){} [Link]("Hello");
}
}
}
class Welcome extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{ [Link](3000);
}
catch(Exception e){} [Link]("Welcome");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
GoodMorning gm=new GoodMorning();
Thread t1=new Thread(gm);
Hello hl=new Hello();
Thread t2=new Thread(hl);
Welcome wc=new Welcome();
Thread t3=new Thread(wc); [Link]();
[Link]();
[Link]();
}
}

Output:
[Link] a java program for to solve producer consumer problem in which a producer
produce a value and consumer consume the value before producer generate the next value.
Program:

class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try {
wait();
}
catch(InterruptedException e)
{
[Link]("InterruptedException caught");
}
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
} //end of the get() method
synchronized void put(int n)
{
while(valueSet)
try {
wait();
}
catch(InterruptedException e)
{
[Link]("InterruptedException caught");
}
this.n = n;
valueSet = true;
[Link]("Put: " + n);
notify();
} //end of the put method
} //end of the class Q
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)
{
[Link](i++);
}
}
} //end of Producer
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
[Link]();
}
}
}//end of Consumer
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
[Link]("Press Control-C to stop.");
}
}
Exercise - 8 (File Handling)
[Link] a java program that displays the number of characters, lines and words in a text file

Program:

import [Link].*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStream fis = new FileInputStream("[Link]");
while([Link]()!=0)
{
code = [Link]();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
[Link]("[Link] characters = "+chars);
[Link]("[Link] words = "+(words+1));
[Link]("[Link] lines = "+(lines+1));
[Link]();
}
catch(FileNotFoundException e)
{
[Link]("Cannot find the specified file...");
}
catch(IOException i)
{
[Link]("Cannot read file...");
}}}
Output:
Exercise – 9 (JDBC & Packages)
1)Write a java program that connects to a database using JDBC of the following a. add b.
Delete c. Modify d. Retrieve operations.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Mysql{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link]( "jdbc:mysql://localhost:3306/poll","root","");

Statement stmt=[Link]();
ResultSet rs=[Link]("select * from tbmembers");
while([Link]())

[Link]([Link](1)+" "+[Link](2)+" "+[Link](3)+" "+[Link](4)+"


"+[Link](5));
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3)+" "+[Link](4)+"
"+[Link](5));
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
2.)Write a java program to create a package called employee and implement this package out
of the package.
Program:

package employee;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}

import [Link];
public class PrintName
{
public static void main(String args[])
{
String name = "Iam the Employee of PACE INSTITUTE OF TECHNOLOGY & SCIENCES";
MyClass obj = new MyClass();
[Link](name);
}
}
Output:
Exercise - 10 (Applet)
1. Write a JAVA program to paint like paint brush in applet.
Program:

import [Link].*;
import [Link].*;
import [Link].*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground([Link]);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}
public void mouseMoved(MouseEvent me){}
}

<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Output:
2. Write a JAVA program to display analog clock using Applet.
Program:

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class MyClock extends Applet implements Runnable {
int width, height;
Thread t = null;
boolean threadSuspended;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( [Link] );
}
public void start() {
if ( t == null ) {
t = new Thread( this );
[Link]( Thread.MIN_PRIORITY );
threadSuspended = false;
[Link]();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}

public void stop() {


threadSuspended = true;
}

public void run() {


try {
while (true) {

Calendar cal = [Link]();


hours = [Link]( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = [Link]( [Link] );
seconds = [Link]( [Link] );
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", [Link]() );
Date date = [Link]();
timeString = [Link]( date );
// Now the thread checks to see if it should suspend itself
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
[Link]( 1000 ); // interval specified in milliseconds
}
}
catch (Exception e) { }
}

void drawHand( double angle, int radius, Graphics g ) {


angle -= 0.5 * [Link];
int x = (int)( radius*[Link](angle) );
int y = (int)( radius*[Link](angle) );
[Link]( width/2, height/2, width/2 + x, height/2 + y );
}

void drawWedge( double angle, int radius, Graphics g ) {


angle -= 0.5 * [Link];
int x = (int)( radius*[Link](angle) );
int y = (int)( radius*[Link](angle) );
angle += 2*[Link]/3;
int x2 = (int)( 5*[Link](angle) );
int y2 = (int)( 5*[Link](angle) );
angle += 2*[Link]/3;
int x3 = (int)( 5*[Link](angle) );
int y3 = (int)( 5*[Link](angle) );
[Link]( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
[Link]( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
[Link]( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}

public void paint( Graphics g ) {


[Link]( [Link] );
drawWedge( 2*[Link] * hours / 12, width/5, g );
drawWedge( 2*[Link] * minutes / 60, width/3, g );
drawHand( 2*[Link] * seconds / 60, width/2, g );
[Link]( [Link] );
[Link]( timeString, 10, height-10 );
}
}

<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

Output:
3. Develop an Applet that receives an integer in one text field & compute its factorial
value & returns it in another text filed when the button “Compute” is clicked..
Program:

import [Link].*;
import [Link].*;
import [Link];
public class Fact extends Applet implements ActionListener
{
Label l1,l2; TextField
t1,t2; Button b1;
public void init(){
l1=new Label("enter the value"); add(l1);
t1=new TextField(10); add(t1);
b1=new Button("Factorial"); add(b1);
[Link](this);
l2=new Label("Factorial of given no is"); add(l2);
t2=new TextField(10); add(t2);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
int fact=fact([Link]([Link]()));
[Link]([Link](fact));
}
}

int fact(int f)
{
int s=0; if(f==0)
return 1; else
return f*fact(f-1);
}
}
/*<applet code="[Link]" height=300 width=300></applet>*/

Output:
Exercise - 11 (Event Handling)
1. Write a JAVA program that display the x and y position of the cursor movement using
Mouse.
Program:

import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
[Link](msg, mouseX, mouseY);
}
}
Output:
2. Write a JAVA program that identifies key-up key-down event user entering text in a
Applet.
Program:

// Demonstrate the key event handlers.


import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += [Link]();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
[Link](msg, X, Y);
}
}
Output:
Exercise - 12 (Swings)
1. Write a JAVA program to build a Calculator in Swings.
Program:

import [Link].*;
import [Link].*;
class Calc implements ActionListener
{
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
static double a=0,b=0,result=0;
static int operator=0;
Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Delete");
bclr=new JButton("Clear");
[Link](30,40,280,30);
[Link](40,100,50,40);
[Link](110,100,50,40);
[Link](180,100,50,40);
[Link](250,100,50,40);
[Link](40,170,50,40);
[Link](110,170,50,40);
[Link](180,170,50,40);
[Link](250,170,50,40);
[Link](40,240,50,40);
[Link](110,240,50,40);
[Link](180,240,50,40);
[Link](250,240,50,40);
[Link](40,310,50,40);
[Link](110,310,50,40);
[Link](180,310,50,40);
[Link](250,310,50,40);
[Link](60,380,100,40);
[Link](180,380,100,40);
[Link](t);
[Link](b7);
[Link](b8);
[Link](b9);
[Link](bdiv);
[Link](b4);
[Link](b5);
[Link](b6);
[Link](bmul);
[Link](b1);
[Link](b2);
[Link](b3);
[Link](bsub);
[Link](bdec);
[Link](b0);
[Link](beq);
[Link](badd);
[Link](bdel);
[Link](bclr);
[Link](null);
[Link](true);
[Link](350,500);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](false);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent e)


{
if([Link]()==b1)
[Link]([Link]().concat("1"));
if([Link]()==b2)
[Link]([Link]().concat("2"));
if([Link]()==b3)
[Link]([Link]().concat("3"));
if([Link]()==b4)
[Link]([Link]().concat("4"));
if([Link]()==b5)
[Link]([Link]().concat("5"));
if([Link]()==b6)
[Link]([Link]().concat("6"));
if([Link]()==b7)
[Link]([Link]().concat("7"));
if([Link]()==b8)
[Link]([Link]().concat("8"));
if([Link]()==b9)
[Link]([Link]().concat("9"));
if([Link]()==b0)
[Link]([Link]().concat("0"));
if([Link]()==bdec)
[Link]([Link]().concat("."));
if([Link]()==badd)
{
a=[Link]([Link]());
operator=1;
[Link]("");
}
if([Link]()==bsub)
{
a=[Link]([Link]());
operator=2;
[Link]("");
}
if([Link]()==bmul)
{
a=[Link]([Link]());
operator=3;
[Link]("");
}
if([Link]()==bdiv)
{
a=[Link]([Link]());
operator=4;
[Link]("");
}
if([Link]()==beq)
{
b=[Link]([Link]());
switch(operator)
{
case 1: result=a+b;
break;
case 2: result=a-b;
break;
case 3: result=a*b;
break;
case 4: result=a/b;
break;
default: result=0;
}
[Link](""+result);
}
if([Link]()==bclr)
[Link]("");
if([Link]()==bdel)
{
String s=[Link]();
[Link]("");
for(int i=0;i<[Link]()-1;i++)
[Link]([Link]()+[Link](i));
}
}
public static void main(String...s)
{
new Calc();
}
}
Output:

2) Write a JAVA program to display the digital watch in swing tutorial.


Program:

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class DigitalWatch implements Runnable{
JFrame f;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch(){
f=new JFrame();
t = new Thread(this);
[Link]();
b=new JButton();
[Link](100,100,100,50);
[Link](b);
[Link](300,400);
[Link](null);
[Link](true);
}
public void run() {
try {
while (true) {
Calendar cal = [Link]();
hours = [Link]( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = [Link]( [Link] );
seconds = [Link]( [Link] );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = [Link]();
timeString = [Link]( date );
printTime();
[Link]( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
public void printTime(){
[Link](timeString);
}
public static void main(String[] args) {
new DigitalWatch();
}
}
Output:
Exercise – 13 (Swings - Continued)
1. Write a JAVA program that to create a single ball bouncing inside a JPanel
Program:

import [Link].*;
import [Link].*;

public class BouncingBall extends JPanel {

// Box height and width


int width;
int height;

// Ball Size
float radius = 40;
float diameter = radius * 2;

// Center of Call
float X = radius + 50;
float Y = radius + 20;

// Direction
float dx = 3;
float dy = 3;

public BouncingBall() {

Thread thread = new Thread() {


public void run() {
while (true) {

width = getWidth();
height = getHeight();

X = X + dx ;
Y = Y + dy;

if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > width) {
dx = -dx;
X = width - radius;
}

if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > height) {
dy = -dy;
Y = height - radius;
}
repaint();

try {
[Link](50);
} catch (InterruptedException ex) {
}

}
}
};
[Link]();
}

public void paintComponent(Graphics g) {


[Link](g);
[Link]([Link]);
[Link]((int)(X-radius), (int)(Y-radius), (int)diameter, (int)diameter);
}

public static void main(String[] args) {


[Link](true);
JFrame frame = new JFrame("Bouncing Ball");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);
[Link](new BouncingBall());
[Link](true);
}
}
Output:
[Link] a JAVA program JTree as displaying a real tree upside down
Program:

import [Link].*;
import [Link];
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
[Link](color);
[Link](font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
[Link](red); [Link](blue); [Link](black); [Link](green);
JTree jt=new JTree(style);
[Link](jt);
[Link](200,200);
[Link](true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:

You might also like