Department of Cse: Java Programming Lab
Department of Cse: Java Programming Lab
R20
1 Exercise - 1 (Basics)
a). Write a JAVA program to display default value of all primitive data type of JAVA.
b). Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate
thediscriminate D and basing on value of D, describe the nature of root.
c). Five Bikers Compete in a race such that they drive at a constant speed which may or may
not be the same as the other. To qualify the race, the speed of a racer must be more than the
average speed of all 5 racers. Take as input the speed of each racer and print back the speed of
qualifying racers.
d) Write a case study on public static void main(250 words)
b). Write a Case study on run time polymorphism, inheritance that implements in above
problem
9 Exercise – 9 (User defined Exception)
a). Write a JAVA program for creation of Illustrating throw
b). Write a JAVA program for creation of Illustrating finally
c). Write a JAVA program for creation of Java Built-in Exceptions
d).Write a JAVA program for creation of User Defined Exception
10 Exercise – 10 (Threads)
a). Write 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)
b). Write a program illustrating isAlive and join ()
c). Write a Program illustrating Daemon Threads.
11 Exercise - 11 (Threads continuity)
a).Write a JAVA program Producer Consumer Problem
b).Write a case study on thread Synchronization after solving the above producer consumer
problem
12 Exercise – 12 (Packages)
a). Write a JAVA program illustrate class path
b). Write a case study on including in class path in your os environment of your package.
c). Write a JAVA program that import and use the defined your package in the previous
Problem
13 Exercise - 13 (Applet)
a).Write a JAVA program to paint like paint brush in applet.
b) Write a JAVA program to display analog clock using Applet.
c). Write a JAVA program to create different shapes and fill colors using Applet.
14 Exercise - 14 (Event Handling)
a).Write a JAVA program that display the x and y position of the cursor movement using
Mouse.
b).Write a JAVA program that identifies key-up key-down event user entering text in a
Applet.
15 Exercise - 15 (Swings)
a).Write a JAVA programto build a Calculator in Swings
b). Write a JAVA program to display the digital watch in swing tutorial
16 Exercise – 16 (Swings - Continued)
a). Write a JAVA program that to create a single ball bouncing inside a JPanel.
b). Write a JAVA program JTree as displaying a real tree upside down.
The programs 1.d), 15, 16 are intended to enhance the student skills which are not
included in JNTU Kakinada curriculum.
1) Write a JAVA Program to display default value of all primitive data types of
JAVA
Aim: Displaying default value of all primitive data types of JAVA
Description:
Primitive Data Types: The Java programming language is statically-typed, which
means that all variables must first be declared before they can be used.
The eight primitive data types supported by the Java programming language are:
Data Type Default Value (for fields)
Byte 0
Short 0
Int 0
Long 0L
Float 0.0f
Double 0.0d
Char '\u0000'
String (or any object) null
Boolean false
Program:
class DefaultValues
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
Output:
Program:
import java.io.*;
class Quadratic
double x1,x2,disc,a,b,c;
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
x1=x2=-b/(2*a);
else if(disc>0)
x1=(-b+Math.sqrt(disc))/(2*a); x2=(-
b+Math.sqrt(disc))/(2*a);
else
Output:
3) Five Bikers Compete in a race such that they drive at a constant speed which may
or may not be the same as the other. To qualify the race, the speed of a racer must be
more than the average speed of all 5 racers. Take as input the speed of each racer
and print back the speed of qualifying racers.
Aim: Displaying the speed of qualifying racers.
Description:
Calculate the average speed of all the racers and identify the speed of qualifying racers.
Speed=distance X time
Program:
import java.io.*;
import java.util.*;
class Race1
{
public static void main(String args[]) throws IOException
{
int i;
int flag=0 ;
float avg = 0.0f;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the speed of five racers"); int
a[]=new int[5];
for(i=0;i<5;i++)
{
a[i]=Integer.parseInt(dis.readLine());
avg += a[i];
}
System.out.println(" the speeds of five racers are follows");
for(i=0;i<5;i++)
{
System.out.println("The speed of racer" +(i+1)+ "is "+a[i]);
}
for(i=0;i<4;i++)
{
if(a[i] != a[i+1])
{
flag=1;
break;
}
}
if(flag!=0)
{
avg=avg/5.0f;
System.out.println("average is"+avg);
for(i=0;i<5;i++)
{
if(a[i]>avg)
{
System.out.println("The winner of the racer is player
"+(i+1));
}
}
else
Output:
Explanation:
Public static void main(String args[]) { }
The main part of the statement is the method. That is, it is the block of code that is actually
going to display our output. Therefore, it needs to be included within a class. Even though
this is the main method, it may be hard to notice since the keyword is buried in the other
keywords.Each and every keyword present in this method must be known.
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
Public
The first word in the statement, public, means that any object can use the main method.
The first word could also be static, but public static is the standard way. Still, public
means that it is truly the main method of the program and the means by which all other
code will be used in the program.
Static
Even though you could write static public or public static, the program will work just fine.
Still, it's more common to use public static. In the context of Java, the static keyword
means that the main method is a class method. What this also means is that you can
access this method without having an instance of the class (Remember that the public
keywords makes the method accessible by all classes, so this makes it possible.)
Void : is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a
starting point for an application with a particular signature only.
1) What is a method?
2) What is the prototype of a method?
3) Prototype of a class
4) What is the default input type of Java?
5) What does void mean?
6) Differentiate between Top-Down approach and Bottom-up approach.
7) What is access modifier?
8) Is public static void main(int k) valid?give reason.
else
{
h=m-1;
}
m=(l+h)/2;
}
if(l>h)
System.out.println("key not found");
}
}
Output:
Program:
import java.io.*;
class Sort
{
public static void main(String args[]) throws IOException
{
int i,j,n,temp;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter n:");
n=Integer.parseInt(dis.readLine()); int a[]=new int[n];
Output:
Description:
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves,
calls itself for the two halves and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is key process that
assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays
into one.
Program:
import java.util.Scanner;
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);
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[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
Output:
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as
length.
Important methods of StringBuffer class
public synchronized StringBuffer delete(int startIndex,int endIndex) is used to delete
the string from specified
startIndex and endIndex.
public char charAt(int index) is used to return the character at the
specified position.
Program:
Import java.io.*;
public class JavaStringBufferDeleteExample {
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:
Program:
import java.io.*;
class Area
{
double a;
public double area(double r)
{
a=3.14*r*r;
return a;
}
}
class Circle
{
public static void main(String args[]) throws IOException
{
Area ob=new Area();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter radius of a circle"); double
r=Integer.parseInt(dis.readLine());
double ar=ob.area(r);
System.out.println("Area of a circle is:"+ar);
}
}
Output:
Name of the constructor must be same as that of a class name. If you give another
name it will give compile time error. If you give another name, it is neither a method
because of no return type, nor constructor because name is different from class name.
Program:
import java.io.*;
class A
{
A(int a,int b)
{
int c;
c=a*b;
System.out.println("the c value is"+c);
}
}
class B
{
public static void main(String args[]) throws IOException
{
A ob=new A(10,20);
}
}
Output:
Name of the constructor must be same as that of a class name. If you give another
name it will give compile time error. If you give another name, it is neither a method because
of no return type, nor constructor because name is different from class name.
Program:
import java.io.*;
class A
{
A(int a)
{
System.out.println("The area of a square is:"+a*a);
}
A(int a,int b)
{
super();
System.out.println("The area of a rectangle is"+a*b);
}
A(int a,int b,int c)
{
super();
System.out.println("The volume of a cuboid is "+a*b*c);
}
}
class B
{
public static void main(String args[]) throws IOException
{
A ob=new A(10);
A ob1=new A(10,2);
A ob2=new A(10,2,50);
}
}
Output:
If a class have multiple methods by same name but different parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Program:
class Overload
double demo(double a) {
return a*a;
class MethodOverloading
double result;
Obj .demo(10);
Output:
Program:
Import java.io.*;
public class Inherit_Single {
Inherit_Single() {
SubClass() {
void display()
{
System.out.println(str);
}
}
class MainClass {
obj.display();
}
}
Output:
Program:
import java.io.*;
class Inherit
Output:
15) Write a java program for abstract class to find areas of different shapes
Aim:A Java program for abstract class to find areas of different shapes.
Description:
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't know
the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
Example
abstract class A{}
Program:
import java.io.*;
abstract class Area
{
abstract void square(int s);
abstract void rect(int l,int b);
abstract void circle(int r);
abstract void triangle(int b,int h);
}
class A extends Area
{
void square(int s)
{
System.out.println("Area of square is"+s*s);
}
void rect(int l,int b)
{
System.out.println("Area of rectangle is"+l*b);
}
void circle(int r)
{
System.out.println("Area of circle is"+(3.14*r*r));
}
void triangle(int b,int h)
{
System.out.println("Area of triangle is"+(0.5*b*h));
}
}
class AbstractDemo
{
public static void main(String args[]) throws IOException
{
A a1=new A();
a1.square(10);
a1.rect(10,2);
a1.circle(3);
a1.triangle(2,5);
}
}
Output:
Program:
class A
{
int i, j;
A()
{
i = 0;
j = 0;
}
A(int a, int b)
{
i = a;
j=b;
}
void show()
{
System.out.println ("i and j : "+ i +" " + j);
}
}
class B extends A
{
int k;
B()
{
super();
k = 0;
}
B(int a, int b, int c)
{
super(a, b);
k =c;
}
void show()
{
super.show();
System.out.println("k:" + k);
}
}
class SuperKeyword
{
public static void main ( String args[])
{
B subob = new B( 1, 2, 3 );
subob.show();
}
}
Output:
17) Write a JAVA program to implement Interface. What kind of Inheritance can
be achieved?
Aim: implementing interface and using this achieving multiple inheritance.
Description:
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface. Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types.
Program:
class Number
{
protected int x;
protected int y;
}
interface Arithmetic
{
int add(int a, int b);
int sub(int a, int b);
}
class UseInterface extends Number implements Arithmetic
{
public int add(int a, int b)
{
return(a + b);
}
public int sub(int a, int b)
{
return (a - b);
}
public static void main(String args[])
{
UseInterface ui = new UseInterface();
System.out.println("Addition --- >" + ui.add(2,3));
System.out.println("Subtraction------>" +
ui.sub(2,1)); }
}
Output:
1) what is interface?
2) What is the keyword used to inherit an interface?
3) What is the default access of variable and method in an interface
4) What is final in java language?
5) Using interface concept what type of inheritance is achieved
6) Does interface contain concrete methods?
Program:
Import java.io.*;
public class ExcepTest{
Output:
Program:
public class ExceptionExample {
try {
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
//arr[5] = 5;
}catch (ArithmeticException e)
{ System.out.println("Err: Divided by
Zero");
}catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Err: Array Out of
Bound");
}
}
}
Output:
Program:
import java.io.*;
class Override
{
public void methodoverride()
{
System.out.println("This is base class Method");
}
}
class Overridederived extends Override
{
public void methodoverride()
{
System.out.println("This is Derived class Method");
}
}
public class Methodoverride
{
public static void main(String args[]) throws IOException
{
Override ob=new Override();
Override ob1=new Overridederived();
ob.methodoverride();
ob1.methodoverride();
}
}
Output:
21) Write a Case study on run time polymorphism, inheritance that implements in
above problem
Aim: case study on RunTime Polymorphism
Explanation
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the type
of the object being referred to at the time the call occurs. Thus, this determination is made
at run time.
At run-time, it depends on the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Program:
class NoBalanceException extends Exception
{
public NoBalanceException(String problem)
{
super(problem);
}
}
class YesBank
{
public static void main( String args[ ] ) throws
NoBalanceException {
int balance = 100, withdraw = 1000;
if (balance < withdraw)
{
NoBalanceException e = new NoBalanceException("No balance please");
throw e;
}
else
{
System.out.println("Draw & enjoy, Best wishes of the day");
}
}
}
Output:
Program:
Output:
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");
}
}
}
Output:
Program:
import java.io.*;
class MyException extends Exception
{
private int a;
MyException(int b)
{
a = b;
}
public String toString()
{
return "MyException [ " + a + "]";
}
}
class Userdefexception
{
public int x;
final int k = 5;
void getInt()
{
try {
BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
System.out.println("do some guess work to generate your own exception ");
System.out.println("enter a number between 1 and 10");
System.out.println("between these numbers lies the number to generate your own
exception ");
String line;
while((line = d.readLine()) != null)
{
x = Integer.parseInt(line);
if ( x == 5)
{
System.out.println(" congrats ! you have generated an exception !");
throw new MyException(x);
}
else
System.out.println("Wrong guess ! try again");
continue;
}
}
catch(MyException m)
{ System.out.println("Generated exception: " +m);
}
catch(NumberFormatException n)
{
System.out.println("sorry ! no characters");
System.out.println("Exiting ...");
System.out.println("generated Exception:"+n);
}
catch(IOException e) { }
}
public static void main(String a[])
{ UserdefException u = new
UserdefException();
u.getInt();
}
}
Output:
26) Write 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:
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class ThreadDemo1
{
public static void main(String args[])
{
GoodMorning a1=new GoodMorning();
Hello b1=new Hello();
Welcome c1=new Welcome();
a1.start();
b1.start();
c1.start();
}
}
class GoodMorning implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class ThreadDemo
{
public static void main(String args[])
{
GoodMorning a1=new GoodMorning();
Hello b1=new Hello();
Welcome c1=new Welcome();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Output:
Program:
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
try {
t1.join(); // Waiting for c1 to finish
}
catch (InterruptedException ie)
{
}
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output:
Program:
public class DaemonThreadExample1 extends Thread{
Output:
Program:
class A
{
int n;
boolean b=false;
synchronized int get()
{
if(!b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n);
b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n;
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
A a1; Thread
t1; producer(A
a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class consumer implements Runnable
{
A a1; Thread t1;
consumer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class ProducerConsumer
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}
Output:
30) Write a case study on thread Synchronization after solving the above
producer consumer problem
Aim: case study on thread Syncronisation after giving solution to the
producer consumer problem.
In computing, the producer–consumer problem (also known as the bounded-buffer
problem) is a classic example of a multi-process synchronization problem. The problem
describes two processes, the producer and the consumer, which share a common, fixed-
size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be
empty. The next time the producer puts data into the buffer, it wakes up the sleeping
consumer. An inadequate solution could result in a deadlock where both processes are
waiting to be awakened.
sleep() at the end of both methods just make the output of program run in step wise
manner and not display everything all at once so that you can see what actually is
happening in the program.
package pack:
public class A
{
public int c;
public int add(int a,int b)
{
c=a+b;
return c;
}
public int subtract(int a,int b)
{
c=a-b;
return c;
}
}
1)What is JDK?
2)What is JVM?
3)What is JRE?
4)How to set classpath using command prompt?
32) Write a case study on including in class path in your os environment of your
package.
Aim: Illustrating the setup of classpath in operating system.
Program:
CLASSPATH is actually an environment variable in Java, and tells Java applications and
the Java Virtual Machine (JVM) where to find the libraries of classes. These include any
that you have developed on your own.
An environment variable is a global system variable, accessible by the computer's
operating system (e.g., Windows). Other variables include COMPUTERNAME,
USERNAME (computer's name and user name).
In Java, CLASSPATH holds the list of Java class file directories, and the JAR file, which
is Java's delivered class library file.
If you are trying to run a stand-alone Java program, you may find it necessary to change
the CLASSPATH variable. When the program runs, Java's run-time system, called the
interpreter, is working through your code. If it comes across a class name, it will look at
each directory listed in the CLASSPATH variable. If it does not find the class name, it will
error out.
We can set the value of CLASSPATH in DOS. The following example changes the
variable to a local folder that we've created called CustomClasses; it's located in a folder
on the C: drive called Java:
33) Write a JAVA program that import and use the defined your package in the
previous Problem.
Aim: use and import package
Program:
import pack.*;
class B
{
public static void main(String artgs[])
{
A a1=new A();
int l=a1.add(2,3);
System.out.println("The addition of two no's is : "+l);
l=a1.subtact(10,4);
System.out.println("The subtraction of two no's is : "+l);
}
}
Output:
The addition of two no's is : 5
The subtraction of two no's is : 6
Sample viva questions:
1) What is a package?
2) what is Abstraction of Data?
3)how to use a package?
4)can we create a package and use it in our programs?
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html> */
public class MouseDrag extends Applet implements MouseMotionListener{
Program:
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/*<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html> */
public class MyClock extends Applet implements Runnable {
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
Output:
36) Write a JAVA program to create different shapes and fill colors using Applet.
Aim: A JAVA program to create different shapes and fill colors using Applet.
Program:
import java.applet.*;
import java.awt.*;
/*
<applet code="ShapColor.class" width="500" height="400">
</applet>
*/
public class ShapColor extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.setColor(Color.red); //Drawing line color is red
g.drawLine(3,300,200,10);
g.setColor(Color.magenta);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.setColor(Color.yellow); //Fill the yellow color in circle
g.fillOval( x-r,y-r, 100, 100 );
g.setColor(Color.magenta);
g.drawString("Circle",275,100);
g.drawRect(400,50,200,100);
g.setColor(Color.yellow); //Fill the yellow color in rectangel
g.fillRect( 400, 50, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangel",450,100);
}
Output:
37) Write a JAVA program that display the x and y position of the cursor movement
using Mouse.
Aim: A JAVA program that display the x and y position of the cursor
movement using Mouse.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code="AppletMouseXY.class" width="500" height="500">
</applet>
*/
public class AppletMouseXY extends Applet implements MouseListener,
MouseMotionListener
{
int x, y;
String str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// override ML 5 abstract methods
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Released";
repaint();
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Clicked";
repaint();
}
Output
38) Write a JAVA program that identifies key-up key-down event user entering text
in a Applet.
Aim: A JAVA program that identifies key-up key-down event user entering text in
a Applet.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
Swings
Program:
import javax.swing.*;
import java.awt.event.*;
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;
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);
PREPARED BY R.V.V.G.LAKSHMI, ASSISTANT PROFESSOR, CSE 94
Department of Information Technology Java Programming Lab
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);
}
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));
}
}
Output:
40) Write a JAVA program to display the digital watch in swing tutorial.
Aim: A JAVA program to display the digital watch in swing tutorial.
Program:
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);
}
printTime();
}
}
Output:
41) Write a JAVA program that to create a single ball bouncing inside a JPanel
Aim: A JAVA program that to create a single ball bouncing inside a JPanel
Program:
import java.awt.*;
import javax.swing.*;
// Ball Size
float radius = 40;
float diameter = radius * 2;
// Direction
float dx = 3;
float dy = 3;
public BouncingBall() {
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 {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
};
thread.start();
}
Output:
42) Write a JAVA program JTree as displaying a real tree upside down.
Program:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample { JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output: