JAVA LAB PROGRAMS r19 19
JAVA LAB PROGRAMS r19 19
AND SCIENCES,
VISAKHAPATNAM.
JAVA PROGRAMMING
R19 & R20
LAB MANUAL
1(a) write a java program to display default values of all primitive data types?
Program:
class Defaultvalues
{
public static void main(String[] args)
{
byte b =100;
short s =123;
int v = 123543;
int calc = -9876345;
long amountVal = 1234567891;
float intrestRate = 12.25f;
double sineVal = 12345.234d;
boolean flag = true;
boolean val = false;
char ch1 = 88; // code for X
char ch2 = 'Y';
System.out.println("byte Value = "+ b);
System.out.println("short Value = "+ s);
System.out.println("int Value = "+ v);
System.out.println("int second Value = "+ calc);
System.out.println("long Value = "+ amountVal);
System.out.println("float Value = "+ intrestRate);
System.out.println("double Value = "+ sineVal);
System.out.println("boolean Value = "+ flag);
System.out.println("boolean Value = "+ val);
System.out.println("char Value = "+ ch1);
System.out.println("char Value = "+ ch2);
}
}
Output:
1(b) write java program that display roots of quadratic equation ax2+bx+c=0.calculate the
discriminate D and basing
Program:
import java.util.Scanner;
class solutions
{
public static void main(String args[])
{
int a,b,c;
double x,y;
Scanner s=new Scanner(System.in);
System.out.println("enter the values of a,b,c");
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
int k=(b*b)-4*a*c;
if(k<0)
{
System.out.println("no real roots");
}
else
{
double l=Math.sqrt(k);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
System.out.println("roots of given equation:"+x+y);
}
}
}
Output:
1(c) Five bikers complete in race such that they drive in constant speed which may or may
not be same as other to qualify race the speed of racer must be more than average speed of all
5 racers .take as input the speed of each racer and print back speed of qualifying racers?
Program:
import java.util.Scanner;
class BIKE
{
public static void main(String args[])
{
int a,b,c,d,e;
double avg;
Scanner S=new Scanner(System.in);
System.out.println("enter A BIKE SPEED");
a=S.nextInt();
System.out.println("enter B BIKE SPEED");
b=S.nextInt();
System.out.println("enter C BIKE SPEED");
c=S.nextInt();
System.out.println("enter D BIKE SPEED");
d=S.nextInt();
System.out.println("enter E BIKE SPEED");
e=S.nextInt();
avg=(a+b+c+d+e)/5;
System.out.println("avg"+avg);
if(avg<a)
{
System.out.println("A is qualify"+a);
}
else
{
System.out.println("A is not qualify"+a);
}
if(avg<b)
{
System.out.println("B is qualify"+b);
}
else
{
System.out.println("B is not qualify"+b);
}
if(avg<c)
{
System.out.println("C is qualify"+c);
}
else
{
System.out.println("C is not qualify"+c);
}
if(avg<d)
{
System.out.println("D is qualify"+d);
}
else
{
System.out.println("D is not qualify"+d);
}
if(avg<e)
{
System.out.println("E is qualify"+e);
}
else
{
System.out.println("E is not qualify"+e);
}
}
}
Output:
1(d) Write a case study on public static void main(250 words)?
<code class=”language_css”>class SBT
{
Public static void main(String args[])
{
System.out.println(“hello SBT”);
}
}
</code>
Public: it is an access modifier,which defines who can access this method.public means that it
can accessible by any class.
Static: it is keyword which identifies the class related thing.this means the given method (or)
variable is not instance related but class related.it can be associated without creating instance
of class.
Void: it is used to define the returntype of the metthod.it defines what the method can
return,void means the method will not return any value.
Main: it is the name of method.this method is searched by JVM as starting point for an
application with a particular sinature only .
String args[]: parameters to main method.
OPERATIONS EXPRESSIONS CONTROL FLOW STRINGS
2(A) Write a java program to search element in given llist of element using binary search?
Program:
import java.util.Scanner;
class Binarysearch
{
public static void main(String args[])
{
int n, i, search, first, last, middle;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Total Number of Elements : ");
n = scan.nextInt();
System.out.print("Enter " +n+ " Elements : ");
for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Enter a Number to Search..");
search = scan.nextInt();
first = 0;
last = n-1;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle] < search)
{
first = middle+1;
}
else if(arr[middle] == search)
{
System.out.print(search+ " Found at Location " +middle);
break;
}
else
{
last = middle - 1;
}
middle = (first+last)/2;
}a
if(first > last)
{
System.out.print("Not Found..!! " +search+ " is not Present in the List.");
}
}
}
Output:
2(b) Write java program to sort for an element in given list of elements using bubble sort?
Program:
import java.util.Scanner;
class BUBBLESORT
{
public static void main(String args[])
{
int n,i,j,swap;
int a[]=new int[50];
Scanner s=new Scanner(System.in);
System.out.println("enter size of array");
n=s.nextInt();
System.out.println("enter array of elements");
for(i=0;i<n;i++)
{
a[i]=s.nextInt();
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j-1]>a[j])
{
swap=a[j-1];
a[j-1]=a[j];
a[j]=swap;
}
}
}
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Output:
2(c) Write java program to sort for an element in given list of elements using merge sort?
Program:
public class Mergesort
{
public static void sort(int a[],int low,int high)
{
int N=high-low;
if(N<=1)
return;
int mid=low+N/2;
sort(a,low,mid);
sort(a,mid,high);import java.util.Scanner;
int[] temp=new int[N];
int i=low,j=mid;
for(int k=0;k<N;k++)
{
if(i==mid)
temp[k]=a[j++];
else if(j==high)
temp[k]=a[i++];
else if(a[j]<a[i])
temp[k]=a[j++];
else
temp[k]=a[j++];
}
for(int k=0;k<N;k++)
a[low +k]=temp[k];
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Merge sort test\n");
int n,i;
System.out.println("enter number of integer elements");
n=s.nextInt();
int arr[]=new int[n];
System.out.println("\n enter "+n+"integer elements");
for(i=0;i<n;i++)
arr[i]=s.nextInt();
sort(arr,0,n);
System.out.println("\n elements after sorting");
for(i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
Output:
2(d) Write a java program using string buffer to delete remove character?
Program:
public class Deleteex
{
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer("hello world");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2=new StringBuffer("some content");
System.out.println(sb2);
sb2.delete(0,sb2.length());
System.out.println(sb2);
StringBuffer sb3=new StringBuffer("hello world");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
Output:
3(a) Write a java program to implement class mechanism create class methods and invoke
them inside main method?
Program:
class student
{
int x;
floay y;
{
Void setdata("int rollno;float percentage")
x=rollno;
y=percentage;
}
Void getdata()
{
System.out.println("studentinfo");
System.out.println("Rollno:"+x,"percentage:"+y);
}
}
public class studentinfo
{
public static void mian(String args[])
{
student s=new student();
s.setdata(18,70.86f);
s.getdata();
}
}
Output:
3(b) Write java program to implement constructor?
Program:
class Student3
{
int id;
String name;
void display(){System.out.println(id+" "+name);.
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output :
4(a) Write a java program to implement constructor overloading?
Program:
class Box
{
double width,height,depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
Box(double len)
{
width=height=depth=len;
}
double volume()
{
return width*height*depth;
}
}
class overloadcons
{
public static void main(String args[])
{
Box mybox1=new Box(10,20,15);
Box mybox2=new Box();
Box mycube=new Box(7);
double vol;
vol=mybox1.volume();
System.out.println("volume of mybox is"+vol);
vol=mybox2.volume();
System.out.println("volume of mybox2:"+vol);
vol=mycube.volume();
System.out.println("volume of mycube is:"+vol);
}
}
Output:
4(b) Write java program to implement method overloading?
Program:
class overloaddemo
{
void test()
{
System.out.println("no parameters");
}
void test(int a)
{
System.out.println("a:"+a);
}
void test(int a,int b)
{
System.out.println("a and b:"+a+b);
}
double test(double a)
{
System.out.println("double a:"+a);
return a*a;
}
}
class overload
{
public static void main(String args[])
{
overloaddemo ob=new overloaddemo();
double result;
ob.test();
ob.test(10,20);
result=ob.test(123.45);
System.out.println("result of ob.test(123.45):"+result);
}
}
Output:
5(a) Write a java program to implement single inheritance?
Program:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
5(b) Write java program to implement multiple inheritance ?
Program:
class Car
{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
5(c) Write java program for abstract class to find areas in different shapes?
Program:
import java.util.Scanner;
abstract class calculateArea
{
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 calculate
{
void findTriangle(double b, double h)
{
double area = (b*h)/2;
System.out.println("Area of Triangle: "+area);
}
void findRectangle(double l, double b)
{
double area = l*b;
System.out.println("Area of Rectangle: "+area);
}
void findSquare(double s)
{
double area = s*s;
System.out.println("Area of Square: "+area);
}
void findCircle(double r)
{
double area = 3.14*r*r;
System.out.println("Area of Circle: "+area);
}
}
class area
{
public static void main(String args[])
{
double l, b, h, r, s;
findArea area = new findArea();
Scanner get = new Scanner(System.in);
System.out.print("\nEnter Base & Vertical Height of Triangle: ");
b = get.nextDouble();
h = get.nextDouble();
area.findTriangle(b, h);
System.out.print("\nEnter Length & Breadth of Rectangle: ");
l = get.nextDouble();
b = get.nextDouble();
area.findRectangle(l, b);
System.out.print("\nEnter Side of a Square: ");
s = get.nextDouble();
area.findSquare(s);
System.out.print("\nEnter Radius of Circle: ");
r = get.nextDouble();
area.findCircle(r);
}
}
Output:
6(a) Write a java program give example of “super” keyword?
Program:
class vehicle
{
int id;
String color;
vehicle(int regno,String color)
{
id=regno;
this.color=color;
}
}
class vchl6a extends vehicle
{
int id;
String color;
vchl6a(int i1,int i2,String s1,String s2)
{
super(i2,s2);
id=i1;
color=s1;
}
void pdata()
{
System.out.println(super.id);
}
void ddata()
{
System.out.println(super.color);
}
public static void main(String args[])
{
vchl6a v=new vchl6a(10,2334,"GREV","WHITE");
System.out.println("vehicle color is");
v.ddata();
System.out.println("\n vehicle number is");
v.pdata();
System.out.println("\n vehicle engine color is"+v.color);
System.out.println("vehicle engine id is"+v.id);
}
}
Output:
6(b) Write java program to implement interface? What kind of interface can be achieved?
Program:
interface MyInterface
{
public void method1();
public void method2();
}
class Demo6b implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String args[])
{
MyInterface obj=new Demo6b();
obj.method1();
obj.method2();
}
}
Output:
7(a) write java program describes exception handling mechanism?
Program:
import java.util.Scanner;
class Division
{
public static void main(String args[])
{
int a,b,result;
Scanner s=new Scanner(System.in);
System.out.println("enter value of two integers");
a=s.nextInt();
b=s.nextInt();
result=a/b;
System.out.println("result="+result);
}
}
Output :
7(b) Write java program to illustrate multiple catch clauses?
Program:
public class TestMultipleCatchBlock
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");
}
catch(Exception e)
{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
Output:
8(a) Write java program implements runtime polymorphism?
Program:
class Bike
{
void run()
{
System.out.println("running");
}
}
class splender extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
public static void main(String args[])
{
Bike b=new splender();
b.run();
}
}
Output :
(b) write case study on runtime polymorphism,inheritance that implements in above problem
Case study:
Method overloading is one of ways in which java supports runtime polymorphism
When an overridden method is called then a super class reference, java determines which
version (superclass/subclass) of that method is to be executed based on the type of object
being referral to all, the time of call occurs
This determination is made at runtime
In java we can override method only not the variables (data members), so runtime
polymorphism cannot be achieved by data members.
(a) Write a java program to illustrate throw
import java.io.IOException;
class Testthrows1{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}catch(Exception e){System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
b write a java program to illustrate finally
Program:
class FinallyBlockDemo
{
publicstaticvoid main(String[] args)
{
int a=45,b=0,rs=0;
try
{
rs = a / b;
}
catch(ArithmeticException Ex)
{
System.out.print("\n\tError : " + Ex.getMessage());
}
finally
{
System.out.print("\n\tThe result is : " + rs);
}
}
}
output:
Error : / by zero
The result is : 0
(c)Write a java program for creation of built in exception?
Program:
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e)
{
System.out.println("Can't divide a number by 0");
}
}
}
(d) write a java program for creation of user defined exception?
Program:
class JavaException
{
public static void main(String args[])
{
Try
{
throw new MyException(2);
}
catch(MyException e)
{
System.out.println(e) ;
}
}
}
class MyException extends Exception
{
int a;
MyException(int b)
{
a=b;
}
public String toString()
{
return ("Exception Number = "+a) ;
}
}
10 (a)write a java program that creates threads by extending thread class first thread display
“Good morning” every 1sec
Second thread display “Hello” every 2sec third thread display
“Welcome” every 3rd sec (repeat same by implementing runnable)
Program:
Output:
E:\javamani>java ThreadDemo
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
hello
welcome
good morning
b)write a java program to illustrate isAlive and join methods?
isAlive():
class isAliveAndJoin1 implements Runnable
{
thread t;
isAliveAndJoin1(String n)
{
t=new Thread(this,n);
System.out.println("Thread is :"+t);
}
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t.getName()+":"+i);
t.sleep(200);
}
}
catch(InterruptedException e)
{
System.out.println(t.getName()+" is Interrupted");
}
}
}
class isAliveAndJoin2 implements Runnable
{
Thread t;
isAliveAndJoin2(String n)
{
t=new Thread(this,n);
System.out.println("Thread is :"+t);
}
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
System.out.println(t.getName()+":"+i);
t.sleep(200);
}
}
catch(InterruptedException e)
{
system.out.println(t.getName()+" is Interrupted");
}
}
}
class isAliveAndJoin
{
public static void main(String args[])
{
isAliveAndJoin1 k1=new isAliveAndJoin1("AWT Thread");
isAliveAndJoin2 k2=new isAliveAndJoin2("Swing Thread");
k1.t.start();
k2.t.start();
while(k1.t.isAlive() && k2.t.isAlive())
{
try
{
thread.sleep(400);
}
catch(e)
{
}
try
{
k1.t.join();
k2.t.join();
}
catch(InterruptedException e)
{
}
}
if(!k1.t.isAlive())
System.out.println("AWT Thread is Over");
if(!k2.t.isAlive())
System.out.println("Swing Thread is Over");
}
OUTPUT:
JOIN():
publicclassJoinExample2
{
publicstaticvoid main(String[] args)
{
Thread th1 = newThread(newMyClass2(), "th1");
Thread th2 = newThread(newMyClass2(), "th2");
th1.start();
th2.start();
}
}
classMyClass2implementsRunnable
{
publicvoid run()
{
Thread t = Thread.currentThread();
System.out.println("Thread started: "+t.getName());
try
{
Thread.sleep(4000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("Thread ended: "+t.getName());
}
}
OUTPUT:
Thread started: th1
Thread started: th3
Thread started: th2
Thread ended: th1
Thread ended: th3
Thread ended: th2
.
(d)write java program to illustrate daemon threads?
Program:
public class TestDaemonThread1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:
11 (a)write a java program producer consumer problem?
Program:
public class ProducerConsumerTest
p1.start();
c1.start();
class CubbyHole
try
wait();
catch (InterruptedException e) {}
available = false;
notifyAll();
return contents;
}
try
wait();
catch (InterruptedException e) { }
contents = value;
available = true;
notifyAll();
cubbyhole = c;
this.number = number;
int value = 0;
value = cubbyhole.get();
cubbyhole = c;
this.number = number;
cubbyhole.put(i);
try
sleep((int)(Math.random() * 100));
catch (InterruptedException e) { }
Output:
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
(b)write a case study on thread synchronisation after solving producer consumer problem?
1. When more than one thread try to access a shared resource we need to ensure that
resource will be used by only one thread at a time.
4. If we do not use synchronisation $let two (or) more threads access a shared resume at
same time,it will lead to distorted results.
12 (a)write a java program to illustrate class path?
Program:
import java.lang.*
class StaticImportDemo
{
public static void main(String args[])
{
System. out.println("welcome");
}
}
Output:
Welcome
(b)write a java program that import and use the defined your package in previous problem?
Program:
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
(C)write a case study on class path
The class path accepts directories and jar files path entries are separated by semi colon(;)
When you can set class path permanently via
Control panel->system->(vista 7/8).advanced system settings ->switch to advanced tab-
>environment variables->choose system variables(for all users) or user variables.
To modify the existing class path,select variable (“CLASS PATH” and choose “EDIT”-> in
variable value provided directories and jar files separated by semi colon(;).
13 (A)Write a java program to paint like paint brush in applet?
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
(b) write a java program to display analog clock using applet?
Program:
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
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( Color.black );
}
public void start() {
if ( t == null ) {
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}
public void stop() {
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
// Now the thread checks to see if it should suspend itself
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
void drawHand( double angle, int radius, Graphics g ) {
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
}
void drawWedge( double angle, int radius, Graphics g )
{
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}
public void paint( Graphics g )
{
g.setColor( Color.gray );
drawWedge( 2*Math.PI * hours / 12, width/5, g );
drawWedge( 2*Math.PI * minutes / 60, width/3, g );
drawHand( 2*Math.PI * seconds / 60, width/2, g );
g.setColor( Color.white );
g.drawString( timeString, 10, height-10 );
}
}
myapplet.html
<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html>
(c) write a java program to create different shapes and fill colors using applets?
Program:
import java.applet.*;
import java.awt.*;
{
g.setColor(new Color(255,255,255));
g.setColor(Color.red);
g.setColor(new Color(80,10,124));
g.setColor(Color.BLUE);
g.fillArc(100, 20, 300, 300, 0, 90); //g.fillArc(x, y, w, h, Starting Angle, Further Angle);
}
/*
*/
Output:
14 (a)Write a JAVA program that display the x and y position of the cursor movement using
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Output:
15 (a)).Write a JAVA programto build a Calculator in Swings
import javax.swing.*;
import java.awt.event.*;
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
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");
t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);
b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);
bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);
bdel.setBounds(60,380,100,40);
bclr.setBounds(180,380,100,40);
f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bdel);
f.add(bclr);
f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}
{
if(e.getSource()==b1)
t.setText(t.getText().concat("1"));
if(e.getSource()==b2)
t.setText(t.getText().concat("2"));
if(e.getSource()==b3)
t.setText(t.getText().concat("3"));
if(e.getSource()==b4)
t.setText(t.getText().concat("4"));
if(e.getSource()==b5)
t.setText(t.getText().concat("5"));
if(e.getSource()==b6)
t.setText(t.getText().concat("6"));
if(e.getSource()==b7)
t.setText(t.getText().concat("7"));
if(e.getSource()==b8)
t.setText(t.getText().concat("8"));
if(e.getSource()==b9)
t.setText(t.getText().concat("9"));
if(e.getSource()==b0)
t.setText(t.getText().concat("0"));
if(e.getSource()==bdec)
t.setText(t.getText().concat("."));
if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}
if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
operator=2;
t.setText("");
}
if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}
if(e.getSource()==bdiv)
{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
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;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
if(e.getSource()==bdel)
{
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()+s.charAt(i));
}
}
public static void main(String...s)
{
new Calc();
}
}
b). Write a JAVA program to display the digital watch in swing tutorial.
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
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);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
printTime();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
public void printTime(){
b.setText(timeString);
}
public static void main(String[] args) {
new DigitalWatch();
}
}
16 (A). Write a JAVA program that to create a single ball bouncing inside a JPane
importjava.awt.*;
importjavax.swing.*;
int width;
int height;
// Ball Size
// Center of Call
// Direction
float dx =3;
float dy =3;
public BouncingBall(){
publicvoid run(){
while(true){
width = getWidth();
height = getHeight();
X = X + dx ;
Y = Y + dy;
dx =-dx;
X = radius;
dx =-dx;
X = width - radius;
dy =-dy;
Y = radius;
dy =-dy;
Y = height - radius;
repaint();
try{
Thread.sleep(50);
}catch(InterruptedException ex){
};
thread.start();
}
super.paintComponent(g);
g.setColor(Color.BLUE);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setContentPane(new BouncingBall());
frame.setVisible(true);
}
(b)). Write a JAVA program JTree as displaying a real tree upside down
package net.codejava.swing;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample extends JFrame
{
private JTree tree;
public TreeExample()
{
//create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
//create the child nodes
DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits");
//add the child nodes to the root node
root.add(vegetableNode);
root.add(fruitNode);
//create the tree by passing in the root node
tree = new JTree(root);
add(tree);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTree Example");
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TreeExample();
}
});
}
}