You are on page 1of 73

DATE: NAME:

REG NO.:

EX 1.A: Program to find the sum of individual digits of a


Positive integer

Aim:
To write a Java program to find the sum of individual digits of a positive
integer.

Algorithm:
1. Start
2. Get the number
3. Declare a variable to store the sum and set it to
4. Repeat the next two step still the number fest
5. Get the rightmost digit of the number with help of the remainder ‘%’
operator by dividing it by10 and adding it to the sum.
6. Divide the number by 10 with the help of ‘/’ operator to remove the
rightmost digit.
7. Print or return the sum
8. Stop

Program:
import java.io.*;
import
java.util.Scanner;
public class ex1
{
public static void main(String Args[ ]) {
Int r,n,sum=0;
Scanner ss=new
Scanner(System.in);
System.out.print("Enter a
number:"); n=ss.nextInt();
while(n>0) { r=n%10; sum=sum+r;
n=n/10;
}
System.out.println("The sum of digits of given number is "+sum);
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program written to find the sum of individual digits of a positive
integer is executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 1.B:Program to generate the first n terms of the sequence.

Aim:
To write a java program to generate the first terms of the sequence.

Algorithm:
1. Start.
2. Get the Number Of Odd Numbers To Be Printed(n).
3. Declare an Integer Variable(i).
4. Set the Value Of i as 1.
5. Repeat the next three steps till is less than or equal to n.
6. If the Numbers Divisible By 2, skip the remaining steps in the current
iteration.
7. If not, print the value.
8. Increment the Value Of By1.
9. Stop.

Program:
import java.util.*; Class
oddNums {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
int i,c=0;
System.out.println("Odd numbers are:");
for(i=1;;i++) { if(i%2 != 0){ c=c+1;
System.out.println(i);} if(c==n)
{
break;}
}
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to generate the first n terms of the sequence is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 1.C: Java program to generate all the prime numbers between


1 and n,where n is a value supplied by the user.

Aim:
To write a java program to generate all the prime numbers between 1 and n,
where n is a value supplied by the user.

Algorithm:
1. start
2. set ct=0,n=0,i=1,j=1
3. repeat step 4 to12 until n<10
4. j=1
5. ct=0
6. repeat step 7 to9 until j<=i
7. if i%j==0 then
8: ct=ct+1
9: j=j+1
10: if ct==2 then print i
11: n =n+1
12: i = i+1
13: end.

Program:
import java.util.*; Class
primeNos {
public static void main(String Args[]) { Scanner
sc = new Scanner(System.in);
Int i,j,n,c;
System.out.println("Enter the number till which you want prime numbers: ");
n=sc.nextInt();
System.out.println("Prime numbers are:");
for(i=2;i<=n;i++) {
c=0;
for(j=1;j<=i;j++) {
if(i%j==0) { c++;
}} if(c==2) {
System.out.print(i+" ");}}}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a java program to generate all the prime numbers between 1 and n,
where is a value supplied by the user is executed successfully and output is
verified.
DATE: NAME:
REG NO.:

EX 1.D: Java program to find both the largest and smallest


number in a list of integers.

Aim:
To write a java program to find both the largest and smallest number in a list
of integers.

Algorithm:
1. Input the Array elements.
2. Initialize small= large=arr[0]
3. Repeat From i= 2 to n
4. if(arr[i]>large)
5. large=arr[i]
6. if(arr[i]<small)
7. small=arr[i]
8. Print small and large.

Program:
Public class smaLarge {
public static void main(String[] args)
{
int numbers[]=new
int[]{15,56,45,6,934,76,98,4321,345,65}; int smallest =
numbers[0]; int biggest=numbers[0];
for(int i=1;i<numbers.length;i++)
{
if(numbers[i]>biggest)
biggest=numbers[i]; else if
(numbers[i] < smallest)
smallest= numbers[i];
}
System.out.println("Largest Number is :+"biggest);
System.out.println("SmallestNumber is :"+smallest);
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a java program to find both the largest and smallest number in a list of
integers is executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 1.E: Java program to find factorial of list of number reading


number input as a command.

Aim:
To write a java program to find factorial of list of number reading Input as
command.

Algorithm:
1. Start
2. Declare Variable n, fact, i
3.Read number from User
4. Initialize Variable fact=1 and i=1
5.Repeat Until i<=number
5.1fact=fact*i
5.2 i=i+1 6.Print
fact
7.Stop.

Program:
class fact{
public static void main(String[] arg){
int[] num=new int[10];
if(arg.length==0)
{
System.out.println("No Command Line argument passed."); return;
}
for(int i=0;i<arg.length;i++) num[i]=Integer.parseInt(arg[i]);
for(int i=0;i<arg.length;i++)
{
Int fact=1;
for(int j=1;j<=num[i];j++)
fact*=j;
System.out.println("The Factorial Of"+arg[i]+" is:"+fact);
}}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a java program to find factorial of list of number reading input as
command is executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 2: Java program to calculate bonuses for different


departments using method overriding.

Aim:
To write a Java program to calculate bonuses for different departments using
method overriding.

Algorithm:
1. START
2. Get Basic Pay
3. Bonus for sales=20%*Basic Pay
4. Bonus for marketing=20%* Basic Pay
5. Bonus for HR=50%*Basic Pay
6. Print Basic Pay ,Bonus for sales ,Bonus for marketing ,Bonus for HR
7. STOP

Program:
import java.util.*;
abstract class dept
{
double bp; dept(double
bpay)
{
bp=bpay;
}
void disp()
{
System.out.println("basic pay="+bp);
}
abstract double bonus();
}
class sales extends dept
{
sales(double bpay)
{
super(bpay); }
public double bonus()
{
return(0.20*bp);
}
}
class marketing extends dept
{
marketing(double bay)
{
super(bpay);
}
public double bonus()
{
return(0.30*bp);
}
}
class hr extends dept
{
hr(double bpay)
{
super(bpay);
}
public double bonus()
{
return(0.50*bp);
}
}
class MethodOverriding
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter basic pay");
double bp=sc.nextdouble();
sales s=new sales(bp);
s.disp();
System.out.println("bonus for sales dept="+s.bonus());
Marketing m=newmarketing(bp);
m.disp();
System.out.println("bonus for marketing
dept="+m.bonus()); hr h=new hr(bp); h.disp();
System.out.println("bonus for hr dept="+h.bonus());
}
}
DATE: NAME:
REG NO.:

Output

Result:
Thus, the Java program to calculate bonus for different departments using
method overriding is executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 3: Java program to sort list of elements in ascending and


descending order and show the exception handling.

Aim:
To write a Java program to sort list of elements ascending and descending
order and show the exception handling.

Algorithm:
1. Start.
2. Get the size of the array and the elements.
3. Using for loops compare the array elements with each other and arrange
them in descending order.
4. Print the Array Elements in Descending Order.
5. Using for loops, compare the array elements with each other and
arrange the min ascending order.
6. Print the Array Elements in Ascending Order.
7. A try-catch block is used to show exception handling.
8. An exception is thrown when an index value greater than the size of the
array is tried to get accessed.
9. Stop.

Program:
import java.util.*; public
class Sorting{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); int i,j;
System.out.println("Enter the size of Array");
int n=sc.nextInt(); int[] arr =new int[n];
int temp=0;
System.out.println("Enter the array elements: "); for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for (i = 0; i< n; i++) {
DATE: NAME:
REG NO.:

for(j= i+1; j<n; j++)


{
if(arr[i] <arr[j]) {
temp=arr[i];
arr[i] = arr[j];
arr[j]=temp;
}}
} System.out.println();
System.out.println("Descending order: ");
for (i = 0; i< n; i++) { Sys-
tem.out.println(arr[i] +" ");
}
temp=0;
for (i = 0; i< n;
i++) { for(j= i+
1;j< n; j++) {if
(arr[i]>arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j]=temp;
}}
} System.out.println();
System.out.println("Ascending order:");
for (i = 0; i< n; i++) {
System.out.println(arr[i] +" ");
}
System.out.println();
try{
System.out.println(arr[n+1]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a Java program to sort a list of elements in ascending and descending
order and to show the exception handling has been executed successfully.
DATE: NAME:
REG NO.:

EX 4: Java program to implement the concept of importing classes


from user defined package and creating packages.

Aim:
To write a program to implement the concept of importing classes from user
defined packages and creating packages.

Algorithm:
1. Start
2. Create a Package namedp1.
3. In p1 package create a class sairam which finds the factorial of a given
number.
4. In a new notepad import the package p1 and create a class packdemo
in which we create an object for Sairam class and getthefactorialof5.
5. Stop.

Program:

NOTEPAD 1: package
p1;
Public class sairam
{
Public int fact(int n)
{
if (n<=1)
return 1;
else
return n*fact(n-1);
}
}
NOTEPAD 2: import
p1.*;
DATE: NAME:
REG NO.:

public class packdemo


{
public static void main(String args[])
{
sairam obj=new sairam();
System.out.println(obj.fact(6));
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a Java program to implement the concept of importing classes from user
defined package and creating packages are successfully verified.
DATE: NAME:
REG NO.:

EX 5A: Java program that illustrate how the following forms of


inheritance supported Single inheritance.
Aim:
To Write a Java Program to illustrate how single inheritance supported.

Algorithm:
1. Start.
2. Create a classA(base class).
3. Declare and initialize variables a and b as 2 and 4 respectively.
4. In classA, create a function fun() which displays the sum of a and b.
5. Create class which inherits class A
6. Inside classB create_function fun1()which Displays the sum of a and b Call
Function Fun() in base class
7. Create a A class ex5a which contains the main function.
8. Create an object obj for class B.
9. Callfun1() using obj.
10. Stop.

Program:
class A
{
int a=5,b=9;
void fun()
{
System.out.println("In base class:\n"+"\tSum="+(a+b));
}
}
class B extends A{ void fun1()
{
System.out.println("In derived class:\n"+"\tSum="+(a+b)); fun();
}
}
DATE: NAME:
REG NO.:

public class ex5a


{
public static void main(String[] args) { B obj=new B();
obj.fun1();
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the Java Program to illustrate how single inheritance is supported is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 5B: Java program that illustrate how the following forms of


inheritance supported Multiple inheritance.

Aim:
To write a Java program to illustrate how multiple inheritance is supported.

Algorithm:
1. Start.
2. Create interface A with function ShowA().
3. Create interface B with function ShowB().
4. Create classC which implements A and B.
5. In classC implement the two functions.
6. Create class ex5b which contains the main function.
7. In the main function create an object obj for class C.
8. Using objc function ShowA() and ShowB().
9. Stop.

Program: interface
A
{
void ShowA();
}
interface B
{
void ShowB();
}
class C implements A,B
{
public void ShowA()
{
System.out.println("ShowA() in interfaceA is implemented");
}
DATE: NAME:
REG NO.:

public void ShowB()


{
System.out.println("ShowB()in interfaceB is implemented");
}
}
public class ex5b
{
public static void main(String[] args) { C obj=new C(); obj.ShowA();
obj.ShowB();
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the Java Program to illustrate how multiple inheritance is supported is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 5C: Java program that illustrate how the following forms of


inheritance supported.

Aim:
To write a Java program to illustrate how multilevel inheritance is supported.

Algorithm:
1. Start
2. Create Class With Function Fun1() that displays “Base class”
3. Create class two which inherits class one and has a function fun2() that
displays “Derived class of base class”
4. Create class three which inherits class two and has a function fun3() that
displays “Derived Class of derived class”
5. Create A class x5c with main function
6. In the main function create object obj1 for class three 7. Using Obj1 Call the
Three Functions 8. Stop.

Program:
class one
{
void fun1()
{
System.out.println("Base class");
}
}
class two extends one{
void fun2()
{
System.out.println("Derived class of base class");
}
}
class three extends two
DATE: NAME:
REG NO.:

{
void fun3()
{
System.out.println("Derived class of derived class");
}
}
public class Main
{
public static void main(String[] args) {
three obj1=new three();
obj1.fun1();
obj1.fun2();
obj1.fun3();
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the Java Program to illustrate how multilevel inheritance is supported is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 5D: Java program that illustrate how the following forms of


inheritance supported Hierarchical Inheritance.

Aim:
To write a Java program to illustrate how hierarchical inheritance supported.

Algorithm:
1. Start
2. Create a classA with function display of that prints “Base class”
3. Create a class B that inherits A with function display1() that displays
”Derived class1”
4. display1() also displays ” Accessing base class function from Derived class 1
“and Calls display()
5. Create a classC that inherits A with function display2() that displays”Derived
class2”
6. Display2() also displays “Accessing base class function from Derived class 2”
and Calls display()
7. Create a class ex5d with main function
8. Inside the main function create objects obj1 and obj2 for classes B and C
respectively
9. Call display1() with obj1 10. Call display2() with obj2 11. Stop.

Program:
class A
{
void display()
{
System.out.println("Base class\n");
}
}
class B extends A
DATE: NAME:
REG NO.:

{
void display1()
{
System.out.println("Derived class1");
System.out.println("\tAccessing base class function from Derived class 1:");
display();
}
}
class C extends A
{
void display2()
{
System.out.println("Derived class2");
System.out.println("\tAccessing base class function from Derived class 2");
display();
}
}
public class ex5d
{
public static void main(String[] args) {
B obj1=new B(); C obj2=new C(); obj1.display1(); obj2.display2();
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the Java Program to illustrate how multilevel inheritance is supported is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 6: Java program to demonstrate the use of implementing


interfaces

Aim:
To write a program to demonstrate the use of implementing interfaces.

Algorithm:
1. Start
2. Create interface with function ShowA()
3. Create interfaceB with function ShowB()
4. Create classC which implements A and B
5. In classC implement the two functions
6. Create class 5b which contains the main function
7. In the main function create an object obj for classC
8. Using objc function ShowA() and ShowB()
9. Stop

Program:
interface AnimalEat{voideat();
}
interface AnimalTravel{void travel();
}
class Animal implements AnimalEat, AnimalTravel{public void eat() {
System.out.println("Animals Eating");
}
public void travel(){
System.out.println("Animal is travelling");
}
}
Public classDemo{
public static void main(String args[]) {
Animal a =newAnimal(); a.eat();
a.travel(); }}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the Java program to demonstrate the use of implementing interfaces is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 7: Java program to implement all string operations using


interface

Aim:
To Write A java program to implement all string operations using interface.

Algorithm:
1. Start
2. Create an interface strings_interface which declares and initializes strings
s, s1,
3. s2, str1, word1, word2 and word4 on which String methods are to be
used.
4. Declare void methods findlength(), findcharat(), findsubstring(),
concatenate(),findindexof(), checkequality(), checkequalitywithoutcase(),
comparingto(), lowercase(),uppercase(),trimword() and replacement()
5. CreateclassAwhichimplementsstrings_interface
6. OverrideandimplementallthemethodsdeclaredintheinterfaceinclassA
7. Createclassex7whichextendsA
8. CreateanobjectaofAinthemainmethod
9. UsingacallallthemethodsinclassA
10.Stop

Program:
import java.io.*; import java .util.*; interface strings_interface
{
String s="Unbowed Unbent Unbroken"; String s1="one";
String s2="two";
String str1="Blows and Burns"; String word1="YES";
String word2="yes";
String word4="High on honor";
void findlength(); void findcharAt(); void findsubstring(); void concatenate();
void findindexof(); void checkequality();
void checkequalitywithoutcase(); void comparingto();
void lowercase();
DATE: NAME:
REG NO.:

void uppercase(); void trimword();


void replacement();
}
class A implements strings_interface
{
public void findlength()
{
System.out.println("String length of 'Unbowed Unbent
Unbroken'="+s.length());
}
public void findcharAt()
{
System.out.println("Character at 3rd position="+s.charAt(3));
}
public void findsubstring()
{
System.out.println("Substring="+s.substring(2,5));
}
public void concatenate()
{
System.out.println("Concatenated String="+s1.concat(s2));
}
public void findindexof()
{
System.out.println("Index of share="+s.indexOf("Unbent"));
}
public void checkequality()
{
Boolean out=s1.equals("one");
System.out.println("Checking Equality of 'one' and 'one':"+out);
}
DATE: NAME:
REG NO.:

public void checkequalitywithoutcase()


{
Boolean out="oNe".equalsIgnoreCase("one");
System.out.println("Checking Equality of 'oNe' and 'one' with equals ignore
case:"+out);
}
public void comparingto()
{
int out1=s1.compareTo(s2);
System.out.println("The difference between ASCII values of s1='one' and
s2='two'="+out1);
}
public void lowercase()
{
System.out.println("Changing 'YES' to lowercase:"+word1.toLowerCase());
}
public void uppercase()
{
System.out.println("Changing 'yes' to uppercase:"+word2.toUpperCase());
}
public void trimword()
{
System.out.println("Trimmed the word"+"'"+word4.trim()+"'");
}
public void replacement()
{
System.out.println("Orginal String:"+str1); String str2=str1.replace('s','i');
System.out.println("Replaced 's' with 'i' ->"+str2);
}
}
class ex7 extends A
{
public static void main(String args[])
DATE: NAME:
REG NO.:

{
A a= new A(); a.findlength(); a.findcharAt(); a.findsubstring();
a.concatenate(); a.findindexof(); a.checkequality();
a.checkequalitywithoutcase(); a.comparingto(); a.lowercase();
a.uppercase(); a.trimword(); a.replacement();
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to implement all string operations using interface is
executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 8. Java program to create student report using applet, read the


input using text boxes and display the output using buttons
Aim:
To write a program to create student report using applet, read the input using
textbox and display the output using buttons.

Algorithm:
Step 1: Start
Step 2: Install jdk* and applet won’t support from jdk9 and upper versions.
Step 3: Now create a student info class and declare all the required labels,
textboxes and buttons.
Step 4: Create init function and create the labels, text fields and buttons
declared in the above class.
Step 5: Create the action performed for each text box, Label and button in try
and catch blocks to avoid exceptions.
Step 6: Stop.

Program:
import java.awt.*; import java.applet.*; import java.awt.event.*;
public class classstudentreport extends Applet implements ActionListener{
Label
lblTitle,lblRegNo,lblName,lblJava,lblSE,lblCA,lblBI,lblSSPD; TextField
txtRegNo,txtName,txtJava,txtSE,txtCA,txtBI,txtSSPD; Button cmdReport int
total; float avg; public void init(){ setLayout(null);
lblTitle = new Label("Enter Student's Details"); lblRegNo = new Label("Reg.No
: ");

lblName = new Label("Name : ");


lblJava = new Label("Java : ");
lblSE = new Label("SE : ");
lblCA = new Label("CA :");
lblBI = new Label("BI :");
DATE: NAME:
REG NO.:

lblSSPD = new Label("SSPD :");


txtRegNo = new TextField(10);
txtName = new TextField(25);
txtJava = new TextField(3);
txtSE = new TextField(3);
txtCA = new TextField(3);
txtBI = new TextField(3);
txtSSPD = new TextField(3);
cmdReport = new Button("View Student Result");
lblTitle.setBounds(100,0,200,20);
lblRegNo.setBounds(0,50,100,20);
txtRegNo.setBounds(120,50,100,20);
lblName.setBounds(0,70,100,20);
txtName.setBounds(120,75,250,20);
lblJava.setBounds(0,100,100,20);
txtJava.setBounds(120,100,40,20);
lblSE.setBounds(0,125,100,20);
txtSE.setBounds(120,125,40,20);
lblCA.setBounds(0,150,100,20);
txtCA.setBounds(120,150,40,20);
lblBI.setBounds(0,175,100,20);
txtBI.setBounds(120,175,40,20);
lblSSPD.setBounds(0,200,100,20);
txtSSPD.setBounds(120,200,40,20);
cmdReport.setBounds(100,225,150,30);
add(lblTitle); add(lblRegNo);
add(txtRegNo); add(lblName);
add(txtName); add(lblJava); add(txtJava);
add(lblSE); add(txtSE); add(lblCA);
NAME:- Student1 REG.NO:- 412522104000
add(txtCA); add(lblBI); add(txtBI); add(lblSSPD); add(txtSSPD);
add(cmdReport);
DATE: NAME:
REG NO.:

cmdReport.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){ try{
int java = Integer.parseInt(txtJava.getText()); int se =
Integer.parseInt(txtSE.getText()); int ca = Integer.parseInt(txtCA.getText()); int
bi = Integer.parseInt(txtBI.getText()); int sspd =
Integer.parseInt(txtSSPD.getText());
total = (java + se + ca + bi + sspd); avg = total/5;
}
catch(NumberFormatException e){
}
repaint();
}
public void paint(Graphics g){
g.drawString(" STUDENTREPORT ",100,275);
g.drawString("Reg. No = "+txtRegNo.getText(),0,300);
g.drawString("Name = "+txtName.getText(),0,325);
g.drawString("Java = "+txtJava.getText(),0,350);
g.drawString("Software Engineering = "+txtSE.getText(),0,375);
g.drawString("Computer Architecture = "+txtCA.getText(),0,400);
g.drawString("Banking & Insurance = "+txtBI.getText(),0,425);
g.drawString("SSPD = "+txtSSPD.getText(),0,450);
g.drawString("Total = "+total,0,475);
g.drawString("Average = "+avg,0,500); }
}
/*<applet code="classstudentreport" height=800 width=800> </applet>*/
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to create student report using applet, read the input
using text boxes and display output using button is executed successfully and
output is verified.
DATE: NAME:
REG NO.:

EX 9: Java Program To Implement Thread Priorities

Aim:
To write a program to implement thread priorities.

Algorithm:
Step 1: Start
Step 2: Import necessary packages.
Step 3: Define class that extends thread.
Step 4: In the driver code, create objects.
Step 5: set the priorities of the threads.
step 6: End

Program:
import java.lang.*; class GFG extends Thread
{
public void run()
{
System.out.println("Inside run method");
}
public static void main(String[] args)
{
Thread.currentThread().setPriority(6);
System.out.println ("main thread
priority:"+Thread.currentThread().getPriority());
GFG t1 = new GFG();
System.out.println("t1 thread priority : "+ t1.getPriority());
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to implement thread priorities has been executed
successfully and output is verified.
DATE: NAME:
REG NO.:

EX 10: Java program to Implement Thread, Applets Graphics


Animate Ball Movement

Aim:
To write a program to implement thread, applets and graphics to animate ball
movement.

Algorithm:
Step 1: Start.
Step 2: Import the Necessary packages.
Step 3: Set the Backgroundcolor (setBackground method) and the color of the
ball (paint method) using methods.
Step 4: Create thread and start running it(declare flag variable as true). Step 5:
Using the dimensions from the html code, set boundaries within which the ball
can move at a certain rate.
Step 6: Repaint the scenario at every instance when while loop gets iterated
every time.

Program:
import java.awt.*; import java.io.*; import java.applet.*; import
java.awt.event.*;
public class movingball extends Applet implements Runnable
{ int x,y,dx,dy; Thread t; boolean flag; public void init()
{
setBackground(Color.black); x=100; y=10;
dx=10;dy=10;
}

public void start()


{
flag = true; t = new Thread(this); t.start(); } public void paint(Graphics g)
{
DATE: NAME:
REG NO.:

g.setColor(Color.white);
g.fillOval(x,y,50,50); } public void run()
{
while(flag) {
Rectangle r = getBounds(); if((x+dx<=0)||(x+dx>=r.width))
{ dx=-dx; }
if((y+dy<=0)||(y+dy>=r.height)) dy=-dy; x+=dx; y+=dy; repaint(); try{
Thread.sleep(300);
} catch(InterruptedException e){}
} } public void stop()
{ t = null; flag = false;
}
}
/*
<applet code = “movingball.class” height = 100 width = 700></applet>
*/
DATE: NAME:
REG NO.:

Output:

Output:
Thus, a program to implement thread, applet and graphics to animate ball
movement has been successfully executed and output is verified.
DATE: NAME:
REG NO.:

EX 11A: Java Program To Paint Like A Paint Brush In An Applet.

Aim:
To write a JAVA program to paint like a paint brush in an applet.

Algorithm:
1. Start
2. Create a public class Mouse Drag which extends Applet and implements
MouseMotionListener.
3. Use public void init() to initialize the applet
4. Set background colour to white
5. Create a method called as mousedragged and create object for method
graphics
6. Set olours and position by caling the method using object name.
7. Add HTML code for frontend
8. Stop

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)
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a Java program to paint like a paint brush in an applet has been
successfully executed successfully and output is verified.
DATE: NAME:
REG NO.:

EX 11B: Display Analog Clock Using Applet

Aim:
To write a JAVA program that display the x and y position of the cursor
movement using Mouse.

Algorithm:
Step1: Start.
Step2: Import the necessary packages.
Step3: Create a class which extends applet class.
Step4: Implement the MouseListener and MouseMotionListener interface.
Step5: Define the comments for each action performed by the mouse.
Step6: Stop.

Program:
import java.applet.*;
import java.awt.*;
import java.util.*;
public class Clock extends Applet implements Runnable
{
Thread t;
public void init()
{
setBackground(Color.white);
}
public void start()
{
t = new Thread(this);
t.start();
}
public void run()
{
DATE: NAME:
REG NO.:

while(true)
{
try
{
repaint();
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
public void paint(Graphics g)
{
Calendar time = Calendar.getInstance();
int hour =time.get(Calendar.HOUR_OF_DAY) % 12;
int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
double angle;
int x,y;
int radius=150;
g.drawOval(100,100,300,300);
String s="12";
int i=0;
while(i<12)
{
angle = Math.toRadians(30*(i-3));
x = 250+(int)(Math.cos(angle)*135);
y = 250+(int)(Math.sin(angle)*135);
g.drawString(s,x,y);
i++;
s=String.valueOf(i);
DATE: NAME:
REG NO.:

}
g.setColor(Color.green);
angle = Math.toRadians((30*hour)-90);
x = 250+(int)(Math.cos(angle)*100);
y = 250+(int)(Math.sin(angle)*100);
g.drawLine(250,250,x,y);
g.setColor(Color.red);
angle = Math.toRadians((6*minute)-90);
x = 250+(int)(Math.cos(angle)*115);
y = 250+(int)(Math.sin(angle)*115);
g.drawLine(250,250,x,y);
g.setColor(Color.blue);
angle = Math.toRadians((6*second)-90);
x = 250+(int)(Math.cos(angle)*130);
y = 250+(int)(Math.sin(angle)*130);
g.drawLine(250,250,x,y);
}
}
/*
<applet code = Clock.class width=500 height=500>
</applet>
*/
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to write a program to display analog clock using Applet
is executed and verified successfully.
DATE: NAME:
REG NO.:

EX 11.C CREATE DIFFERENT SHAPES AND FILL COLORS USING APPLET


Aim:
To write a program that identifies key-up key-down event user entering text in
an Applet

Algorithm:
1. Start
2. Use method drawPolygon and fillPolygon of the Graphics class to draw
and
3. fill the shapes – Square, Pentagon, Rectangle and Triangle.
4. Use method drawOval and fillOval of the Graphics class to draw and fill
the shapes – Oval and Circle.
5. Stop.

Program:
import java.applet.*;
import java.awt.*;
public class Shapes extends Applet
{
public void init()
{
setBackground(Color.white);
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
g.setColor(Color.black);
DATE: NAME:
REG NO.:

g.drawString("Pentagon",225,200);
x=new int[]{200,250,300,300,250,200};
y=new int[]{100,50,100,150,150, 100};
g.drawPolygon(x,y,6);
g.setColor(Color.yellow);
g.fillPolygon(x,y,6);
g.setColor(Color.black);
g.drawString("Circle",400,200);
g.drawOval(350,50,125,125);
g.setColor(Color.yellow);
g.fillOval(350,50,125,125);
g.setColor(Color.black);
g.drawString("Oval",100,380);
g.drawOval(50,250,150,100);
g.setColor(Color.yellow);
g.fillOval(50,250,150,100);
g.setColor(Color.black);
g.drawString("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
g.setColor(Color.black);
g.drawString("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
g.drawPolygon(x,y,3);
g.setColor(Color.yellow);
g.fillPolygon(x,y,3);
}}
/* <applet code = Shapes.class width=600 height=600> </applet> */
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program that identifies key-up key-down event user entering text
in a Applet is executed and verified successfully.
DATE: NAME:
REG NO.:

EX 12A: Java Program to Demonstrate Mouse Event Handling.

Aim:
To write a java program to demonstrate mouse event handling.

Algorithm:
STEP 1: START
STEP 2: If void mouseReleased(MouseEvent e) : Mouse key is released
STEP 3: If void mouseClicked(MouseEvent e) : Mouse key is pressed/release
STEP 4: IF void mouseEntered(MouseEvent e) : Mouse entered the component
STEP 5: If void mousepressed(MouseEvent e) : Mouse key is pressed
STEP 6: END

Program:
import java.awt.*; import java.awt.event.*; import java.applet.*;
public class mouse extends Applet implements MouseListener,
MouseMotionListener
{
String s1=" "; int x,y; public void init()
{
addMouseListener(this); addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=100; y=100;
s1="Mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{
x=100; y=200;
s1="Mouse entered"; repaint();
}
DATE: NAME:
REG NO.:

public void mouseExited(MouseEvent me)


{
x=100; y=300;
s1="Mouse exited"; repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX(); y=me.getY(); s1="Mouse Pressed"; repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX(); y=me.getY(); s1="Mouse Released"; repaint();
}
public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY();
s1="Mouse Dragged"; repaint();
}
public void mouseMoved(MouseEvent me)
{
x=me.getX(); y=me.getY();
s1="Mouse Moved";
repaint();
}
public void paint(Graphics g)
{
g.drawString(s1,x,y);
}
}//<applet code="mouse" width=450 height=300></applet>
DATE: NAME:
REG NO.:

Output:

Result:
Thus, a Java program to demonstrate mouse event handling has been
successfully executed and output is verified.
DATE: NAME:
REG NO.:

EX 12.B KEY-UP KEY-DOWN EVENT USER ENTERING TEXT


IN A APPLET
Aim:
To write a program that identifies key-up key-down event user entering text in
a Applet

Algorithm:
1. Start.
2. Use document.elementFromPoint(x+px, y+py) in which we pass the position
of image cursor.
3. After obtaining the required object,invoke the object.click().
4. Stop.

Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class KeyEventDemo extends Applet implements KeyListener
{
String msg = &quot;&quot;;
public void init()
{
addKeyListener(this);
}
public void keyReleased(KeyEvent k)
{
showStatus(&quot;Key Released&quot;);
repaint();
}
public void keyTyped(KeyEvent k)
{
showStatus(&quot;Key Typed&quot;);
DATE: NAME:
REG NO.:

repaint();
}
public void keyPressed(KeyEvent k)
{
showStatus(&quot;Key Pressed&quot;);
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 10, 10);
}
}
/*
&lt;applet code=&quot;KeyEventDemo&quot; height=&quot;400&quot;
width=&quot;400&quot;&gt;
&lt;/applet&gt;
*/
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program that identifies key-up key-down event user entering text
in a Applet is executed and verified successfully.
DATE: NAME:
REG NO.:

EX 13.B DISPLAY THE DIGITAL WATCH IN SWING

Aim:
To write a java program to display the digital watch in swing.

Algorithm:
1. Start
2. Import swing libraries
3. Create a class implementing runnable
4. Declare a thread to control the watch
5. Construct a digital clock with bound conditions
6. Declare the sleep time and run the thread
7. Stop

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);
DATE: NAME:
REG NO.:

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();
}
}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to display the digital watch in swing is executed and
verified successfully.
DATE: NAME:
REG NO.:

EX 13.C CREATE A SINGLE BALL BOUNCING INSIDE A JPANEL

Aim:
To write a java program to create a single ball bouncing inside a JPanel.

Algorithm:
1. Start
2. Import swing
3. Create a class extending JPanel
4. Declare the bounds of the ball
5. Create a thread and declare path in all quardinates.
6. Run the thread to animate the bouncing ball
7. Stop

Program:
import java.awt.*;
import javax.swing.*;
public class BouncingBall extends JPanel {
int width;
int height;
float radius = 40;
float diameter = radius * 2;
float X = radius + 50;
float Y = radius + 20;
float dx = 3;
float dy = 3;
public BouncingBall() {
Thread thread = new Thread() {
public void run() {
while (true) {
width = getWidth();
height = getHeight();
DATE: NAME:
REG NO.:

X = X + dx ;
Y = Y + dy;
if (X - radius &lt; 0) {
dx = -dx;
X = radius;
}
else if (X + radius &gt; width) {
dx = -dx;
X = width - radius;
}
if (Y - radius &lt; 0) {
dy = -dy;
Y = radius;
} else if (Y + radius &gt; height) {
dy = -dy;
Y = height - radius
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
};
thread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval((int)(X-radius), (int)(Y-radius), (int)diameter,
(int)diameter); } public static void main(String[] args) {
DATE: NAME:
REG NO.:

JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame(&quot;Bouncing Ball&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setContentPane(new BouncingBall());
frame.setVisible(true);
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the java program to create a single ball bouncing inside a JPanel is
executed and verified successfully.
DATE: NAME:
REG NO.:

EX 13.D DISPLAYING A REAL TREE UPSIDE DOWN

Aim:
To write a JTree as displaying a real tree upside down.

Algorithm:
1. Start
2. Import swing tree library
3. Create a class
4. Set frame and create a tree
5. Create objects of the tree and add objects below the
tree and display it.
6. Stop

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");
DATE: NAME:
REG NO.:

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();
}}
DATE: NAME:
REG NO.:

Output:

Result:
Thus, the JTree program to display a real tree upside down is executed and
verified successfully.

You might also like