0% found this document useful (0 votes)
21 views46 pages

Java Programs for Basic Conversions and Operations

The document outlines a series of Java programming exercises, including converting Celsius to Fahrenheit, finding the largest of two numbers, calculating the factorial of a number, implementing a Vector class, checking for palindromes, creating a class with constructors, and calculating the area of a circle using command line arguments. Each exercise includes an aim, algorithm, description, and a sample program demonstrating the implementation. The results confirm that all programs have been executed and verified successfully.

Uploaded by

shanthis57525
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views46 pages

Java Programs for Basic Conversions and Operations

The document outlines a series of Java programming exercises, including converting Celsius to Fahrenheit, finding the largest of two numbers, calculating the factorial of a number, implementing a Vector class, checking for palindromes, creating a class with constructors, and calculating the area of a circle using command line arguments. Each exercise includes an aim, algorithm, description, and a sample program demonstrating the implementation. The results confirm that all programs have been executed and verified successfully.

Uploaded by

shanthis57525
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EX.

NO:-1
DATE:- CELSIUS TO FAHRENHEIT CONVERSION
______________________________________________________________________________
AIM:
To write a Java program to read the temperature in Celsius and convert into Fahrenheit.
ALGORITHM:
1. Read value of celsius.
2. Calculate the Fahrenheit using the formula
Fahrenheit=celsius*9/5+32
3. Display the value of Fahrenheit.
DESCRIPTION:
Java User Input
The Scanner class is used to get user input, and it is found in the [Link] package.
To use the Scanner class, create an object of the class and use any of the available methods found
in the Scanner .
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
[Link] in Java
Java [Link]() is used to print an argument that is passed to it. The statement can be
broken into 3 parts which can be understood separately as:
System: It is a final class defined in the [Link] package.
out: This is an instance of PrintStream type, which is a public and static member field of the
System class.

Page 1 of 46
println(): As all instances of PrintStream class have a public method println(), hence we can
invoke the same on out as well. This is an upgraded version of print(). It prints any argument
passed to it and adds a new line to the output. We can assume that [Link] represents the
Standard Output Stream.
Syntax:
[Link](parameter);
Parameters: The parameter might be anything that the user wishes to print on the output screen.

PROGRAM:
import [Link];
class Cel_to_Far
{
public static void main(String args[])
{
float cel, far;
Scanner s=new Scanner([Link]);
[Link]("Enter temperature in Celsius:");
cel=[Link]();
far=cel*9/5+32;
[Link]("Temperature in Fahrenheit:"+far);
}
}

Page 2 of 46
INPUT AND OUTPUT:

RESULT:
Thus the Java program to covert Celsius to Fahrenheit has been executed successfully and
verified.

Page 3 of 46
[Link]:-2
DATE:- LARGEST OF TWO NUMBERS
______________________________________________________________________________
AIM:
To write a Java program to read two integers and find the largest number using conditional
operator.

ALGORITHM:
1. Read first number a.

2. Read second number b.

3. Computer largest of two numbers using conditional operator

Big=(a>b)?a:b;

4. Display Big.

DESCRIPTION:

Conditional/Ternary Operator

The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three
operands. It is used to evaluate Boolean expressions. The operator decides which value will be
assigned to the variable. It is the only conditional operator that accepts three operands. It can be
used instead of the if-else statement.

Syntax:

variable = (condition) ? expression1 : expression2

The above statement states that if the condition returns true, expression1 gets executed, else the
expression2 gets executed and the final result stored in a variable.

PROGRAM:

import [Link];

class Big_of_Two

Page 4 of 46
public static void main(String args[])

int a,b,big;

Scanner s=new Scanner([Link]);

[Link]("Enter the first number:");

a=[Link]();

[Link]("Enter the Second number:");

b=[Link]();

big=(a>b)?a:b;

[Link]("Largest of the given two numbers is "+big);

INPUT AND OUTPUT:

RESULT:
Thus the Java program to find the largest of two integers using conditional operator has been
executed successfully and verified.

Page 5 of 46
[Link]:-3
DATE:- FACTORIAL OF A NUMBER
______________________________________________________________________________
AIM:
To write a Java program to read two integers and find the largest number using conditional
operator.
ALGORITHM:
1. Read a number from User , n.
2. Initialize Variable Fact=1 and i=1.
3. Repeat Until i<=n
3.1 Fact=Fact*i
3.2 i=i+1
[Link] Fact
DESCRIPTION:

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:

Syntax

for (statement 1; statement 2; statement 3)

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

PROGRAM:

import [Link];

class Factorial

Page 6 of 46
{

public static void main(String args[])

int n,fact=1;

Scanner s=new Scanner([Link]);

[Link]("Enter a number to find the factorial:");

n=[Link]();

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

fact=fact*i;

[Link]("Factorial of the given number is "+fact);

INPUT AND OUTPUT:

RESULT:

Thus the Java program to find the factorial of a number has been executed successfully and
verified.

Page 7 of 46
[Link]:-4

DATE:- VECTOR CLASS & ITS METHODS


______________________________________________________________________________
AIM:
To write a Java program to implement Vector Class and its methods.

DESCRIPTION:
Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Following is the list of constructors provided by the vector class.

[Link] Constructor & Description


.

1 Vector( )
This constructor creates a default vector, which has an initial size of 10.

2 Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size.

3 Vector(int size, int incr)


This constructor creates a vector whose initial capacity is specified by size and
whose increment is specified by incr. The increment specifies the number of
elements to allocate each time that a vector is resized upward.

4 Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

Page 8 of 46
Vector defines the following methods −

[Link] Method & Description


.

1 void add(int index, Object element)


Inserts the specified element at the specified position in this Vector.

2 boolean add(Object o)
Appends the specified element to the end of this Vector.

3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector,
in the order that they are returned by the specified Collection's Iterator.

4 boolean addAll(int index, Collection c)


Inserts all of the elements in in the specified Collection into this Vector at the
specified position.

5 void addElement(Object obj)


Adds the specified component to the end of this vector, increasing its size by
one.

6 int capacity()
Returns the current capacity of this vector.

7 void clear()
Removes all of the elements from this vector.

8 Object clone()
Returns a clone of this vector.

Page 9 of 46
9 boolean equals(Object o)
Compares the specified Object with this vector for equality.

10 Object firstElement()
Returns the first component (the item at index 0) of this vector.

11 Object get(int index)


Returns the element at the specified position in this vector.

12 int indexOf(Object elem)


Searches for the first occurence of the given argument, testing for equality using
the equals method.

13 int indexOf(Object elem, int index)


Searches for the first occurence of the given argument, beginning the search at
index, and testing for equality using the equals method.

14 void insertElementAt(Object obj, int index)


Inserts the specified object as a component in this vector at the specified index.

15 boolean isEmpty()
Tests if this vector has no components.

16 Object lastElement()
Returns the last component of the vector.

17 int lastIndexOf(Object elem)


Returns the index of the last occurrence of the specified object in this vector.

18 int lastIndexOf(Object elem, int index)


Searches backwards for the specified object, starting from the specified index,
and returns an index to it.

Page 10 of 46
19 Object remove(int index)
Removes the element at the specified position in this vector.

20 boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the vector
does not contain the element, it is unchanged.

21 boolean removeAll(Collection c)
Removes from this vector all of its elements that are contained in the specified
Collection.

22 void removeAllElements()
Removes all components from this vector and sets its size to zero.

23 boolean removeElement(Object obj)


Removes the first (lowest-indexed) occurrence of the argument from this vector.

24 void removeElementAt(int index)


removeElementAt(int index).

25 Object set(int index, Object element)


Replaces the element at the specified position in this vector with the specified
element.

26 void setElementAt(Object obj, int index)


Sets the component at the specified index of this vector to be the specified
object.

27 void setSize(int newSize)


Sets the size of this vector.

28 int size()
Returns the number of components in this vector.

Page 11 of 46
PROGRAM:
import [Link].*;
public class VectorExample
{
public static void main(String args[])
{
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
//Adding elements using addElement() method of Vector
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
[Link]("Elements are: "+vec);
int s,c;
s=[Link]();
c=[Link]();
[Link]("Size of vector is :"+s);
[Link]("Capacity of vector is :"+c);
[Link]("Camel",2);
[Link]("Elements are: "+vec);
[Link]("Cow",4);
[Link]("New Vector after inserting 2 elements:");
[Link]("Elements are: "+vec);
[Link]("Size of vector is :"+s);
[Link]("Capacity of vector is :"+c);
[Link]("Dog");
[Link]("New Vector after deleting element Dog");
[Link]("Elements are: "+vec);
[Link]("Size of vector is :"+s);
[Link]("Capacity of vector is :"+c);
}
}
Page 12 of 46
INPUT AND OUTPUT:

RESULT:

Thus the Java program to implement Vector Class and its methods has been executed and
verified successfully.

Page 13 of 46
[Link]:-5
DATE:- PALINDROME CHECKING
______________________________________________________________________________
AIM:

To write a java program to read a string and check whether it is a palindrome or not.

ALGORITHM:

A palindrome is a string, which, when read in both forward and backward ways is the same.

1. Read a string str.


2. Store the reverse of the given string in rev.
3. Compare str with rev.
If both are same then
Display given string is Palindrome
Otherwise
Display given string is Not Palindrome

PROGRAM:

import [Link];

class ChkPalindrome

public static void main(String args[])

String str, rev = "";

Scanner sc = new Scanner([Link]);

[Link]("Enter a string:");

str = [Link]();

int length = [Link]();

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

rev = rev + [Link](i);


Page 14 of 46
if ([Link](rev))

[Link](str+" is a palindrome");

else

[Link](str+" is not a palindrome");

INPUT AND OUTPUT:

RESULT:

Thus a java program to read a string and check whether it is a palindrome or not had been
executed and verified successfully.
Page 15 of 46
[Link]:-6
DATE:- CREATING A CLASS WITH CONSTRUCTORS
______________________________________________________________________________
AIM:

To write a java program to create a class with following Data members.

1. Register Number

2. Name

3. Marks in 3 subjects

and member functions:

1. Parameterized constructor - to assign values to members

2. Method to find total mark

3. Method to display register number, name, total mark.

Also to create 3 objects for the above class and use the members.

DESCRIPTION:

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:


o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>
{
field;
method;
}

Page 16 of 46
PROGRAM:

//Program No:6
import [Link];
class Student
{
int register_number;
String name;
int marks[]=new int[3];
Student(int rno, String n, int[] m) //Parameterised constructor
{
register_number=rno;
name=n;
for(int i=0;i<3;i++)
{
marks[i]=m[i];
}
}
int total_marks() //method to find total marks
{
int total;
total=marks[0]+marks[1]+marks[2];
return(total);
}
void display()
{
[Link]("Register Number: "+ register_number);
[Link]("Name: "+ name);
int t=total_marks();
[Link]("Total marks : "+t);
}
}
public class StudentClass
{
public static void main(String args[])
{
int[] m1={50,60,70};
int[] m2={100,90,75};
int[] m3={90,85,90};
Student s1=new Student(100,"Arun",m1);
Student s2=new Student(101,"Babu",m2);
Student s3=new Student(102,"Charles",m3);
[Link]("Register number Name Total marks ");
Page 17 of 46
[Link]();
[Link]();
[Link]();
}
}

INPUT AND OUTPUT:

RESULT:

Thus the Java program to create a class has been executed and verified successfully.

Page 18 of 46
[Link]:-7
DATE:- AREA OF A CIRCLE USING COMMAND LINE ARGUMENT
______________________________________________________________________________
AIM:

To write a Java program that accepts radius of a circle from command line and display its area.

ALGORITHM:

1. Read radius R from command Line.


2. Calculate area of a circle using the formula.
Area=22/7*R*R
3. Display area of the circle.

DESCRIPTION:

Java Command Line Arguments

The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be used as
an input.

So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

PROGRAM:

//Area of the circle using Command Line Argument

public class Area_of_Circle

public static void main(String args[])

float r=[Link](args[0]);

float pi=3.14f;
Page 19 of 46
float area;

area=pi*r*r;

[Link]("Area of the circle is "+area);

INPUT AND OUTPUT:

RESULT:

Thus the Java program that accepts radius of a circle from command line and display its area has
been executed and verified successfully.

Page 20 of 46
[Link]:-8
DATE:- MULTILEVEL INHERITANCE
______________________________________________________________________________
AIM:
To write a java program to implement multilevel inheritance.
DESCRIPTION:
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class. In the below
image, class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

1 class A
2
3 {
4
5 }
6
7 class B extends A
8
9 {
1
0 }
1
1 class C extends B
1
2 {
1
3 }
1
4
1
5
1
6
1
Page 21 of 46
7
Suppose, we have a form as shown above (class A is the parent of class B and class B is the
parent of class C), then features of A are available for B, and features of B (including that of A)
are available for C. So, class C get features of both A and B.
In this case, class B is the parent to C and child to A. such classes are generally known as
intermediate classes. When an object of class C is created, constructors of all the three classes
will be executed.
Even though the control goes to the constructor of C first, the actual sequence of execution will
be the constructor of A first, the constructor of B next and constructor of C at last.

PROGRAM:
//PROGRAM TO IMPLEMENT MUTLILEVEL INHERITANCE
import [Link].*;
class Vehicle
{
String regno;
int model;
String make;
Vehicle(String r,int m, String n)
{
regno=r;
model=m;
make=n;
}
void display()
{
[Link]("Registration number="+regno);
[Link]("Model="+model);
[Link]("Manufacturer="+make);
}
}
class twowheeler extends Vehicle
{
int nogear;
int power;
twowheeler(String a, int b, String c, int g, int p)
{
super(a,b,c);
nogear=g;
power=p;
}
void print()
{
[Link]("Number of gears="+nogear);
[Link]("Power="+power);
}
}
Page 22 of 46
class bike extends twowheeler
{
String owner;
bike(String x,int y, String z, int x1, int x2, String x3)
{
super(x,y,z,x1,x2);
owner=x3;
}
void print1()
{
[Link]("Owner="+owner);
}
}
class VehicleDemo
{
public static void main(String args[])
{
bike b1=new bike("tn32k1111",2022,"TVS",5,125,"XXXX");
[Link]();
[Link]();
b1.print1();
}
}

INPUT AND OUTPUT:

RESULT:-

Page 23 of 46
Thus the java program to implement multilevel inheritance is executed successfully and
output is verified.

[Link]:-9
DATE:- USER DEFINED EXCEPTION
______________________________________________________________________________
AIM:
To write a java program to create a own exception subclass that throws exception if the
given number is not in a range of numbers.

DESCRIPTION:

User-defined Custom Exception in Java


An exception is an issue (run time error) that occurred during the execution of a program. When
an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according to
user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.

Why use custom exceptions?

Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Following are a few of the reasons to use custom exceptions:
 To catch and provide specific treatment to a subset of existing Java exceptions.
 Business logic exceptions: These are the exceptions related to business logic and workflow.
It is useful for the application users or the developers to understand the exact problem.
In order to create a custom exception, we need to extend the Exception class that belongs
to [Link] package.

PROGRAM:

// PROGRAM TO CREATE OWN EXCEPTION


import [Link].*;
class RangeException extends Exception // user defined exception
{
RangeException(String e)
{
Page 24 of 46
super(e);
}
}
public class OutRange
{
public static void main(String args[])
{
int a=0,b=700,n;
try
{
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter any number:");
n=[Link]([Link]());
if(n<a||n>b) throw new RangeException("Number out of range");
[Link]("The given number "+n+" is in the range of numbers
"+a+" and "+b);
}
catch(RangeException s) //catching user defined exception
{
[Link](s);
}
catch(IOException e)
{
[Link](e);
}
}
}
INPUT AND OUTPUT:

RESULT:-
Page 25 of 46
Thus a java program to create own exception subclass that throw exception if the given
number is not in a range of numbers is executed successfully and verified.

[Link]:-10
DATE:- USER DEFINED THREADS
______________________________________________________________________________
AIM:
To write a java program that creates three threads. First thread displays “Good Morning”
everyone second, the second thread displays “Hello” every two seconds and the third thread
displays “Welcome” every three seconds.

DESCRIPTION:

Java Threads:

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the [Link] calls the run() method on the
thread.

Page 26 of 46
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public int getPriority(): returns the priority of the thread.
5. public int setPriority(int priority): changes the priority of the thread.
6. public String getName(): returns the name of the thread.
7. public void setName(String name): changes the name of the thread.
8. public Thread currentThread(): returns the reference of currently executing thread.
9. public int getId(): returns the id of the thread.
10. public [Link] getState(): returns the state of the thread.
11. public boolean isAlive(): tests if the thread is alive.
12. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
13. public void suspend(): is used to suspend the thread(depricated).
14. public void resume(): is used to resume the suspended thread(depricated).
15. public void stop(): is used to stop the thread(depricated).

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Page 27 of 46
PROGRAM:

class one extends Thread


{
public void run()
{
try
{
sleep(1000);
[Link]("Good Morning");
}
catch(Exception e)
{
[Link](e);
}
}
}
class two extends Thread
{
public void run()
{
try
{
sleep(2000);
[Link]("Hello");
}
catch(Exception e)
{
[Link](e);
}
}
}
class three extends Thread
{
public void run()
{
try
{
sleep(3000);
[Link]("Welcome");
}
catch(Exception e)
{
[Link](e);
Page 28 of 46
}
}
}

class ThreadDemo
{
public static void main(String args[])
{
one a =new one();
two b=new two();
three c =new three();
[Link]();
[Link]();
[Link]();

}
}

INTPUT AND OUTPUT:

Page 29 of 46
RESULT:

Thus a java program to create three threads is written, executed and verified successfully.

[Link]:-11
DATE:- FILE CREATION USING BYTE STRAEM CLASS
______________________________________________________________________________
AIM:

To write a java program to create a file using Byte stream or Character stream class.

DESCRIPTION:

Byte Streams in Java


These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using
these you can store characters, videos, audios, images etc.
The InputStream and OutputStream classes (abstract) are the super classes of all the input/output
stream classes: classes that are used to read/write a stream of bytes. Following are the byte array
stream classes provided by Java −

InputStream OutputStream

FIleInputStream FileOutputStream

ByteArrayInputStream ByteArrayOutputStream

ObjectInputStream ObjectOutputStream

PipedInputStream PipedOutputStream

FilteredInputStream FilteredOutputStream

BufferedInputStream BufferedOutputStream

DataInputStream DataOutputStream

InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

[Link]. Method with Description

1 int available()

Page 30 of 46
[Link]. Method with Description

It returns the number of bytes that can be read from the input stream.

2 int read()

It reads the next byte from the input stream.

3 int read(byte[] b)

It reads a chunk of bytes from the input stream and store them in its byte array, b.

4 void close()

It closes the input stream and also frees any resources connected with this input stream.

OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

[Link]. Method with Description

1 void write(int n)
It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.

3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.

4 void close()
It closes the output stream and also frees any resources connected with this output stream.

PROGRAM:

import [Link].*;
class FileDemo
{
Page 31 of 46
public static void main(String args[])
{
try
{
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter the data to write:");
String s=[Link]();
FileOutputStream fout=new FileOutputStream("[Link]");
byte b[]=[Link]();
[Link](b);
[Link]("File created successfully");
[Link]();
}
catch(IOException e)
{
[Link](e);
}
}
}

INPUT AND OUTPUT:

RESULT:
Page 32 of 46
Thus the java program to create a file using Byte stream is executed successfully and
verified.

[Link]:-12
DATE:- MOUSE EVENTS
______________________________________________________________________________
AIM:

To write a java program to demonstrate Mouse Events.

DESCRIPTION:

MouseListener and MouseMotionListener in Java


MouseListener and MouseMotionListener is an interface in [Link] package . Mouse
events are of two types. MouseListener handles the events when the mouse is not in motion.
While MouseMotionListener handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract functions
that represent these five events.
The abstract functions are :

1. void mouseReleased(MouseEvent e) : Mouse key is released


2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousepressed(MouseEvent e) : Mouse key is pressed

There are two types of events that MouseMotionListener can generate. There are two abstract
functions that represent these five events.
The abstract functions are :

1. void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the


component and dragged. Events are passed until the user releases the mouse button.
2. void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one
point to another within the component, without pressing any mouse buttons.

PROGRAM:

/*
<applet code="[Link]" width=300 height=200>
</applet>*/
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseMotionDemo extends Applet implements

Page 33 of 46
MouseListener,MouseMotionListener
{
String msg="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
Font f1=new Font("Arial",[Link],20);
[Link](f1);
[Link](msg,100,50);
}
public void mousePressed(MouseEvent e)
{
msg="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
msg="MouseReleased";
repaint();
}
public void mouseClicked(MouseEvent e)
{
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
msg="Mouse Exited";
repaint();
}
public void mouseMoved(MouseEvent e)
{
msg="Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e)
{
msg="Mouse Dragged";
repaint();
}
Page 34 of 46
}

INPUT AND OUTPUT:

RESULT:

Thus the java program to demonstrate mouse events is executed successfully and
verified.

Page 35 of 46
[Link]:-13
DATE:- BASIC SHAPES USING GRAPHICS CLASS
______________________________________________________________________________
AIM:

To write a java program to display basic shapes using Graphics class and fill them using
Color class.

DESCRIPTION:

Displaying Graphics in Applet


[Link] class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw
the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used
to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used
to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

Page 36 of 46
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
[Link] abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
[Link] abstract void setFont(Font font): is used to set the graphics
current font to the specified font.

PROGRAM:

import [Link];
import [Link].*;
/* <applet code="[Link]" width="300" height="300">
</applet> */
public class GraphicsDemo extends Applet
{
Color c1=new Color(255,0,0);
Color c2=new Color(0,255,0);
Color c3=new Color(0,0,255);
Color c4=new Color(255,0,255);
Color c5=new Color(255,255,0);
Color c6=new Color(0,255,255);
Color c7=new Color(100,100,100);
public void paint(Graphics g)
{
[Link](c1);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](c2);
[Link](70,100,30,30);
[Link](c3);
[Link](170,100,30,30);
[Link](c4);
[Link](70,200,30,30);
[Link](c5);
[Link](170,200,30,30);
[Link](c6);
[Link](90,150,30,30,30,270);
[Link](c7);

Page 37 of 46
[Link](270,150,30,30,0,180);

}
}

INPUT AND OUTPUT:

RESULT:

Thus the java program to display basic shapes using Graphics class and fill them using
Color class is executed successfully and verified.

Page 38 of 46
Page 39 of 46
[Link]:-14
DATE:- CALCULATOR
______________________________________________________________________________
AIM:

To write a java program to create a simple calculator to perform addition, subtraction,


multiplication and division using button, label and text field.

DESCRIPTION:

Java Swing | Simple Calculator


Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of
Oracle’s Java foundation classes . Java Swing is an API for providing graphical user interface
elements to Java [Link] was created to provide more powerful and flexible
components than Java AWT (Abstract Window Toolkit).

methods used :

1. add(Component c) : adds component to container.


2. addActionListenerListener(ActionListener d) : add actionListener for specified
component
3. setBackground(Color c) : sets the background color of the specified container
4. setSize(int a, int b) : sets the size of container to specified dimensions.
5. setText(String s) : sets the text of the label to s.
6. getText() : returns the text of the label.

PROGRAM:

// Java program to create a simple calculator


// with basic +, -, /, * using java swing elements

import [Link].*;
import [Link].*;
import [Link].*;
class Calculator extends JFrame implements ActionListener
{
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

Page 40 of 46
// default constructor
Calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try
{
// set look and feel

[Link]([Link]());
}
catch (Exception e)
{
[Link]([Link]());
}

// create a object of class


Calculator c = new Calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
[Link](false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
Page 41 of 46
bm = new JButton("*");
beq = new JButton("C");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
// add action listeners
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);
[Link](c);

// add elements to panel


[Link](l);
[Link](ba);
[Link](b1);
[Link](b2);
[Link](b3);
[Link](bs);
[Link](b4);
[Link](b5);
[Link](b6);
[Link](bm);
[Link](b7);
[Link](b8);
[Link](b9);
[Link](bd);
[Link](be);
[Link](b0);
[Link](beq);
[Link](beq1);

// set Background of panel


[Link]([Link]);

// add panel to frame


Page 42 of 46
[Link](p);

[Link](200, 220);
[Link]();
}
public void actionPerformed(ActionEvent e)
{
String s = [Link]();

// if the value is a number


if (([Link](0) >= '0' && [Link](0) <= '9') || [Link](0) == '.')
{
// if operand is present then add to second no
if (![Link](""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


[Link](s0 + s1 + s2);
}
else if ([Link](0) == 'C')
{
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


[Link](s0 + s1 + s2);
}
else if ([Link](0) == '=')
{

double te;

// store the value in 1st


if ([Link]("+"))
te = ([Link](s0) + [Link](s2));
else if ([Link]("-"))
te = ([Link](s0) - [Link](s2));
else if ([Link]("/"))
te = ([Link](s0) / [Link](s2));
else
te = ([Link](s0) * [Link](s2));

// set the value of text


[Link](s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = [Link](te);
Page 43 of 46
s1 = s2 = "";
}
else
{
// if there was no operand
if ([Link]("") || [Link](""))
s1 = s;
// else evaluate
else
{
double te;

// store the value in 1st


if ([Link]("+"))
te = ([Link](s0) + [Link](s2));
else if ([Link]("-"))
te = ([Link](s0) - [Link](s2));
else if ([Link]("/"))
te = ([Link](s0) / [Link](s2));
else
te = ([Link](s0) * [Link](s2));

// convert it to string
s0 = [Link](te);

// place the operator


s1 = s;

// make the operand blank


s2 = "";
}

// set the value of text


[Link](s0 + s1 + s2);
}
}
}

Page 44 of 46
INPUT AND OUTPUT:

RESULT:

Thus the java program to create a simple calculator is executed successfully and verified.

Page 45 of 46
Page 46 of 46

You might also like