B-TechIIYearIISemester[R22] Java
Programming Lab Manual JNTU
Hyderabad (JNTUH)
Use eclipse or Netbean platform and acquaint with the various menus, create a test project,
add a test class and run it see how you can use auto suggestions, auto fill. Try code formatter
and code refactoring like renaming variables, methods and classes. Try debug step by step
with a smallprogramofabout 10 to 15 lineswhich containsat least one ifelse condition and a for
loop.
Aim:
Use eclipse or Netbean platform and acquaint with the various menus, create a test project, add atest
class and run it see how you can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods and classes. Try debug step by step with a small
programof about 10to 15 lines which contains at least one if else condition and a for loop.
SourceCode:
//Importing packages
[Link];
[Link];
//CreatingClass
classSample_Program{
//mainmethod
publicstaticvoidmain(Stringargs[]){ int
i,count=0,n;
//creatingscannerobject
Scannersc=newScanner([Link]);
// get input number from user
[Link]("EnterAnyNumber:");
n=[Link]();
//logictocheckprimeornot
for(i=1;i<=n;i++) {
if(n%i==0){
count++;
}
}
if(count==2)
[Link](n+"isprime");
else
[Link](n+"isnotprime");
}
}
Output:
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 textfield to display the result. Handleany
possible exceptions like divided by zero.
Aim:
Write a Java programthat 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. Handle any possible
exceptions like divided by zero.
SourceCode:
/*ProgramtocreateaSimpleCalculator*/
import [Link].*;
[Link].*;
import [Link].*;
import [Link].*;
/*
<appletcode="MyCalculator"width=300height=300>
</applet>
*/
publicclassMyCalculatorextendsAppletimplementsActionListener{ int
num1,num2,result;
TextFieldT1;
ButtonNumButtons[]=newButton[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=newTextField(30);
[Link](newFlowLayout([Link]));
[Link](T1);
CPanel=new Panel();
[Link]([Link]);
[Link](newGridLayout(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("=");
[Link](this);
for(int i=0;i<10;i++) {
[Link](NumButtons[i]);
}
[Link](Add);
[Link](Sub);
[Link](Mul);
[Link](Div);
[Link](EQ);
SPanel=newPanel();
[Link](newFlowLayout([Link]));
[Link]([Link]);
[Link](clear);
for(inti=0;i<10;i++){
NumButtons[i].addActionListener(this);
}
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](new BorderLayout());
add(nPanel,[Link]);
add(CPanel,[Link]);
add(SPanel,[Link]);
}
publicvoidactionPerformed(ActionEventae)
{ String str=[Link] ();
char ch=[Link](0);
if([Link](ch))
[Link]([Link]()+str);
else
if([Link]("+")){
num1=[Link]([Link]());
Operation='+';
[Link]("");
}
if([Link]("-"))
{ num1=[Link]([Link]()
); Operation='-';
[Link]("");
}
if([Link]("*"))
{ num1=[Link]([Link]());
Operation='*';
[Link]("");
}
if([Link]("/"))
{ num1=[Link]([Link]());
Operation='/';
[Link]("");
}
if([Link]("%"))
{ num1=[Link]([Link]());
Operation='%';
[Link]("");
}
if([Link]("=")) {
num2=[Link]([Link]());
switch(Operation)
{
case'+':result=num1+num2;
break;
case'-':result=num1-num2;
break;
case'*':result=num1*num2;
break;
case'/':try{
result=num1/num2;
}
catch(ArithmeticExceptione){
result=num2;
[Link](this,"Dividedbyzero");
}
break;
}
[Link](""+result);
}
if([Link]("clear")){
[Link]("");
}
}
}
Output:
DevelopanappletinJavathatdisplaysasimplemessage.
Aim:
a) DevelopanappletinJavathatdisplaysasimplemessage.
SourceCode:
/*Developaappletto displaythesimplemessage*/
import [Link].*;
[Link].*;
/*<appletcode="FirstApplet"width=400height=300></applet>*/ public
class FirstApplet extends Applet {
publicvoidpaint(Graphicsg){
[Link]([Link]);
Fontfont=newFont("Arial",[Link],16);
[Link](font);
[Link]("ThisisMyFirstApplet",60,110);
}
}
Output:
Develop an applet in Java that receives an integer in one text field, and computes its factorial
Value and returns it in another text field, when the button named “Compute” is clicked.
Aim:
b) Developanappletin Javathatreceivesanintegerin onetextfield,andcomputesitsfactorial Value and
returns it in another text field, when the button named “Compute” is clicked.
SourceCode:
Aim:
b)DevelopanappletinJavathatreceivesanintegerinonetextfield,andcomputesitsfactorial Value and
returns it in another text field, when the button named “Compute” is clicked.
SourceCode:
/**Developapplet tofind factorialofthegivennumber*/
import [Link].*;
import [Link].*;
[Link].*;
/*<appletcode="FactorialApplet"width=500height=250>
</applet>*/
publicclassFactorialAppletextendsAppletimplementsActionListener{ Label
L1,L2;
TextFieldT1,T2;
Button B1;
publicvoidinit(){
L1=newLabel("EnteranyNumber:");
add(L1);
T1=newTextField(10);
add(T1);
L2=newLabel("FactorialofNum:");
add(L2);
T2=newTextField(10);
add(T2);
B1=newButton("Compute");
add(B1);
[Link](this);
}
publicvoidactionPerformed(ActionEvente){
if([Link]()==B1)
{
intvalue=[Link]([Link]());
int fact=factorial(value);
[Link]([Link](fact));
}
}
intfactorial(intn){
if(n==0)
return1;
else
returnn*factorial(n-1);
}
}
Output:
Write a Java program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is
displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an
integer, the program would throw a Number Format Exception. If Num2 were Zero, the
program would throw an Arithmetic Exception. Display the exception in a message dialogbox.
Aim:
Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is displayed in the
Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program
would throw a Number Format Exception. If Num2 were Zero, the program would throw an
Arithmetic Exception. Display the exception in a message dialog box.
SourceCode:
/*Developanappletto performdivision*/
import [Link].*;
import [Link].*;
[Link].*;
import [Link].*;
/*<appletcode="DivisionApplet"width=600height=200>
</applet>*/
publicclassDivisionAppletextendsApplet implementsActionListener{ Label
L1,L2,L3;
TextFieldT1,T2,Result;
Button B1;
publicvoidinit(){
L1=newLabel("EnterFirstNum:");
add(L1);
T1=newTextField(10);
add(T1);
L2=newLabel("EnterSecondNum:");
add(L2);
T2=newTextField(10);
add(T2);
L3=newLabel("result");
add(L3);
Result=newTextField(10);
add(Result);
B1=new Button("Divide");
add(B1);
[Link](this);
}
publicvoidactionPerformed(ActionEvente)
{ if([Link]()==B1) {
try{
intvalue1=[Link]([Link]());
intvalue2=[Link]([Link]());
int result=value1/value2;
[Link]([Link](result));
}
catch(NumberFormatException nfe)
{ [Link](this,"Notanumber");
}
catch(ArithmeticException ae)
{ [Link](this,"DividedbyZero");
}
}
}
}
Output:
Write a Java program that implements a multi-thread application that has three [Link]
thread generates random integer every 1 second and if the value is even, second thread
computes the square of the number and prints. If the value is odd, the third thread will print
the value of cube of the number.
Aim:
Write a Java programthat implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes thesquare
of the number and prints. If the value is odd, the third thread will print the value of cube of the
number.
SourceCode:
Aim:
Write a Java programthat implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes thesquare
of the number and prints. If the value is odd, the third thread will print the value of cube of the
number.
SourceCode:
[Link].*;
//classforEvenNumber
classEvenNumimplementsRunnable{ publi
c int a;
publicEvenNum(inta)
{ this.a = a;
}
publicvoidrun(){
[Link]("TheThread"+a+" isEVENandSquareof"+a+"is:"+a*a);
}
}//class forOddNumber
classOddNumimplementsRunnable{ public
int a;
publicOddNum(inta)
{ this.a = a;
}
publicvoidrun(){
[Link]("TheThread"+a+"isODDandCubeof"+a+"is:"+a*a*a);
}
}
//classtogeneraterandomnumber
classRandomNumGeneratorextendsThread{ public
void run() {
intn=0;
Randomrand=newRandom(); try{
for(int i=0;i<10;i++){ n =
[Link](20);
[Link]("GeneratedNumberis"+n);
//check ifrandomnumber isevenorodd if
(n % 2 == 0) {
Threadthread1=newThread(newEvenNum(n));
[Link]();
}
else{
Threadthread2=newThread(newOddNum(n));
[Link]();
}
//threadwaitfor1second
[Link](1000);
[Link](" ");
}
}
catch (Exception ex) {
[Link]([Link]());
}
}
}
//Driverclass
publicclassMultiThreadRandOddEven{ pu
blicstaticvoidmain(String[]args){
RandomNumGeneratorrand_num=newRandomNumGenerator();
rand_num.start();
}
}
Output:
Write a Java program forthe following: i) Create a doubly linked list of elements. ii) Delete a
given element from the above list. iii)Display the contents of the list after deletion.
Aim:
Write a Java program for the following:i) Create a doubly linked list of [Link]) Delete a given
element from the above [Link])Display the contents of the list after deletion.
SourceCode:
[Link].*;
public class DoublyLinkListDemo
{ publicstaticvoidmain(String[]args){
inti,ch,element,position;
LinkedList<Integer>dblList=newLinkedList<Integer>();
[Link]("[Link] element at begining");
[Link]("[Link] element at end");
[Link]("[Link] element at position");
[Link]("[Link] a given element");
[Link]("[Link] elements in the list");
[Link]("[Link]");
Scannersc=newScanner([Link]);
do {
[Link]("Chooseyourchoice(1-6):");
ch=[Link]();
switch(ch) {
case1://Toreadelement formtheuser
[Link]("Enteranelementtoinsertatbegining:");
element=[Link]();
//toaddelementtodoublylinkedlistatbegining
[Link](element);
[Link]("Successfully Inserted");
break;
case 2: // To read element form the user
[Link]("Enteranelementtoinsertatend:");
element=[Link]();
//to addelementtodoublylinked list atend
[Link](element);
[Link]("SuccessfullyInserted");
break;
case 3: // To read position form the user
[Link]("Enterpositiontoinsertelement:");
position=[Link]();
//checksifthepositionislessthanorequaltolist size.
if(position<=[Link]()) {
// To read element
[Link]("Enterelement:");
element=[Link]();
//to addelementtodoublylinkedlist at givenposition
[Link](position,element);
[Link]("Successfully Inserted");
}
else{
[Link]("Enterthesizebetween0to"+[Link]());
}
break;
case4://Toreadelement formtheusertoremove
[Link]("Enterelementtoremove:");
Integer ele_rm;
ele_rm=[Link]();
if ([Link](ele_rm)){
[Link](ele_rm);
[Link]("SuccessfullyDeleted");
Iterator itr=[Link]();
[Link]("Elementsafterdeleting:"+ele_rm);
while([Link]()) {
[Link]([Link]()+"<->");
}
[Link]("NULL");
}
else{
[Link]("Elementnotfound");
}
break;
case 5: // To Display elements in the list
Iterator itr=[Link]();
[Link]("Elementsinthelist:");
while([Link]()) {
[Link]([Link]()+"<->");
}
[Link]("NULL");
break;
case 6: [Link]("Programterminated");
break;
default:[Link]("Invalidchoice");
}
}
while(ch!=6);
}
}
Output:
Write a Java program that simulates a traffic light. The program lets the user selects one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate
message with Stop, Ready, or Go should appear above the buttons in the selected color.
Initially, there is no message shown
Aim:
Write a Java program that simulates a traffic light. The program lets the user selects one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with
Stop, Ready, or Go should appear above the buttons in the selected color. Initially, there is no
message shown
SourceCode:
import [Link].*;
[Link].*;
import [Link].*;
[Link].*;
classTrafficLightSimulatorextendsJFrameimplementsItemListener{ JL
abel lbl1, lbl2;
JPanelnPanel,cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator()
{ setTitle("TrafficLightSimulator");
setSize(600,400);
setLayout(newGridLayout(2,1));
nPanel=newJPanel(newFlowLayout());
cPanel=newJPanel(newFlowLayout());
lbl1 = new JLabel();
Fontfont=newFont("Verdana",[Link],70); [Link](font);
[Link](lbl1);
add(nPanel);
FontfontR=newFont("Verdana",[Link],20); lbl2
= new JLabel("Select Lights"); [Link](fontR);
[Link](lbl2);
cbg=newCheckboxGroup();
Checkboxrbn1=newCheckbox("RedLight",cbg,false);
[Link]([Link]);
[Link](fontR);
[Link](rbn1);
[Link](this);
Checkboxrbn2=newCheckbox("OrangeLight",cbg,false); [Link]([Link]);
[Link](fontR);
[Link](rbn2);
[Link](this);
Checkboxrbn3=newCheckbox("GreenLight",cbg,false);
[Link]([Link]);
[Link](fontR);
[Link](rbn3);
[Link](this);
add(cPanel);
setVisible(true);
// to close the main window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Toreadselecteditem
public void itemStateChanged(ItemEvent i)
{ Checkboxchk=[Link]();
String str=[Link]();
charchoice=[Link](0);
switch (choice) {
case 'R':[Link]("STOP");
[Link]([Link]);
break;
case 'O':[Link]("READY");
[Link]([Link]);
break;
case 'G':[Link]("GO");
[Link]([Link]);
break;
}
}
//mainmethod
publicstaticvoidmain(String[]args){ new
TrafficLightSimulator();
}
}
Output:
Write a Java program to create an abstract class named Shape that contains two integers and
an empty method named print Area (). Provide three classes named Rectangle, Triangle, and
Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given shape.
Aim:
Write a Java programto create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle
suchthat eachoneoftheclassesextendstheclass Shape. Eachoneoftheclassescontainsonlythe method
print Area () that prints the area of the given shape.
SourceCode:
import [Link].*;
abstractclassShape{
publicintx,y;
publicabstractvoidprintArea();
}
classRectangle1extendsShape{ pu
blic void printArea() {
float area;
area=x*y;
[Link]("AreaofRectangleis"+area);
}
}
classTriangleextendsShape{ publi
c void printArea() {
floatarea;
area=(x*y)/2.0f;
[Link]("AreaofTriangleis"+area);
}
}
classCircleextendsShape{ p
ublic void printArea() {
floatarea;
area=(22 * x * x) / 7.0f;
[Link]("AreaofCircleis"+area);
}
}
publicclassAreaOfShapes{
publicstaticvoidmain(String[]args){ int
choice;
Scannersc=newScanner([Link]);
[Link]("Menu\[Link]\[Link]\[Link]");
[Link]("Enter your choice : ");
choice=[Link]();
switch(choice) {
case1:[Link]("Enter lengthandbreadthfor areaofrectangle:");
Rectangle1 r = new Rectangle1();
r.x=[Link]();
r.y=[Link]();
[Link]();
break;
case2:[Link]("Enterbredthandheight forareaoftraingle:"); Triangle t =
new Triangle();
t.x=[Link]();
t.y=[Link]();
[Link]();
break;
case3:[Link]("Enterradiusforareaofcircle:"); Circle
c = new Circle();
c.x=[Link]();
[Link]();
break;
default:[Link]("Entercorrectchoice");
}
}
}
Output:
Suppose that a table named [Link] is stored in a text file. The first line in the file is the
header, and the remaining lines correspond to rows in the table. The elements are separated
by commas. Write a java program to display the table using Labels in Grid Layout.
Aim:
Supposethatatable [Link] isstoredina [Link] first line inthe file istheheader, and the
remaining lines correspond to rows inthe table. The elements are separatedbycommas. Write a java
program to display the table using Labels in Grid Layout.
SourceCode:
import [Link].*;
[Link].*;
[Link].*;
import [Link].*;
import [Link].*;
[Link].*;
classText_To_TableextendsJFrame
{
publicvoidconvertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayoutg=newGridLayout(0,4);
setLayout(g);
try
{
FileInputStreamfis=newFileInputStream("./[Link]"); Scanner
sc = new Scanner(fis);
String[]arrayList;
String str;
while([Link]())
{
str = [Link]();
arrayList=[Link](",");
for (String i: arrayList)
{
add(newLabel(i));
}
}
}
catch (Exception ex) {
[Link]();
}
setVisible(true);setTitle("Display
DatainTable");
}
}
publicclassTableText
{
publicstaticvoidmain(String[]args)
{
Text_To_Tablett=newText_To_Table();
[Link]();
}
}
[Link]
NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS
[Link]
NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS
Output:
Writeajavaprogramthat handlesallmouseeventsand showstheeventnameatthecenterof the
window when a mouse event is fired (Use Adapter classes).
Aim:
Writea javaprogramthat handlesall mouseeventsandshowstheevent nameat thecenterofthe window
when a mouse event is fired (Use Adapter classes).
SourceCode:
Aim:
Writea javaprogramthat handlesall mouseeventsandshowstheevent nameat thecenterofthe window
when a mouse event is fired (Use Adapter classes).
SourceCode:
[Link].*;
import [Link].*;
[Link].*;
import [Link].*;
classMouseEventPerformerextendsJFrameimplementsMouseListener
{
JLabell1;
publicMouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(newFlowLayout([Link]));
l1 = new JLabel();
Fontf=newFont("Verdana",[Link],20);
[Link](f);
[Link]([Link]);
add(l1);addMouseListener(this);
setVisible(true);
}
publicvoidmouseExited(MouseEventm)
{
[Link]("MouseExited");
}
publicvoidmouseEntered(MouseEventm)
{
[Link]("MouseEntered");
}
publicvoidmouseReleased(MouseEventm)
{
[Link]("MouseReleased");
}
publicvoidmousePressed(MouseEventm)
{
[Link]("MousePressed");
}
publicvoidmouseClicked(MouseEventm)
{
[Link]("MouseClicked");
}
publicstaticvoidmain(String[]args){
MouseEventPerformermep=newMouseEventPerformer();
}
}
Output: