0% found this document useful (0 votes)
328 views61 pages

Oops (Java) Lab Programs-2 PDF

The document appears to be a certificate from Narasaraopeta Engineering College that certifies the completion of laboratory experiments by a student over the course of an academic year, as it lists the student name, year of study, semester, experiments completed with dates and page numbers, marks awarded and signatures of staff. It contains 35 experiments conducted in areas like Java programming, classes, interfaces, exceptions and more.

Uploaded by

Syam Siva Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
328 views61 pages

Oops (Java) Lab Programs-2 PDF

The document appears to be a certificate from Narasaraopeta Engineering College that certifies the completion of laboratory experiments by a student over the course of an academic year, as it lists the student name, year of study, semester, experiments completed with dates and page numbers, marks awarded and signatures of staff. It contains 35 experiments conducted in areas like Java programming, classes, interfaces, exceptions and more.

Uploaded by

Syam Siva Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 61

NARASARAOPETA ENGINEERING COLLEGE::NARASARAOPET

(AUTONOMOUS)

GUNTUR DIST - 522 601

REGISTER NUMBER

CERTIFICATE
This is to Certify that this is the bonafide record of work done by

Mr./Miss………………………………………………………………………………

……Of………………………………………year,M.C.A……………………...…….

semester In the………………………………… laboratory during the academic

year………………….

Total No. of Experiments Performed:

Staff – in charge Head of the Department

Submitted for the practical Examination held on ……….

Internal Examiner External Examiner

i
INDEX

S.No Date Name of the Experiment Page. Awarded Signature


No Marks

1 WJAP to display simple message 1

2 WJAP to print integers. 2

3 WJAP to If else control 3

4 WJAP to command line arguments 4

5 WJAP for loop print natural numbers 5

6 WJAP for while loop 6

7 WJAP for odd and even numbers 7

8 WJAP for swapping 8

9 WJAP for factorial of number 9

10 WJAP to print time and date 10

11 WJAP for bubble sort 11-12

12 WJAP to large of three numbers 13-14

13 WJAP using classes and objects 15-16

14 WJAP to implement inheritance 16-17

15 WJAP to multithreading 17-18

ii
S.No Date Name of the Experiment Page. No Awarded Signature
Marks

16 WJAP to method overriding 19-20

17 WJAP to method overloading 21


18
WJAP to implement interface 22
19
WJAP for exception handling 23
20
WJAP for Fibonacci 24
21
WJAP for wrapper classes 25
22
WJAP for prime numbers 26
23
WJAP for palindrome or not 27
24
WJAP for sorting ascending order 28-31
25
WJAP to multiplication of two 32-36
matrices
26
WJAP for run time polymorphism 37
27
WJAP for package 38
28
WJAP for string tokenizes classes 39
29
WJAP for files operations 40-41
30
WJAP to count things in a string 42
31
WJAP for applet 43-44
32
WJAP to draw lines ,rectangles 45-46
33
WJAP for simple calculator 47-51
34
WJAP for handling mouse events 52-54

iii
35
WJAP for life cycle of thread 55-57

iv
1. Write a java program to display simple messages on screen .
class manoj
{
public static void main(String args[])
{
System.out.println("hello ");
System.out.println("welcome to java world ");
System.out.println("a very good morning "); manoj
obj=new manoj();
obj.add(2,7);
}
int result;

void add(int x,int y)


{
result=x+y;
System.out.println("result is "+result);
}
}

OUTPUT :

hello
welcome to java world a very
good morning result is 9

1
2. Write a java program to Print integers

class Integers {
public static void main(String[] arguments) {
int c; //declaring a variable

/* Using a for loop to repeat instruction execution */

for (c = 1; c <= 10; c++) {


System.out.println(c);
}
}
}
Output:

2
3. Write a java program to If else control instructions.

class Condition {
public static void main(String[] args) {
boolean learning = true;

if (learning) {
System.out.println("Java programmer");
}
else {
System.out.println("What are you doing here?");
}
}
}
Output:

3
4. Write a java program to Command line arguments.

class Arguments {
public static void main(String[] args) {
for (String t: args) {
System.out.println(t);
}
}
}

OUTPUT :

4
5. Write a java program for loop to print first 10 natural numbers, i.e., from 1 to 10.

//Java for loop program


class ForLoop {
public static void main(String[] args) {
int c;

for (c = 1; c <= 10; c++) {


System.out.println(c);
}
}
}

Output of program:

5
6. Write a java program to while loop example
import java.util.Scanner;

class WhileLoop {
public static void main(String[] args) {
int n;

Scanner input = new Scanner(System.in);


System.out.println("Input an integer");

while ((n = input.nextInt()) != 0) {


System.out.println("You entered " + n);
System.out.println("Input an integer");
}

System.out.println("Out of loop");
}
}

Output of program:

6
7. Write a java program Odd even program in Java
import java.util.Scanner;

class OddOrEven
{
public static void main(String args[])
{
int x;
System.out.println("Enter an integer to check if it's odd or even");
Scanner in = new Scanner(System.in);
x = in.nextInt();

if (x % 2 == 0)
System.out.println("The number is even.");
else
System.out.println("The number is odd.");
}
}

Output of program:

7
8. Write a java program to Swapping
import java.util.Scanner;

class SwapNumbers
{
public static void main(String args[])
{
int x, y, t;
System.out.println("Enter two numbers (x & y)");
Scanner in = new Scanner(System.in);

x = in.nextInt();
y = in.nextInt();

System.out.println("Before Swapping\nx = "+x+"\ny = "+y);

t = x;
x = y;
y = t;

System.out.println("After Swapping\nx = "+x+"\ny = "+y);


}
}

Output of program:

8
9. Write a java program to Factorial of a number in Java
import java.util.Scanner;

class Factorial
{
public static void main(String args[])
{
int n, c, f = 1;

System.out.println("Enter an integer to calculate its factorial");


Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println("Number should be non-negative.");
else
{
for (c = 1; c <= n; c++)
f = f*c;

System.out.println("Factorial of "+n+" is = "+f);


}
}
}

Output of program:

9
10. Write a java program to Date and Time program in Java
import java.util.*;

class GetCurrentDateAndTime
{
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();

day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);

second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);

System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);


System.out.println("Current time is "+hour+" : "+minute+" : "+second);
}
}

Output of program:

10
11. Write a java program to Bubble sort program in Java
import java.util.Scanner;

class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);

System.out.println("Input number of integers to sort");


n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)


array[c] = in.nextInt();

for (c = 0; c < ( n - 1 ); c++) {


for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

System.out.println("Sorted list of numbers:");

for (c = 0; c < n; c++)


System.out.println(array[c]);
}
}

OUTPUT :

11
12
12. write a java program to find largest of three numbers

class greater
{
public static void main(String args[])
{
int a=98,b=87,c=99; if(a>b)

{
if(a>c)
{

System.out.println(" a is greater ");


}
else
{

System.out.println(" c is greater ");


}
}

else
{
if(b>c)
}

else
{

13
}
}
}
}
OUTPUT :
c is greater

14
13. write a java program using classes and object in java

public class data


{
String id;
String name;
String age;

public data()
{
id="8043";
name="MANOJ";
age="22";
}
public void displaydata()
{
System.out.println("my id is="+id);
System.out.println("my name is="+name);
System.out.println("my age is="+age);
}
public static void main(String args[])
{
data obj=new data();
obj.displaydata();
}
}

OUTPUT :
my id is=8043
my name is=MANOJ
my age is=22

15
14. write a java program to implement inheritance
class room
{
int l;
int b;
room(int x, int y)
{
l=x;
b=y;
}
int area()
{
return(l*b);
}
}
class bedroom extends room
{
int h;
bedroom(int x,int y, int z)
{
super(x,y);
h=z;
}
int volume()
{
return(l*b*h);
}
}
class inheritance
{
public static void main(String args[])
{
bedroom room1=new bedroom(10,20,30);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("area1="+area1);
System.out.println("volume1="+volume1);
}
}

OUTPUT :

16
area1=200
volume1=6000

15. write a java program to implement multithreading


class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("from thread A :i= "+i);
}
}
}
class B extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("from thread B :i= "+i);
}
}
}
class C extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("from thread C :i= "+i);
}
}
}
class threadtest
{
public static void main(String args[])
{
new A().start();
new B().start();

17
new C().start();
}
}

OUTPUT :
from thread A :i= 1
from thread A :i= 2
from thread A :i= 3
from thread A :i= 4
from thread A :i= 5
from thread B :i= 1
from thread B :i= 2
from thread B :i= 3
from thread B :i= 4
from thread B :i= 5
from thread C :i= 1
from thread C :i= 2
from thread C :i= 3
from thread C :i= 4
from thread C :i= 5

18
16. write a java program to implement method overriding
class sup
{
int x;
sup(int x)
{
this.x=x;
}
void display()
{
System.out.println("x= "+x);
}
}

class sub extends sup


{
int y;
sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("x= "+x);
System.out.println("y= "+y);
}
}

class overloading
{
public static void main(String args[])
{
sub s=new sub(10,20);
s.display();
}
}

19
OUTPUT :
x= 10
y= 20

20
17. write a java program to implement method overloading
class funcload
{
public static void main(String args[])
{
funcload obj=new funcload();
obj.add(15,24);
obj.add(2.3f,0.8f);
obj.add(56,76.76f);
}
int x,y;
float p,q,result;
void add(int a,int b)
{
x=a;
y=b;
result=x+y;
System.out.println("the result is:" + result);
}
void add(float a,float b)
{
p=a;
q=b;
result=p+q;
System.out.println("the result is:" + result);
}
void add(int a,float b)
{
x=a;
p=b;
result=x+p;
System.out.println("the result is:" + result);

}
}

21
OUTPUT :
the result is:39.0
the result is:3.1
the result is:132.76001

18. write a java program to implement interface

interface area
{
final float p=3.14f;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements area
{
public float compute(float x,float y)
{
return(p*x*x);
}
}
class inter
{
public static void main(String args[])
{

"+a.compute(10,20));

OUTPUT :

Area of rectangle= 200.0


Area of circle= 314.0

22
19 .write a java program to implement exception handling in java

class handle
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x;
int y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("y="+y);
}
}

OUTPUT :

Division by zero
y=1

23
20. A Java program that uses both recursive and non-recursive functions to print the nth value of the

Fibonacci sequence .

import
java.util.Scanner;
class _2Assignment
{
public static void main(String args[])
{
System.out.println("Enter the number n to print the faboniccs series ");
Scanner ob=new Scanner(System.in);
short a=ob.nextShort();
Series ob1=new Series();
long b=ob1.input(a);
System.out.println("The "+a+"th number of the faboniccs series is "+b);
}
}
class Series
{

int a=1;
int b=1;
int c=0;
int count;
int input(int a)
{
count=a;
count=fabo(count);
return count;
}

int fabo(int count)


{
if(count!=2)
{
c=a+b;
a=b;
b=c;
fabo(--count);
}
return c;
}
}

OUTPUT :

24
Enter the number n to print the faboniccs series 8

the number of the faboniccs series is 0 1 1 2 3 5 8 13

25
21. A Java program to demonstrate wrapper classes and to fix the precision.

public class WrapperExample3{

public static void main(String args[]){

byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj); System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");

26
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}

OUTPUT :

---Printing object values---


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

27
22. A Java program that prompts the user for an integer and then prints out all prime numbers up
to that integer.

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
OUTPUT:
Enter a number:

20

11

13

17

19

28
23. Write a java program to Whether check the given string is Palindrome or
not.(ex:MALAYALAM)

import java.util.Scanner;

class ChkPalindrome

public static void main(String args[])

String str, rev = "";

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");

str = sc.nextLine();

int length = str.length();

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

rev = rev + str.charAt(i);

if (str.equals(rev))

System.out.println(str+" is a palindrome");

else

System.out.println(str+" is not a palindrome");

29
}

OUTPUT:
Enter a string:

MALAYALAM

MALAYALAM is a palindrome

30
24. write a java program to sorting given list of names in ascending ordeer

import java.util.Scanner;
public class Alphabetical_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}

31
OUTPUT:
$ javac Alphabetical_Order.java
$ java Alphabetical_Order

Enter number of names you want to enter:5


Enter all the names:
bryan
adam
rock
chris
scott
Names in Sorted Order:adam,bryan,chris,rock,scott

32
25. Write a java program to check the compatibility for multiplication, if compatible
multiplies two matrices and find its transpose.
import java.util.Scanner;
class Matrix
{
void matrixMul(int m, int n, int p, int q)
{
int[][] a,b,c,t;
a = new int[m][n];
b = new int[p][q];
c = new int[m][q];
t = new int[q][m];
Scanner s = new Scanner(System.in);
System.out.println("Enter the elements of matrix A: ");
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
a[i][j] = s.nextInt();
}
}
System.out.println("Enter the elements of matrix B: ");
for(int i = 0; i < p; i++)
{
for(int j = 0; j < q; j++)
{
b[i][j] = s.nextInt();
}
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < q; j++)
{
for(int k = 0; k < n; k++)
{
c[i][j] += a[i][k]*b[k][j];
}
}
}
System.out.println("Elements of result matrix C are: ");

33
for(int i = 0; i < m; i++)
{
for(int j = 0; j < q; j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.print("\n");
}
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
t[i][j] = c[j][i];
}
}
System.out.println("Elements of transpose matrix T are: ");
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
System.out.print(t[i][j]+"\t");
}
System.out.print("\n");
}
}
}
class Driver
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter no of rows in first matrix: ");
int m = s.nextInt();
System.out.println("Enter no of columns in first matrix: ");
int n = s.nextInt();
System.out.println("Enter no of rows in second matrix: ");
int p = s.nextInt();
System.out.println("Enter no of columns in second matrix: ");
int q = s.nextInt();
if(n == p)

34
{
Matrix obj = new Matrix();
obj.matrixMul(m,n,p,q);
}
else
{
System.out.println("Matrix multiplication cannot be performed...");
}
}
}
OUTPUT:
Enter no of rows in first matrix:
3
Enter no of columns in first matrix:
3
Enter no of rows in second matrix:
3
Enter no of columns in second matrix:
3
Enter the elements of matrix A:
111
222
333
Enter the elements of matrix B:
123
123
111
Elements of result matrix C are:
3 5 7
6 10 14
9 15 21
Elements of transpose matrix T are:
3 6 9
5 10 15
7 14 21

35
26. Write a java program that illustrates how runtime polymorphism is achieved.

abstract class Figure


{
int dim1, dim2;
Figure(int x, int y)
{
dim1 = x;
dim2 = y;
}
abstract void area();
}
class Triangle extends Figure
{
Triangle(int x, int y)
{
super(x,y);
}
void area()
{
System.out.println("Area of triangle is: "+(dim1*dim2)/2);
}
}
class Rectangle extends Figure
{
Rectangle(int x, int y)
{
super(x,y);
}
void area()
{
System.out.println("Area of rectangle is: "+(dim1*dim2));
}
}
class RuntimePoly
{
public static void main(String args[])
{
Figure f;
Triangle t = new Triangle(20,30);

36
Rectangle r = new Rectangle(20,30);
f = t;
f.area();
f = r;
f.area();
}
}

OUTPUT:

Area of triangle is: 300


Area of rectangle is: 600

37
27. Write a java program to create and demonstrate package

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Output :

Welcome to package

38
28. Write a java program using StringTokenizer class, which reads a line of
integers and then displays each integer and the sum of all integers.

import java.util.*;
class StringTokenDemo
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a line of numbers: ");
String input = s.next();
StringTokenizer st = new
StringTokenizer(input,"@");
int sum = 0;
while(st.hasMoreTokens())
{
int n = 0;
n = Integer.parseInt(st.nextToken());
System.out.println("Number is: "+n);
sum += n;
}
System.out.println("Sum of the numbers is: "+sum);
}
}
OUTPUT:
Enter a line of numbers: 2@3@1@4@5
Number is: 2
Number is: 3
Number is: 1
Number is: 4
Number is: 5
Sum of the numbers is: 15

39
29. Write a java program that reads a file name from the user and then displays
information about whether the file exists, whether the file is
readable/writable, the type of file and the length of the file in bytes and
display the content using FileInputStream.
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");

try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}

OUTPUT:
40
File name: sample.txt
File exists: true
File is readable: true
File is writable: true
Is a directory: false
length of the file: 20 bytes
Contents of the file are:
Hi, welcome to Java.

41
30. Write a java program that displays the number of characters, lines and words in a text
file.
import java.util.*;
import java.io.*;
class Cfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n)
}
}
OUTPUT:
Enter File name: Sample.txt
Number of lines : 3
Number of words : 3
Number of characters : 26

42
31. Write an Applet program that displays the content of the file.

/*
<applet code="MyApplet" height="300" width="500">
</applet>
*/

import java.applet.*;
import java.awt.*;
import java.io.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new
FileInputStream("sample.txt");
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
fis.close();
content = new String(buff);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)

43
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
OUTPUT:
Contents of sample.txt file:
Hi, welcome to Java.

32. Write a java program that allows the user to draw lines,rectangles and ovals.

44
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class LinesRectsOvals extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.red);

g.drawLine(5,30,350,30);
g.setColor(Color.blue);
g.drawRect(5,40,90,55);
g.fillRect(100,40,90,55);
g.setColor(Color.cyan);
g.fillRoundRect(195,40,90,55,50,50);
g.drawRoundRect(290,40,90,55,20,20);
g.setColor(Color.yellow);
g.draw3DRect(5,100,90,55,true);
g.fill3DRect(100,100,90,55,false);
g.setColor(Color.magenta);
g.drawOval(195,100,90,55);
g.fillOval(290,100,90,55);
}
}

Output:

45
46
33. Write a java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field
to display the result.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code="Calculator1" width=300 height=300></applet>*/

public class Calculator1 extends Applet implements ActionListener

TextField t;

Button b[]=new Button[15];

Button b1[]=new Button[6];

String op2[]={"+","-","*","%","=","C"};

String str1="";

int p=0,q=0;

String oper;

public void init()

setLayout(new GridLayout(5,4));

t=new TextField(20);

setBackground(Color.pink);

setFont(new Font("Arial",Font.BOLD,20));

int k=0;

47
t.setEditable(false);

t.setBackground(Color.white);

t.setText("0");

for(int i=0;i<10;i++)

b[i]=new Button(""+k);

add(b[i]);

k++;

b[i].setBackground(Color.pink);

b[i].addActionListener(this);

for(int i=0;i<6;i++)

b1[i]=new Button(""+op2[i]);

add(b1[i]);

b1[i].setBackground(Color.pink);

b1[i].addActionListener(this);

add(t);

public void actionPerformed(ActionEvent ae)

{
48
String str=ae.getActionCommand();

if(str.equals("+")){
p=Integer.parseInt(t.getText());

oper=str;

t.setText(str1="");

else if(str.equals("-")){ p=Integer.parseInt(t.getText());

oper=str;

t.setText(str1="");

else if(str.equals("*")){ p=Integer.parseInt(t.getText());

oper=str;

t.setText(str1="");

else if(str.equals("%")){ p=Integer.parseInt(t.getText());

oper=str;

t.setText(str1="");

else if(str.equals("=")) { str1="";

if(oper.equals("+")) {

49
q=Integer.parseInt(t.getText());

t.setText(String.valueOf((p+q)));}

else if(oper.equals("-")) {

q=Integer.parseInt(t.getText());

t.setText(String.valueOf((p-q))); }

else if(oper.equals("*")){

q=Integer.parseInt(t.getText());

t.setText(String.valueOf((p*q))); }

else if(oper.equals("%")){

q=Integer.parseInt(t.getText());

t.setText(String.valueOf((p%q))); }

else if(str.equals("C")){ p=0;q=0;

t.setText("");

str1="";

t.setText("0");

50
else{ t.setText(str1.concat(str));

str1=t.getText();

OUTPUT:

51
34. Write a java program for handling mouse events.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="MouseEvents" width=300 height=100>
</applet>

*/

public class MouseEvents extends Applet


implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;

52
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
sg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}

53
Output:

54
35. Write a java program to Demonstrating the life cycle of a tread.
class thread implements Runnable
{
public void run()
{
// moving thread2 to timed waiting state
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

System.out.println("State of thread1 while it called join() method on


thread2 -"+
Test.thread1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

public class Test implements Runnable


{
public static Thread thread1;
public static Test obj;

public static void main(String[] args)


{
obj = new Test();
thread1 = new Thread(obj);

// thread1 created and is currently in the NEW state.


System.out.println("State of thread1 after creating it - " +
thread1.getState());
thread1.start();

// thread1 moved to Runnable state


System.out.println("State of thread1 after calling .start() method on
it - " +
thread1.getState());
}

public void run()


{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);

55
// thread1 created and is currently in the NEW state.
System.out.println("State of thread2 after creating it - "+
thread2.getState());
thread2.start();

// thread2 moved to Runnable state


System.out.println("State of thread2 after calling .start() method on
it - " +
thread2.getState());

// moving thread1 to timed waiting state


try
{
//moving thread1 to timed waiting state
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 after calling .sleep() method on
it - "+
thread2.getState() );

try
{
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's
execution - " +
thread2.getState());
}

}
Output:
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on
it - RUNNABLE
State of thread2 after creating it - NEW

56
State of thread2 after calling .start() method on
it - RUNNABLE
State of thread2 after calling .sleep() method on
it - TIMED_WAITING
State of thread1 while it called join() method on
thread2 -WAITING
State of thread2 when it has finished it's
execution - TERMINATED

57

You might also like