JAVA PROGRAMS Msword&rendition 1
JAVA PROGRAMS Msword&rendition 1
R18
Program 1:
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 small program of about 10
to 15 lines which contains at least one if else condition and a for loop.
About Eclipse IDE
In the context of computing, Eclipse is an integrated development environment (IDE) for developing
applications using the Java programming language and other programming languages such as C/C++,
Python, PERL, Ruby etc. The Eclipse platform which provides the foundation for the Eclipse IDE is
composed of plug-ins and is designed to be extensible using additional plug-ins. Developed using Java,
the Eclipse platform can be used to develop rich client applications, integrated development
environments and other tools. Eclipse can be used as an IDE for any programming language for which a
plug-in is available.
By right clicking in the package explorer and selecting New > Class
Before bringing up the New Java Class wizard, if possible, select the package in which the class is to be
created so that the wizard can automatically fill in the package name for you.
Enter the super class name or click on the Browse button to search for an existing class
Click on the Add button to select the interfaces implemented by this class
Examine and modify the check boxes related to method stubs and comments
1
Java Programming Lab II B.Tech II sem. R18
Program 2:
Write a java program that works as simple calculator . Use a grid layout to arrange
buttons for the digits and for the +,-,*,% operations. add a textfield to display the result.
Handle any possible exceptions like divide by zero
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
2
Java Programming Lab II B.Tech II sem. R18
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
3
Java Programming Lab II B.Tech II sem. R18
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
try
{
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
4
Java Programming Lab II B.Tech II sem. R18
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
5
Java Programming Lab II B.Tech II sem. R18
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
catch (Exception e)
{
t1.setText(e.toString());
}
}
}
6
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
7
Java Programming Lab II B.Tech II sem. R18
8
Java Programming Lab II B.Tech II sem. R18
Program 3.
import java.awt.*;
import java.applet.*;
/*
<applet code="MyApplet" height=500 width=500>
</applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to applets",120,120);
}
}
9
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
10
Java Programming Lab II B.Tech II sem. R18
PROGRAM 3
b) 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.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener
{
Button b;
TextField tf,tf1;
public void init()
{
tf=new TextField("Eneter a value");
tf1=new TextField("Results will appear here");
tf.setBounds(30,40,150,20);
tf1.setBounds(30,80,150,20);
b=new Button("Compute ");
b.setBounds(80,150,60,50);
add(b);
add(tf);
add(tf1);
b.addActionListener(this);
setLayout(null);
}
11
Java Programming Lab II B.Tech II sem. R18
/*
<applet code="EventApplet" height=500 width=500>
</applet>
*/
12
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
13
Java Programming Lab II B.Tech II sem. R18
14
Java Programming Lab II B.Tech II sem. R18
Program 4:
Write a java program that causes a user interface to perform integer divisions. the user
enters two numbers in textfields Num1 and Num2 . the division of num1 and num2 is
displayed in the result field when the divide button is clicked. if Num1 or num2 were not an
integer , the program would through a NumberFormatException . If Num2 were zero , the
program would through an arithmeticException . Display the exception in a message dialog
box.
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
15
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
18
Java Programming Lab II B.Tech II sem. R18
Program 5:
program on multi threading here we create three threads First thread will generate a
random no, then second thread will print square of that number if it is Even Number,Third
will print cube of given no if it is odd number....
import java.util.*;
class MultiThread
{
int n=0;
boolean n_set=false;
public void n_set()
{
Random r=new Random();
while(n_set==true)
n=r.nextInt(100);
n_set=true;
System.out.println("Random no is "+n);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
public void n_sq()
{
if(n_set==true && n%2==0)
{
System.out.println("square of given "+n+" is"+n*n);
n_set=false;
19
Java Programming Lab II B.Tech II sem. R18
}
}
20
Java Programming Lab II B.Tech II sem. R18
t1.start();
Thread t2 =new Thread();
public void run()
{
while(true)
l.n_sq();
}}
t2.start();
Thread t3 = new Thread();
public void run()
{
while(true)
l.n_cube();
}
}
t3.start();
}
}
21
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
22
Java Programming Lab II B.Tech II sem. R18
Program 6
// Java program to create and delete a node from doubly linked list
class LinkedList {
class Node
{
int data;
Node next, prev;
Node(int d)
{
data = d;
next = prev = null;
}
}
/* base case */
if (head == null || del == null) {
return;
}
23
Java Programming Lab II B.Tech II sem. R18
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(Node head_ref, int new_data)
{
/* allocate node */
Node new_node = new Node(new_data);
24
Java Programming Lab II B.Tech II sem. R18
25
Java Programming Lab II B.Tech II sem. R18
Output:
26
Java Programming Lab II B.Tech II sem. R18
Program 7:
Write a java program that simulates a traffic light. the program lets the user select one of
the three lights : red,Yellow,Green with radio buttons. On selecting a button, an
appropriate message with Stop or Ready Or GO should appear above button in selected
color Initially there is no message shown.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*
<applet code="TraficLight" height=500 width=500> </applet>
*/
public class TraficLight extends Applet
implements ItemListener
{
CheckboxGroup cg1 = new CheckboxGroup ();
public void init()
{
Checkbox c1,c2,c3;
setBackground(Color.black);
c1=new Checkbox ("RED", cg1, false);
c1.setBackground(Color.red);
c2=new Checkbox ("GREEN", cg1, false);
c2.setBackground(Color.green);
c3=new Checkbox ("YELLOW", cg1, false);
c3.setBackground(Color.yellow);
c1.addItemListener(this);
c2.addItemListener(this);
27
Java Programming Lab II B.Tech II sem. R18
c3.addItemListener(this);
add (c1);
add (c2);
add (c3);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
Checkbox chk = cg1.getSelectedCheckbox();
if(chk.getLabel()=="YELLOW")
{
g.setColor(Color.yellow);
g.drawString(chk.getLabel() + " is selected : READY TO GO", 10 ,70);
}
if(chk.getLabel()=="RED")
{
g.setColor(Color.red);
g.drawString(chk.getLabel() + " is selected : STOP", 10 ,70);
}
if(chk.getLabel()=="GREEN")
{ g.setColor(Color.green);
g.drawString(chk.getLabel() + " is selected : GO ", 10 ,70);
}
g.fillOval(10,100,50,50);
}
}
28
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
29
Java Programming Lab II B.Tech II sem. R18
Program 8:
Write a java program to create an abstract class named Shape that contains two integers
and empty method named printArea() 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 printarea() that prints the area of the given shape
abstract class shape
{
int l,b;
abstract public void printArea();
}
class rectangle extends shape
{
rectangle(int l,int b)
{
super.l=l;
super.b=b;
}
public void printArea()
{
System.out.println("area of rectangle is: "+l*b);
}
}
class triangle extends shape
{
triangle(int l,int b)
{
super.l=l;
super.b=b;
}
public void printArea()
{
System.out.println("area of triangle is: "+05.*l*b*b);
}
}
30
Java Programming Lab II B.Tech II sem. R18
31
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
32
Java Programming Lab II B.Tech II sem. R18
Program 9:
Suppose that a table named Table.txt 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
seperated by commas. Write a java program to display the table using Labels in Grid
Layout.
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class JTableDemo extends JApplet
{
public void init( )
{
Container c =getContentPane( );
c.setLayout(new BorderLayout( ));
String fields [ ]={"empid "," empname ","empsal"} ;
Object details [][] = {{" 1" ,"Nataraj" ,"4500.50 "} , {"2","ravi" ," 4567.50 "} ,
{"3","raja","2246.30"},{"4","sita","3245.75"},
{"5"," Jyostna " ,"2500.25"}
} ;
JTable jt = new JTable( details, fields ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ; // if the rows are more than
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ; // height of the applet,
JScrollPanejsp = new JScrollPane(jt); // scroll bar is added
c.add(jsp , BorderLayout.SOUTH ) ;
}
}
/*
<APPLET ALIGN="CENTER" CODE="JTableDemo.class" WIDTH=500
HEIGHT=500></APPLET>
*/
33
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
34
Java Programming Lab II B.Tech II sem. R18
Program 10:
Write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired(Use Adapter classes)
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class MouseEv1 extends Applet
{
String msg="welcome";
public void init()
{
addMouseListener(new InnerCls1());
addMouseMotionListener(new InnerCls2());
}
public void paint(Graphics g)
{
Dimension d=getSize();
g.drawString(msg,(getWidth()/2)-msg.length()/2,(getHeight()/2));
}
class InnerCls2 extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
msg="mouseMoved"+me.getX()+"'"+me.getY();
repaint();
}
35
Java Programming Lab II B.Tech II sem. R18
}
public void mouseExited(MouseEvent me)
{
msg="mouseExited"+me.getX()+"'"+me.getY();
repaint();
}
}
}
/*
<applet code="MouseEv1" height=500 width=500></applet>
*/
OUTPUT:
37
Java Programming Lab II B.Tech II sem. R18
38
Java Programming Lab II B.Tech II sem. R18
39
Java Programming Lab II B.Tech II sem. R18
40
Java Programming Lab II B.Tech II sem. R18
Program 11:
Write a java program that loads names and phone numbers from the text file where data is
organized as one line per record and each field in record are separated by a tab(\t).It takes
a name or phone number as input and prints corresponding other value from hash
table(hint: use Hash Table)
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("D:\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
41
Java Programming Lab II B.Tech II sem. R18
System.out.println("----MENU------");
System.out.println("----1.Search by Name------");
System.out.println("----2.Search by Mobile------");
System.out.println("----3.Exit------");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else
{
System.out.println("Not Found");
}
break;
42
Java Programming Lab II B.Tech II sem. R18
case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile)) {
for (Map.Entry e : ht.entrySet()) {
if (mobile.equals(e.getValue())) {
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
}
break;
case "3": {
opt = "3";
System.out.println("Menu Successfully Exited");
}
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}}}
43
Java Programming Lab II B.Tech II sem. R18
OUTPUT:
HASH TABLE IS
KEY : VALUE
PRA 1236
RAP 2034
----MENU------
----1.Search by Name------
----2.Search by Mobile------
----3.Exit------
Enter Your Option 1,2,3
1
Enter Name: PRA
Mobile is 1236
Enter Your Option 1,2,3
2
Program 12:
44
Java Programming Lab II B.Tech II sem. R18
Write a Java program that correctly implements the producer – consumer problem using
the concept of interthread communication.
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
45
Java Programming Lab II B.Tech II sem. R18
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
46
Java Programming Lab II B.Tech II sem. R18
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
47
Java Programming Lab II B.Tech II sem. R18
Output:
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
48
Java Programming Lab II B.Tech II sem. R18
Program 13:
Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
import java.io.File;
public class ListDirectoryRecurisve {
public void listDirectory(String dirPath, int level) {
File dir = new File(dirPath);
File[] firstLevelFiles = dir.listFiles();
if (firstLevelFiles != null && firstLevelFiles.length > 0) {
for (File aFile : firstLevelFiles) {
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
if (aFile.isDirectory()) {
System.out.println("[" + aFile.getName() + "]");
listDirectory(aFile.getAbsolutePath(), level + 1);
} else {
System.out.println(aFile.getName());
}
}
}
}
public static void main(String[] args) {
ListDirectoryRecurisve test = new ListDirectoryRecurisve();
String dirToList = System.getProperty("user.home") + File.separator + "Documents";
test.listDirectory(dirToList, 0);
}}
49