Java Programs for Basic Conversions and Operations
Java Programs for Basic Conversions and Operations
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.
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:
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;
a=[Link]();
b=[Link]();
big=(a>b)?a:b;
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:
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
Statement 1 is executed (one time) before the execution of 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
{
int n,fact=1;
n=[Link]();
for(int i=1;i<=n;i++)
fact=fact*i;
RESULT:
Thus the Java program to find the factorial of a number has been executed successfully and
verified.
Page 7 of 46
[Link]:-4
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.
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.
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 −
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.
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.
15 boolean isEmpty()
Tests if this vector has no components.
16 Object lastElement()
Returns the last component of the vector.
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.
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.
PROGRAM:
import [Link];
class ChkPalindrome
[Link]("Enter a string:");
str = [Link]();
[Link](str+" is a palindrome");
else
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:
1. Register Number
2. Name
3. Marks in 3 subjects
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.
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]();
}
}
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:
DESCRIPTION:
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:
float r=[Link](args[0]);
float pi=3.14f;
Page 19 of 46
float area;
area=pi*r*r;
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();
}
}
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:
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:
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:
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
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().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
Page 27 of 46
PROGRAM:
class ThreadDemo
{
public static void main(String args[])
{
one a =new one();
two b=new two();
three c =new three();
[Link]();
[Link]();
[Link]();
}
}
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:
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.
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()
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.
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);
}
}
}
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:
DESCRIPTION:
There are two types of events that MouseMotionListener can generate. There are two abstract
functions that represent these five events.
The abstract functions are :
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
}
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:
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);
}
}
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:
DESCRIPTION:
methods used :
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;
class Calculator extends JFrame implements ActionListener
{
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
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]());
}
// 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);
[Link](200, 220);
[Link]();
}
public void actionPerformed(ActionEvent e)
{
String s = [Link]();
double 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;
// convert it to string
s0 = [Link](te);
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