0% found this document useful (0 votes)
71 views35 pages

OOPS Through Java Lab Manual - Student

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
71 views35 pages

OOPS Through Java Lab Manual - Student

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 35

ST.

ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA


(AUTONOMOUS)
ECE - UG – R22

Year &Sem III Year – I Semester


Course Code L T P SS C
Course Name OOPS through Java Lab 0 0 3 0 1.5

Course Outcomes: At the end of the course, students will be able to Knowledge
Level (K)#
CO1 Identify classes, objects, members of a class and the relationship among K3
them needed for a specific problem
CO2 Implement programs to distinguish different forms of inheritance K4
CO3 Create packages and to reuse them K3
CO4 Develop programs using Exception Handling mechanism K3
CO5 Develop multithreaded application using synchronization concept. K6
CO6 Design GUI based applications using Swings and AWT. K6
List of programs to be executed:
1. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are
1, 1Every subsequent value is the sum of the 2 values preceding it. Write a Java Program that
uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence.
2. Write a Java Program that prompts the user for an integer and then prints out all the prime
numbers upto that integer.
3. Write a java program to implement call by value and call by reference mechanisms.
4.Write a Java Program that checks whether a given string is a palindrome or not.
5.Write a Java Program to check the compatibility for multiplication, if compatible multiply
two matrices and find its transpose.
6.Write a Java program to implement constructor overloading and method overloading.
7.Write a Java Program that illustrates how run time polymorphism is achieved.
8.Write a Java Program that illustrates the use of super keyword.
9.Write a Java Program to create and demonstrate packages.
10.Write a Java Program, using String Tokenizer class, which reads a line of integers and
then display search integer and the sum of all integers.
11.Write a Java Program that reads on file name form the user 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 of the using File Input Stream class.
12.Write a Java Program that displays the number of characters, lines and words in a text/text
file.
13.Write a Java Program to implement a Queue, using user defined Exception Handling (also
make use ofthrow, throws).
14. Write a Java Program that creates 3 threads by extending Thread class. First thread
displays “Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds
and the third displays“Welcome”every 3 seconds. (Repeat the same by implementing
Runnable).
15.Write a Java Program demonstrating the life cycle of a thread.
16. Write an Applet that displays the content of a file.
17.Write a Java Program that works as a simple calculator. Use a gridlay out to arrange
buttons for the digits and for the +-*?% operations. Add a text field to display the result.
18.Writea Java Program for handling mouse events, keyboard events.
19. Write a Java Program that allows user to draw lines, rectangles and ovals.
20.Write a Java Program that lets users create Piecharts. Design your own user interface (with
Swings & AWT).
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

1. AIM: -The Fibonacci sequence is defined by the following rules: The first two values in the
sequence are 1and 1. Every subsequent values is the sum of the two values preceding it.
Write a java program that uses both recursive and non-recursive functions to print the nth
value in the Fibonacci sequence.

1.Fibonacci Series in Java without using recursion


class FibonacciExample1
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}

}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

II. Fibonacci Series using recursion in java


class FibonacciExample2{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

2. AIM: - Write a program that prompts the user for an integer and then prints out all prime
numbers up to that integer.

import java.io.*;
class Primenos
{
public static void main(String[] args) throws Exception
{
int n,fact;
System.out.println("Enter the range of Prime No U want");
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
System.out.println("Prime No's from 1 to "+n+" is");
for(int i=1;i<=n;i++)
{
fact=1;
for(int x=1;x<i;x++)
if(i%x==0)
fact++;
if(fact==2)
System.out.print(i+"\t");
}
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

3. AIM: -Write a java program to implement callbyvalue and call byreference mechanisms.

Call By Value

public class CallByValue{


public static void main(String[] args){
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

Call By Reference

public class CallByReference {


public static void main(String[] args) {
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
// Invoke the swap method
swapFunction(a, b);
System.out.println("**Now, Before and After swapping values will be different here**:");
System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
// Swap n1 with n2
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

4. AIM: - Write a Java Program that checks whether a given string is a palindrome or not.

PROGRAM: -

import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( inti = length - 1; i>= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

5. AIM: - Write a Java Program to check the compatibility for multiplication, if compatible
multiply two matrices and find its transpose.

PROGRAM: -

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: ");
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");
}
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

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)
{
Matrix obj = new Matrix();
obj.matrixMul(m,n,p,q);
}
else
{
System.out.println("Matrix multiplication cannot be performed...");
}
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

6. AIM: - Write a Java program to implement constructor overloading and method


overloading.

Constructor Overloading

public class Student {


//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

Method Overloading

// Java program to demonstrate working of method


// overloading in Java

public class MethodOverloading {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
MethodOverloading s = new MethodOverloading();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

7. AIM:- Write a Java Program that illustrates how runtime polymorphism is achieved

POLYMORPHISMEX-1

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

POLYMORPHISMEX-2

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

POLYMORPHISMEX-3

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

8. AIM: - Write a Java Program that illustrates the use of superkeyword.

PROGRAM-1

class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

PROGRAM-2

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

PROGRAM-3

class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

9. AIM: - Write a Java Program to create and demonstrate packages.

PROGRAM-1

// Name of package to be created


package FirstPackage;

// Class in which the above created package belong to


class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
System.out.println(
"This Is The First Program Geeks For Geeks..");
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

PROGRAM-2

// Name of package to be created


package data;

// Class to which the above package belongs


public class Demo {

// Member functions of the class- 'Demo'


// Method 1 - To show()
public void show()
{

// Print message
System.out.println("Hi Everyone");
}

// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

10. AIM: - Write a Java Program, using String Tokenizer class, which reads a line of integers
and then displays each integer and the sum of all integers.

PROGRAM

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();
StringTokenizerst = 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:-

11. AIM:- Write a Java Program that reads on file name form the user then displays
information about Whether the file exists, whether the file is readable/ writable, the type of
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

file and the length of the file in bytes and display the content of the using FileInputStream
class.

PROGRAM

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("");
FileInputStreamfis = 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(IOExceptioni)
{
System.out.println("Cannot read file...");
}
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

12. AIM:- Write a Java Program that displays the number of characters, lines and words in a
text/text file.

PROGRAM

import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStreamfis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
code = fis.read();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
System.out.println("No.of characters = "+chars);
System.out.println("No.of words = "+(words+1));
System.out.println("No.of lines = "+(lines+1));
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOExceptioni)
{
System.out.println("Cannot read file...");
}
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

13. AIM:- Write a Java Program to implement a Queue, using user defined Exception
Handling (also make use ofthrow, throws).

PROGRAM

import java.io.*;
class myException extends Exception
{ myException()
{ System.out.println("Error:Password too short");
}
myException(int n)
{ System.out.println("Error:Only adults can join");
}
}
class user_exception
{
public static void main(String s[]) throws IOException,myException
{ BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

try

{ System.out.print("Enter user name : ");

String n=br.readLine();

System.out.print("Enter your password : ");

String m=br.readLine();

if(m.length() <6)

throw new myException();

System.out.print("Enter your age : ");

int o=Integer.parseInt(br.readLine());

if(o<18)

throw new myException(o);

catch(Exception e)

{ }

OUTPUT :-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

14. AIM:- Write a Java Program that creates 3 threads by extending Thread class. First thread

displays “Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds
and
the third displays“Welcome”every 3 seconds. (Repeat the same by implementing Runnable).
PROGRAM

class ChildThread implements Runnable


{
Thread t;
ChildThread(String name)
{
t = new Thread(this, name);
t.start();
}
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
if(t.getName().equals("First Thread"))
{
Thread.sleep(1000);
System.out.println(t.getName()+": Good Morning");
}
else if(t.getName().equals("Second Thread"))
{
Thread.sleep(2000);
System.out.println(t.getName()+": Hello");
}
else
{
Thread.sleep(3000);
System.out.println(t.getName()+": Welcome");
}
}
catch(InterruptedException e)
{
System.out.println(t.getName()+" is interrupted");
}
}
}
}
class ThreeThreads
{
public static void main(String args[])
{
ChildThread one = new ChildThread("First Thread");
ChildThread two = new ChildThread("Second Thread");
ChildThread three = new ChildThread("Third Thread");
}
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

OUTPUT :-
15. AIM:- Write a Java Program demonstrating the life cycle of a thread.

PROGRAM

import java.util.*;
class ChildThread implements Runnable
{
Thread t;
ChildThread()
{
t = new Thread(this);
System.out.println("Thread is in new state");
t.start();
}
public void run()
{
System.out.println("Thread is in runnable state");
Scanner s = new Scanner(System.in);
System.out.println("Thread entering blocked state");
System.out.print("Enter a string: ");
String str = s.next();
for(int i = 1; i<= 3; i++)
{
try
{
System.out.println("Thread suspended");
t.sleep(1000);
System.out.println("Thread is running");
}
catch(InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println("Thread terminated");
t.stop();
}
}
}
class Driver
{
public static void main(String[] args)
{
new ChildThread();
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

16. Aim: Write an Applet that displays the content of a file

PROGRAM :

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("");
FileInputStreamfis = 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(IOExceptioni)
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
/*
<applet code="MyApplet" height="300" width="500">
</applet>
*/

OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

17. Aim: 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

PROGRAM :

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}

OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

18. AIM: Write a Java Program for handling mouse events, keyboard events.

PROGRAM :

// demonstrate the mouse event handlers.


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,MouseWheelListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";

repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

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();
msg = "*";
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());
}
// Handle mouse wheel moved.
public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving 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);
}
}

OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

19. AIM :Write a Java Program that allows user to draw lines, rectangles and ovals.

PROGRAM :

import java.applet.*;
import java.awt.*;
import javax.swing.*;

/*

<applet code="Lro" height="400" width="500" border="1">

</applet>

*/

public class Lro 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);
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

20. AIM :Write a Java Program that lets users create Piecharts. Design your own user
interface (with Swings & AWT).

PROGRAM :

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

/*<applet code=PiChart.class width=600 height=600></applet>*/

public class PiChart extends Applet


{
public void paint(Graphics g)
{

setBackground(Color.green);
g.drawString("PI CHART",200,40);
g.setColor(Color.blue);
g.fillOval(50,50,150,150);
g.setColor(Color.white);
g.drawString("40%",130,160);
g.setColor(Color.magenta);
g.fillArc(50,50,150,150,0,90);
g.setColor(Color.white);
g.drawString("25%",140,100);
g.setColor(Color.yellow);
g.fillArc(50,50,150,150,90,120);
g.setColor(Color.black);
g.drawString("35%",90,100);
g.setColor(Color.yellow);
g.fillOval(250,50,150,150);
g.setColor(Color.black);
g.drawString("15%",350,150);
g.setColor(Color.magenta);
g.fillArc(250,50,150,150,0,30);
g.setColor(Color.black);
g.drawString("5%",360,120);
g.setColor(Color.blue);
g.fillArc(250,50,150,150,30,120);
g.setColor(Color.white);
g.drawString("30%",330,100);
g.setColor(Color.black);
g.fillArc(250,50,150,150,120,180);
g.setColor(Color.white);
g.drawString("50%",280,160);
}
}

OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22

You might also like