Java Programming Lab Manual
Java Programming Lab Manual
IMS
IMS
Faculty of Computer Science
Use eclipse, Netbean or IntelliJ IDEA 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.
2 Week 2 :
Write a Java program that works as a simple calculator. Use a grid layout
to arrange buttons for the digits and for the +, -,*, % operations. Add a text
field to display the result. Handle any possible exceptions like divide by
zero.
3 Week 3 :
b) Develop an Applet that receives an integer in one text field & compute
its factorial value & returns it in another text filed when the button
“Compute” is clicked
Week 4 :
4
Write a 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 Num2 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 NumberFormatException. If Num2 were Zero, the
program would throw an Arithmetic Exception Display the exception in a
message dialog box
5 Week 5 :
Write a java program that connects to a database using JDBC and does
The Institute of Management Sciences
add, deletes, modify and retrieve operations.
7 Week 7 :
Write a java program that simulates a traffic light. The program lets the
user select one of three lights: red, yellow, or green with radio buttons. On
selecting a button, an appropriate message with “stop” or “ready” or “go”
should appear above the buttons in a selected color. Initially there is no
message shown.
Lab Mid
8 Week 8 :
Write a java program to create an abstract class named Shape that contains
two integers and an 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 contain only the
method printArea( ) that prints the area of the given shape.
9 Week 9 :
Suppose that a table named Table.txt is stored in a text file. The first line
in the file header and the remaining lines correspond to row in the table.
The elements are separated by commas. Write a Java program to display
the table using labels in grid layout.
10 Week 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).
11 Week 11 :
Write a java program that loads names and phone numbers from a text file
where the data is organized as one line per record and each field in a
record are separated by a tab (\t).it takes a name or phone number as input
and prints the corresponding other value from the hash table(hint: use hash
tables)
Week 12 :
12
Implement the above program with database instead of a text file.
13 Week 13 :
Write a java program that takes tab separated data (one record per line)
from a text file and inserts them into a database.
14 Week 14 :
1 Write a Java program that prints all real solutions to the quadratic equation
2
ax +bx+c = 0. Read in a, b, c and use the quadratic formula. If the
2
discriminate b -4ac is negative, display a message stating that there are no
real solutions?
2 The Fibonacci sequence is defined by the following rule. The first 2 values
in the sequence are 1, 1. Every subsequent value is the sum of the 2 values
preceding it. Write a Java program that uses both recursive and non-
th
recursive functions to print the n value of the Fibonacci sequence?
3 Write a Java program that prompts the user for an integer and then prints
out all the prime numbers up to that Integer?
5 Write a Java program for sorting a given list of names in ascending order?
7 Write a Java program that reads a line of integers and then displays each
integer and the sum of all integers. (use StringTokenizer class)?
8 Write a Java program that reads on file name from the user, then displays
information about whether the file exists, whether the file is readable,
whether the file is writable, the type of file and the length of the file in
bytes?
9 Write a Java program that reads a file and displays the file on the screen,
with a line number before each line?
10 Write a Java program that displays the number of characters, lines and
words in a text?
INTRODUCTION TO OOP
OOP is widely accepted as being far more flexible than other computer programming
languages. OOPs use three basic concepts as the fundamentals for the Abstraction,
Polymorphism, Event Handling and Encapsulation are also significant concepts within object-
oriented programming languages that are explained in online tutorial describing the
functionality of each concept in detail.
The java platform is undoubtedly fast moving and comprehensive. Its many application
programming interfaces (APIs) provide a wealth of functionality for all aspects of application
and system-level programming. Real-world developers never use one or two APIs to solve a
problem, but bring together key functionality spanning a number of APIs, Knowing which
APIs you need,
which parts of which APIs you need, and how the APIs work together to create the best
solution can be a daunting task.
Program:-
public class Prog1
{
}
}
}
Compile:-
D:>javac Prog1.java
Run:-
D:>java Prog1
Output:-
In Netbeans IDE:-
In Command Prompt:-
2. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the
result. Handle any possible exceptions like divide by zero.
Program:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet
{
public void init()
{
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}
class CalculatorPanel extends JPanel implements ActionListener
{
JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45); static String
lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;
private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}
public CalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));
10
Department of CS JAVA PROGRAMMING Lab Manual
n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);
n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
11
Department of CS JAVA PROGRAMMING Lab Manual
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
12
Department of CS JAVA PROGRAMMING Lab Manual
result.setText("0");
}
}
}
Output:-
13
Department of CS JAVA PROGRAMMING Lab Manual
import java.awt.*;
import java.applet.*;
}
}
Output:-
14
Department of CS JAVA PROGRAMMING Lab Manual
3.b) Develop an Applet that receives an integer in one text field & compute its factorial
value & returns it in another text filed when the button “Compute” is clicked.
Program:-
import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
String str;
Button b0;
TextField t1,t2;
Label l1;
p.setLayout(new GridLayout());
add(t1=new TextField(20));
add(t2=new TextField(20));
add(b0=new Button("compute"));
b0.addActionListener(this);
int i,n,f=1;
n=Integer.parseInt(t1.getText());
15
Department of CS JAVA PROGRAMMING Lab Manual
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f));
repaint();
Output:-
16
Department of CS JAVA PROGRAMMING Lab Manual
4. Write a 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 Num2
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 NumberFormatException. If Num2 were
Zero, the program would throw an Arithmetic Exception Display the exception in a
message dialog box.
Program:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Add1 extends Applet implements
ActionListener {
String msg;
TextField num1, num2, res;
Label l1, l2, l3;
Button div;
public void init()
{
l1 = new Label("Number 1");
l2 = new Label("Number 2");
l3 = new Label("result");
num1 = new TextField(10);
num2 = new TextField(10);
res = new TextField(30);
div = new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
17
Department of CS JAVA PROGRAMMING Lab Manual
APPLET.HTML
<html>
<head>
</head>
<body>
</applet>*/
</body>
</html>
Output:-
18
Department of CS JAVA PROGRAMMING Lab Manual
19
Department of CS JAVA PROGRAMMING Lab Manual
5.) Write a java program that 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 the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.
Program:-
}
class SquareThread implements Runnable
{
Double num;
public void run()
{
try {
20
Department of CS JAVA PROGRAMMING Lab Manual
int i=0;
do{
i++;
if(num != null&&num %2 ==0)
{
System.out.println("t2--->square of "+num+"="+(num*num));
num = null;
}
Thread.sleep(1000);
}while(i<=5);
}
catch (Exception e)
{
e.printStackTrace();
}
}
21
Department of CS JAVA PROGRAMMING Lab Manual
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Double getNum()
{
return num;
}
}
Output:-
22
Department of CS JAVA PROGRAMMING Lab Manual
6).Write a java program that connects to a database using JDBC and does add,
deletes, modify and retrieve operations?
Program:-
ConnectionUtil.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
try
Class.forName("com.mysql.jdbc.Connection");
connection =
DriverManager.getConnection("jdbc:mysql://192.168.216.250:3306/vijju","root", "root");
catch (ClassNotFoundException e)
e.printStackTrace();
catch (SQLException e)
e.printStackTrace();
23
Department of CS JAVA PROGRAMMING Lab Manual
StudentDetails.java
this.st_id = st_id;
this.st_name = st_name;
this.st_mobile = st_mobile;
return st_id;
this.st_id = st_id;
return st_name;
24
Department of CS JAVA PROGRAMMING Lab Manual
this.st_name = st_name;
return st_mobile;
this.st_mobile = st_mobile;
Prog6.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
try
conn = ConnectionUtil.getConnection();
prog6.retrieveData(conn);
25
Department of CS JAVA PROGRAMMING Lab Manual
prog6.insertData(conn, st1);
prog6.insertData(conn, st2);
prog6.insertData(conn, st3);
prog6.retrieveData(conn);
prog6.deleteARow(conn,2);
} catch (SQLException e)
e.printStackTrace();
} finally
try {
conn.close();
} catch (SQLException e)
e.printStackTrace();
26
Department of CS JAVA PROGRAMMING Lab Manual
pstmt.setLong(1, st_mobile);
pstmt.setLong(2, st_id);
//System.out.println(row);
} catch (SQLException e)
{ e.printStackTrace();
PreparedStatement pstmt =
conn.prepareStatement(query); pstmt.setLong(1, st_id);
//System.out.println(row);
catch (SQLException e)
e.printStackTrace();
27
Department of CS JAVA PROGRAMMING Lab Manual
PreparedStatement pstmt =
conn.prepareStatement(query);
pstmt.setString(1,details.getSt_name()); pstmt.setLong(2,
details.getSt_mobile()); pstmt.setLong(3,
//System.out.println(row);
catch (SQLException e)
e.printStackTrace();
try {
ResultSet rs = pstmt.executeQuery();
System.out.println("ST_ID\tST_NAME\t\tST_MOBILE");
while(rs.next())
System.out.println(rs.getString("st_id")+"\t"+rs.getString("st_name")+"\t\t"+rs.getString( "st_mobile"));
28
Department of CS JAVA PROGRAMMING Lab Manual
catch (SQLException e)
e.printStackTrace();
Output:-
29
Department of CS JAVA PROGRAMMING Lab Manual
7) Write a java program that simulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with “stop” or “ready” or “go” should appear above the buttons in
a selected color. Initially there is no message shown.
Program:-
TrafficSignal.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
Thread t;
Font f, f1;
int i = 0, a = 0, j = 0;
setBackground(Color.lightGray);
t = new Thread(this);
t.start();
30
Department of CS JAVA PROGRAMMING Lab Manual
try
Thread.sleep(1000);
catch (Exception e)
System.out.println(e);
a = 1;
repaint();
a = 2;
repaint();
else if (i == 0)//green
a = 3;
try
Thread.sleep(1000);
catch (Exception e)
31
Department of CS JAVA PROGRAMMING Lab Manual
System.out.println(e);
repaint();
run();
repaint();
setBackground(Color.lightGray);//ROAD
g.setColor(Color.black);//POLE UP
g.setColor(Color.black);//POLE DOWN
g.setColor(Color.red);//COUNTDOWN STOP
g.setFont(f);
32
Department of CS JAVA PROGRAMMING Lab Manual
if (a == 1)//REDSIGNAL
{
g.setColor(Color.red);
g.fillOval(150, 150, 50, 50);
if (a == 2)//YELLOWSIGNAL
g.setColor(Color.yellow);
g.setColor(Color.green);
int n1 = 4;
int n2 = 3;
33
Department of CS JAVA PROGRAMMING Lab Manual
TrafficSignal.html
<html>
<head>
</head>
<body>
/*<applet code="TrafficSignal.class" height=500 width=300></applet>*/
</body>
</html>
Output:-
34
Department of CS JAVA PROGRAMMING Lab Manual
8) Write a java program to create an abstract class named Shape that contains two integers
and an 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
contain only the method printArea( ) that prints the area of the given shape.
Program:-
void numberOfSides()
void numberOfSides()
void numberOfSides()
{
System.out.println("Hexagon has six sides");
}
}
class ShapeDemo
35
Department of CS JAVA PROGRAMMING Lab Manual
{
public static void main(String args[ ])
{
Trapezoid t=new Trapezoid();
Triangle r=new Triangle();
Hexagon h=new Hexagon();
Shape s;
s=t;
s.numberOfSides();
s=r;
s.numberOfSides();
s=h;
s.numberOfSides();
}
}
Output:-
36
Department of CS JAVA PROGRAMMING Lab Manual
9) Suppose that a table named Table.txt is stored in a text file. The first line in the file
header and the remaining lines correspond to row in the table. The elements are separated
by commas. Write a Java program to display the table using labels in grid layout.
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
int i=0;
int j=0,k=0;
JButton save;
JTable table1;
FileInputStream fis;
DataInputStream dis;
public Table1()
Container con=getContentPane();
con.setLayout(new BorderLayout());
try
37
Department of CS JAVA PROGRAMMING Lab Manual
while ((d=dis.readLine())!=null)
{
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{
for (j=0;j<4;j++)
{
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}
i++;
}
System.out.println ("______________");
}
} catch (Exception e)
{
System.out.println ("Exception raised" +e.toString());
}
table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll=new JScrollPane(table1,v,h);
con.add(scroll,BorderLayout.CENTER);
}
public static void main(String args[])
{
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} }
Abc.txt:-
a,123,der,23
b,456,frg,45
Output:-
38
Department of CS JAVA PROGRAMMING Lab Manual
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).
39
Department of CS JAVA PROGRAMMING Lab Manual
Program:-
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
int mx=0;
int my=0;
String msg="";
addMouseListener(this);
addMouseMotionListener(this);
mx=20;
my=40;
msg="Mouse Clicked";
repaint();
mx=30;
my=60;
msg="Mouse Pressed";
40
Department of CS JAVA PROGRAMMING Lab Manual
repaint();
mx=30;
my=60;
msg="Mouse Released";
repaint();
mx=40;
my=80;
msg="Mouse Entered";
repaint();
mx=40;
my=80;
msg="Mouse Exited";
repaint();
mx=me.getX();
my=me.getY();
41
Department of CS JAVA PROGRAMMING Lab Manual
repaint(); }
Output:-
11).Write a java program that loads names and phone numbers from a text file where the
data is organized as one line per record and each field in a record are separated by a tab
(\t).it takes a name or phone number as input and prints the corresponding other value from
42
Department of CS JAVA PROGRAMMING Lab Manual
Program:-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
Hashtable<String, String>hashData =
"----");
if(hashData != null)
if(keys.contains(input))
43
Department of CS JAVA PROGRAMMING Lab Manual
output = hashData.get(input);
else
while(iterator.hasNext()) {
if(value.equals(input))
{
output = key;
break;
} } } }
System.out.println("Input given:"+input);
if(output != null)
{
System.out.println("Data found in
HashTable:"+output); }
else {
System.out.println("Data not found in HashTable");
} }
try {
hashData.put(details[0], details[1]);
} catch (FileNotFoundException e) {
44
Department of CS JAVA PROGRAMMING Lab Manual
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}
return hashData; } }
HashTab.txt
vbit 123
abc 345
edrf 567
Output:-
45
Department of CS JAVA PROGRAMMING Lab Manual
ConnectionUtil.Java
package LabProgs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil
{
public static Connection getConnection() throws SQLException
{
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Connection");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "system");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
return connection;
}
}
Prog12.Java:-
package LabProgs;
import java.sql.Connection;
46
Department of CS JAVA PROGRAMMING Lab Manual
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class Prog12
{
public static void main(String[] args)
{
String query = "select * from test.student_details";
Connection conn = null;
try
{
conn = ConnectionUtil.getConnection();
Prog12 prog12 = newProg12();
Hashtable<String, String>hashData = prog12.retrieveData(conn, query);
47
Department of CS JAVA PROGRAMMING Lab Manual
conn.close();
}
catch (SQLExceptione)
{
e.printStackTrace();
}
}
}
Private void printTheData(Hashtable<String, String>hashData, String input)
{
String output = null;
if(hashData != null)
{
Set<String>keys = hashData.keySet();
if(keys.contains(input)) {
output = hashData.get(input);
}
else
{
Iterator<String>iterator = keys.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
String value = hashData.get(key);
if(value.equals(input)) {
output = key;
break;
} } } }
System.out.println("Input given:"+input);
if(output != null)
{
48
Department of CS JAVA PROGRAMMING Lab Manual
Output:-
49
Department of CS JAVA PROGRAMMING Lab Manual
13. Write a java program that takes tab separated data (one record per
line) from a text file and inserts them into a database.
Program:-
50
Department of CS JAVA PROGRAMMING Lab Manual
Prog11.txt
JNTU 65656565
OU 64646464
ConnectionUtil.Java
package LabProgs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil
{
Prog13.Java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;
51
Department of CS JAVA PROGRAMMING Lab Manual
52
Department of CS JAVA PROGRAMMING Lab Manual
e.printStackTrace();
}
return ++id;
}
Output:-
53
Department of CS JAVA PROGRAMMING Lab Manual
14. Write a java program that prints the meta-data of a given table.
Program:-
54
Department of CS JAVA PROGRAMMING Lab Manual
ConnectionUtil.Java
package LabProgs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil
{
public static Connection getConnection() throws SQLException
{ Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Connection");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test",
"root", "system");
} catch (ClassNotFoundException e)
{ e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
55
Department of CS JAVA PROGRAMMING Lab Manual
try {
conn = ConnectionUtil.getConnection();
prog14.printMetaData(conn, "student_details");
Statement statement;
try {
statement = conn.createStatement();
ResultSetMetaDatametaData = statement.executeQuery(query).getMetaData();
longcolSize = metaData.getColumnCount();
System.out.println("Columns are:");
for(inti=1;i<=colSize;i++) {
System.out.println(colName+"-->"+colType);
} catch (SQLException e)
{ e.printStackTrace(
);
56
Department of CS JAVA PROGRAMMING Lab Manual
Output:-
Additional Programs:-
57
Department of CS JAVA PROGRAMMING Lab Manual
2
1.Write a Java program that prints all real solutions to the quadratic equation ax +bx+c = 0.
2
Read in a, b, c and use the quadratic formula. If the discriminate b -4ac is negative, display a
message stating that there are no real solutions.
Program :-
import java.io.*;
class Quadratic
double x1,x2,disc,a,b,c;
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
x1=x2=-b/(2*a);
else if(disc>0)
x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b+Math.sqrt(disc))/(2*a);
58
Department of CS JAVA PROGRAMMING Lab Manual
else
} } }
59
Department of CS JAVA PROGRAMMING Lab Manual
2. The Fibonacci sequence is defined by the following rule. The first 2 values in the
sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it. Write a
th
Java program that uses both recursive and non-recursive functions to print the n value
of the Fibonacci sequence.
Program:-
import java.util.Scanner;
class Fib {
int i,a=1,b=1,c=0,t;
t=input.nextInt();
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<t-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
System.out.println();
60
Department of CS JAVA PROGRAMMING Lab Manual
/* Recursive Solution*/
import java.io.*;
import java.lang.*;
class Demo {
int fib(int n) {
if(n==1)
return (1);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
class RecFibDemo {
61
Department of CS JAVA PROGRAMMING Lab Manual
{ InputStreamReader obj=new
int n=Integer.parseInt(br.readLine());
int res=0;
for(int i=1;i<=n;i++) {
res=ob.fib(i);
System.out.println(" "+res); }
System.out.println();
}}
62
Department of CS JAVA PROGRAMMING Lab Manual
3.WAJP that prompts the user for an integer and then prints out all the prime numbers
up to that Integer.
Program:-
import java.util.*
class Test {
if(i%j==0)
break;
else if((i%j!=0)&&(j==i-1))
System.out.print(“ “+i);
obj1.check(n);
}}
63
Department of CS JAVA PROGRAMMING Lab Manual
4. WAJP that checks whether a given string is a palindrome or not. Ex: MADAM
is a palindrome.
Program:-
import java.io.*;
class Palind {
sb.append(s1);
sb.reverse();
String s2=sb.toString();
if(s1.equals(s2))
System.out.println("palindrome");
else
System.out.println("not palindrome");
} }
64
Department of CS JAVA PROGRAMMING Lab Manual
import java.io.*;
class Test {
int len,i,j;
String arr[ ];
Test(int n) {
len=n;
arr=new String[n];
arr[i]=br.readLine();
return arr;
for (i=0;i<len-1;i++) {
for(int j=i+1;j<len;j++) {
if ((arr[i].compareTo(arr[j]))>0) {
String s1=arr[i];
arr[i]=arr[j];
arr[j]=s1;
65
Department of CS JAVA PROGRAMMING Lab Manual
return arr;
for (i=0;i<len;i++)
System.out.println(arr[i]);
obj1.getArray();
obj1.check();
obj1.display();
66
Department of CS JAVA PROGRAMMING Lab Manual
Program :-
import java.util.*;
class Test {
int r1,c1,r2,c2;
this.r1=r1;
this.c1=c1;
this.r2=r2;
this.c2=c2;
for(int j=0;j<c;j++)
arr[i][j]=input.nextInt();
return arr;
c[i][j]=0;
c[i][j]=c[i][j]+a[i][k]*b[k][j];
67
Department of CS JAVA PROGRAMMING Lab Manual
return c;
System.out.print(res[i][j]+" ");
System.out.println();
[ ],y[ ][ ],z[ ][ ];
System.out.println("MATRIX-1:");
System.out.println("MATRIX-2:");
y=obj2.getArray(3,2);
}}
68
Department of CS JAVA PROGRAMMING Lab Manual
a line of integers and then displays each integer and the sum of all integers.
(use StringTokenizer class)
Program :-
/ Using StringTokenizer
class import java.lang.*;
import java.util.*;
class tokendemo {
int sum=0;
while(a.hasMoreTokens()) {
int b=Integer.parseInt(a.nextToken());
sum=sum+b; System.out.println("
"+b);
class Arguments {
int sum=0;
int n=args.length;
System.out.println("length is "+n);
69
Department of CS JAVA PROGRAMMING Lab Manual
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(args[i]);
for(int i=0;i<n;i++)
System.out.println(arr[i]);
for(int i=0;i<n;i++)
sum=sum+arr[i];
System.out.println(sum);
70
Department of CS JAVA PROGRAMMING Lab Manual
8.WAJP that reads on file name from the user, then displays information about whether
the file exists, whether the file is readable, wheteher the file is writable, the type of file and
the length of the file in bytes.
Program :-
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
71
Department of CS JAVA PROGRAMMING Lab Manual
9. WAJP that reads a file and displays the file on the screen, with a line number before
each line.
Program :-
import java.io.*;
class LineNum{
String thisline;
for(int i=0;i<args.length;i++)
try{
while((thisline=br.readLine())!=null)
System.out.println(br.getLineNumber()+"."+thisline);
}catch(IOException e){
System.out.println("error:"+e);
}}}}
72
Department of CS JAVA PROGRAMMING Lab Manual
10. WAJP that displays the number of characters, lines and words in a text
file. Program :-
import java.io.*;
String line;
nl++;
nc=nc+line.length();
int i=0;
boolean pspace=true;
while (i<line.length()) {
char c=line.charAt(i++);
boolean cspace=Character.isWhitespace(c);
if (pspace&&!cspace)
nw++;
pspace=cspace;
System.out.println("Number of Characters"+nc);
System.out.println("Number of Characters"+nw);
System.out.println("Number of Characters"+nl);
}}
73
Department of CS JAVA PROGRAMMING Lab Manual
import java.util.*;
long nl=0,nw=0,nc=0;
String line;
while ((line=br.readLine())!=null) {
nl++;
nc=nc+line.length();
System.out.println("Number of Characters"+nl);
}}
74