Sie sind auf Seite 1von 33

Department of Computer Science and Engineering

II B Tech II Semester [Branch: CSE]

2016-17

JAVA PROGRAMMING LAB MANUAL

By

MANZOOR MOHAMMAD
Assistant Professor

JOGINPALLY B.R.ENGINEERING COLLEGE


Yenkapally(Village), BhaskarNagar (post),
Moinabad (Mandal), Hyderabad-75
1. AIM
WRITE A JAVA PROGRAM THAT PROMPTS THE USER FOR AN INTEGER AND THEN PRINTS OUT ALL
PRIME NUMBERS UP TO THAT INTEGER .
CODE:
import java.util.*;
class Prime
{
public static void main(String args[])
{
Scanner as=new Scanner(System.in);
System.out.println("Enter an integer value");
int n=as.nextInt();
int i=0,j=0,c=0;
System.out.print("The prime numbers upto "+n+" are ");
for(i=1;i<=n;i++)
{
c=0;
for(j=1;j<=i;j++)
{
int x=i%j;
if(x==0)
{
c++;
}
}
if(c==2)
{
System.out.print(i+" ");
}
}
}
}
OUTPUT:

2. AIM:
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 .
CODE:
import java.awt.*;
import java.awt.event.*;
public class Calci extends Frame implements ActionListener
{
Button a,b,c,d,e,f,g,h,i,j,add,sub,mul,div,mod,equal;
Panel p1, p2;
TextField t;
Calci()
{
p1=new Panel();
p2=new Panel();
t=new TextField(20);
a=new Button("1");
b=new Button("2");
c=new Button("3");
d=new Button("4");
e=new Button("5");
f=new Button("6");
g=new Button("7");
h=new Button("8");
i=new Button("9");
j=new Button("0");
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("Ac");
equal=new Button("=");
p1.add(t,new FlowLayout());
p2.add(g);
p2.add(h);
p2.add(i);
p2.add(div);
p2.add(d);
p2.add(e);
p2.add(f);
p2.add(mul);
p2.add(a);
p2.add(b);
p2.add(c);
p2.add(sub);
p2.add(j);
p2.add(add);
p2.add(mod);
p2.add(equal);
p2.setLayout(new GridLayout(4,4));
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
g.addActionListener(this);
h.addActionListener(this);
i.addActionListener(this);
j.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
equal.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==a||e.getSource()==b||e.getSource()==c||e.getSource()==d||
e.getSource()==e||e.getSource()==f||e.getSource()==g||e.getSource()==h||e.getSource()==i||
e.getSource()==j)
t.setText(String.valueOf();
if(e.getSource()==add)
{
int num2=Integer.parseInt(t.getText());
int c=num1+num2;
t.setText(String.valueOf(c));
}
if(e.getSource()==sub)
{
int num2=Integer.parseInt(t.getText());
int c=num1+num2;
t.setText(String.valueOf(c));
}
if(e.getSource()==mul)
{
int num2=Integer.parseInt(t.getText());
int c=num1+num2;
t.setText(String.valueOf(c));
}
if(e.getSource()==div)
{
int num2=Integer.parseInt(t.getText());
int c=num1+num2;
t.setText(String.valueOf(c));
}

public static void main(String args[])


{
Calci c=new Calci();
c.setSize(400,400);
c.setTitle("Calculator");
c.setVisible(true);
}
}

OUTPUT
3A. AIM

DEVELOP AN APPLET THAT DISPLAYS A SIMPLE MESSAGE IN CENTER OF THE SCREEN

CODE

import java.applet.*;
import java.awt.*;
/* <applet code="Appletdemo.class" width=300 height=300> </applet> */
public class Appletdemo extends Applet
{
public void paint(Graphics g)
{
String msg="HELLO!, Welcome to my applet ";
g.drawString(msg,80,150);
}
}

OUTPUT

3B. AIM
Develop an applet 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

Program
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*<applet code="task8b.class" height=200 width=200>
</applet>*/
public class task8b extends Applet implements ActionListener
{
TextField t1,t2;
Button b;
Label l1,l2;
38
int a,fact;
public void init()
{ l1=new Label("Enter a number",Label.LEFT);
l2=new Label("Result",Label.RIGHT);
t1=new TextField(5);
t2=new TextField(10);
b=new Button("Compute");
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{ a=Integer.parseInt(t1.getText());
fact=1;
if(a<0)
{
t2.setText("Wrong input");
}
else
{
for(int i=a;i>1;i--)
39
fact*=i;
}
t2.setText(""+fact);
//repaint();
}
}

OUTPUT
D:\education\java\programs>javac Week7b.java
D:\education\java\programs>appletviewer Week7b.java

4.AIM
WRITE A PROGRAM THAT CREATES A USER INTERFACE TO PERFORM INTEGER DIVISIONS .THE USER
ENTERS TWO NUMBERS IN THE TEXTFIELDS , NUM 1 AND NUM2. T HE 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 E XCEPTION .IF NUM2
WERE Z ERO, THE PROGRAM WOULD THROW AN ARITHMETIC E XCEPTION DISPLAY THE EXCEPTION
IN A MESSAGE DIALOG BOX .

CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class division extends Frame implements ActionListener
{
Label l1,l2,l3;
Button b;
TextField t1,t2,t3;
division()
{
l1=new Label("Num1");
l2=new Label("Num2");
l3=new Label("Result");
b=new Button("Divide");
t1=new TextField(20);
t2=new TextField(20);
t3=new TextField(20);
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);
add(t3);
setLayout(new FlowLayout());
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b)
{
try
{
int num1=Integer.parseInt(t1.getText());
int num2=Integer.parseInt(t2.getText());
int c=num1/num2;
t3.setText(String.valueOf(c));
}
catch(NumberFormatException n)
{
JOptionPane.showMessageDialog(null,"Number Format
Exception");
}
catch(ArithmeticException a)
{
JOptionPane.showMessageDialog(null,"Arithmetic Exception");
}
}
}
public static void main(String args[])
{
division d=new division();
d.setVisible(true);
d.setSize(400,400);
d.setTitle("Division");
d.addWindowListener(new Myclass());
}
}
class Myclass extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

OUTPUT:
5. AIM :
WRITE A JAVA PROGRAM THAT CREATES THREE THREADS. FIRST THREAD DISPLAYS GOOD
MORNING EVERY ONE SECOND, THE SECOND THREAD DISPLAYS HELLO EVERY TWO SECONDS
AND THE THIRD THREAD DISPLAYS W ELCOME EVERY THREE SECONDS .

CODE:
import java.io.*;
class Mythread extends Thread
{
String msg;
Mythread(String m)
{
msg=m;
}
public void run()
{
System.out.println(msg);
}
}
class testThread
{
public static void main(String args[])throws InterruptedException
{
Mythread s1=new Mythread("Good Morning");
Mythread s2=new Mythread("Hello");
Mythread s3=new Mythread("Welcome");
s1.sleep(1000);
s1.start();
s2.sleep(2000);
s2.start();
s3.sleep(3000);
s3.start();
}
}

OUTPUT:
7. AIM

WRITE A JAVA PROGRAM THAT SIMULATES A TRAFFIC LIGHT. T HE PROGRAM LETS THE USER
SELECT ONE OF THREE LIGHTS : RED , YELLOW , OR GREEN. W HEN A RADIO BUTTON IS SELECTED ,
THE LIGHT IS TURNED ON , AND ONLY ONE LIGHT CAN BE ON AT A TIME NO LIGHT IS ON WHEN THE
PROGRAM STARTS .

CODE:
IMPORT JAVA. AWT .*;
IMPORT JAVA. AWT .EVENT .*;
CLASS TRAFFIC L IGHTS EXTENDS FRAME IMPLEMENTS ITEMLISTENER
{
CHECKBOXGROUP LNGGRP;
STRING STR;
TRAFFIC L IGHTS ()
{
LNG GRP=NEW CHECKBOX GROUP ();
CHECKBOX R=NEW CHECKBOX ("RED",LNG GRP,TRUE);
CHECKBOX Y=NEW CHECKBOX ("Y ELLOW ",LNGGRP,TRUE);
CHECKBOX G=NEW CHECKBOX ("G REEN",LNGGRP,TRUE);
ADD (R );
ADD (Y );
ADD (G );
SET L AYOUT (NEW FLOWLAYOUT());
R .ADD ITEM L ISTENER ( THIS );
Y .ADD ITEM L ISTENER ( THIS );
G .ADD ITEM L ISTENER ( THIS );
}
PUBLIC VOID ITEM S TATE CHANGED (I TEME VENT E)
{
CHECKBOX CHK=LNG GRP.GETSELECTED CHECKBOX ();
STR =CHK .GET L ABEL ();
REPAINT ();
}
PUBLIC VOID PAINT (GRAPHICS GR)
{
GR. SET COLOR (COLOR . BLACK );
GR. DRAWR ECT(100,100,100,300);
GR. SET COLOR (COLOR . WHITE );
GR. DRAWOVAL (125,120,50,50);
GR. DRAWOVAL (125,220,50,50);
GR. DRAWOVAL (125,320,50,50);
IF ( STR .EQUALS ("R ED "))
{
GR. SET COLOR (COLOR . RED);
GR. FILL OVAL(125,120,50,50);
}
IF ( STR .EQUALS ("YELLOW "))
{
GR. SET COLOR (COLOR . YELLOW );
GR. FILL OVAL(125,220,50,50);
}
IF ( STR .EQUALS ("GREEN"))
{
GR. SET COLOR (COLOR . GREEN);
GR. FILL OVAL(125,320,50,50);
}
}
PUBLIC STATIC VOID MAIN (STRING ARGS [])
{
TRAFFIC L IGHTS T =NEW TRAFFIC L IGHTS ();
T .SET VISIBLE (TRUE);
T .SET S IZE (500,500);
T .SET T ITLE ("T RAFFIC LIGHTS ");
}
}
OUTPUT

8. AIM

WRITE A JAVA PROGRAM TO CREATE AN ABSTRACT CLASS NAMED SHAPE THAT CONTAINS AN
EMPTY METHOD NAMED NUMBER OFSIDES ( ).PROVIDE THREE CLASSES NAMED TRAPEZOID,
TRIANGLE AND HEXAGON SUCH THAT EACH ONE OF THE CLASSES EXTENDS THE CLASS SHAPE.
EACH ONE OF THE CLASSES CONTAINS ONLY THE METHOD NUMBER OFSIDES () THAT SHOWS THE
NUMBER OF SIDES IN THE GIVEN GEOMETRICAL FIGURES .

CODE:
import java.util.*;
abstract class Shape
{
int n;
abstract void numberOfSides(int n);
}
class Trapezoid extends Shape
{
void numberOfSides(int n)
{
System.out.println("Number of sides in the given geometrical figure is "+n);
}
}
class Triangle extends Shape
{
void numberOfSides(int n)
{
System.out.println("Number of sides in the given geometrical figure is "+n);
}
}
class Hexagon extends Shape
{
void numberOfSides(int n)
{
System.out.println("Number of sides in the given geometrical figure is "+n);
}
}

class Details
{
public static void main(String args[])
{
Shape s;
s=new Trapezoid();
s.numberOfSides(4);
s=new Triangle();
s.numberOfSides(3);
s=new Hexagon();
s.numberOfSides(6);
}
}

OUTPUT

9. AIM
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 SEPARATED BY COMMAS . WRITE A JAVA PROGRAM TO DISPLAY THE TABLE USING JTABLE
COMPONENT .

CODE:
import javax.swing.*;
import java.awt.*;
public class table extends JFrame
{
JTable table;
String columnnames[]={"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object rowdata[][]={
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
table()
{
Container c=getContentPane();
table = new JTable(rowdata, columnnames);
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
c.setLayout(new BorderLayout());
c.add(table,BorderLayout.CENTER);

public static void main(String args[])


{
table t=new table();
t.setVisible(true);
t.setSize(400,400);
}
}

OUTPUT

10. AIM
WRITE A JAVA PROGRAM FOR HANDLING MOUSE EVENTS .
CODE:
import java.awt.*;
import java.awt.event.*;
public class MouseLis extends Frame implements MouseListener,MouseMotionListener
{
int x,y;
String msg;
MouseLis()
{
x=10;
y=10;
msg=null;
addMouseListener(this);
addMouseMotionListener(this);

}
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,15);
g.setFont(f);
g.setColor(Color.PINK);
g.drawString(msg+"("+x+","+y+")",x,y);
}
public void mousePressed(MouseEvent e)
{
msg="Mouse Pressed";
x=e.getX();
y=e.getY();
repaint();
}
public void mouseClicked(MouseEvent e)
{
msg="Mouse Clicked";
x=e.getX();
y=e.getY();
repaint();
}

public void mouseExited(MouseEvent e)


{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
msg="Mouse Released";
x=e.getX();
y=e.getY();
repaint();
}
public void mouseDragged(MouseEvent e)
{
msg="Mouse Dragged";
x=e.getX();
y=e.getY();
repaint();
}
public void mouseMoved(MouseEvent e)
{
msg="Mouse Moved";
x=e.getX();
y=e.getY();
repaint();
}
public static void main(String args[])
{
MouseLis a=new MouseLis();
a.setVisible(true);
a.setTitle("Mouse Listener");
a.setSize(400,400);
a.addWindowListener(new Myclass());
}
}

class Myclass extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
OUTPUT

AIM
WRITE A JAVA PROGRAM FOR HANDLING KEY EVENTS.
CODE:
/*<applet Code="KeyLis.class" width=400 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyLis extends Applet implements KeyListener
{
String c=" ";
public void init()
{
addKeyListener(this);
}

public void keyPressed(KeyEvent e)


{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent e)
{
c+=e.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(c,10,20);
}
}

OUTPUT:

11. AIM

WRITE A JAVA PROGRAM THAT READS A 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 .
CODE:
import java.util.*;
import java.io.*;
import java.io.File;
class file
{
public static void main(String args[])throws IOException
{
String s=args[0];
File f=new File(s);
if(f.exists())
{
System.out.println("File exists");
System.out.println("File type is "+f.getAbsolutePath());
System.out.println("File is readable "+f.canRead( ));
System.out.println("File is writeable "+f.canWrite());
System.out.println("File length is "+f.length());
}
else
{
System.out.println("File doesnot exist");
}
}
}

OUTPUT:
AIM
WRITE A JAVA PROGRAM THAT READS A FILE AND DISPLAYS THE FILE ON THE SCREEN , WITH A
LINE NUMBER BEFORE EACH LINE .
CODE:
import java.io.*;
class Linenumber
{
public static void main(String args[])throws IOException
{
FileReader fr=new FileReader("z:\\new.txt");
LineNumberReader ln=new LineNumberReader(fr);
String line=null;
do
{
line=ln.readLine();
System.out.println("Line="+ln.getLineNumber()+" "+line);
}while(line!=null);
}
}

OUTPUT:
AIM:
WRITE A JAVA PROGRAM THAT DISPLAYS THE NUMBER OF CHARACTERS , LINES AND WORDS IN A
TEXT FILE EACH LINE .
CODE:
import java.io.*;
class Count
{
public static void main(String args[])throws IOException
{
int w=1,l=1,ch=0,c=0;
FileReader fr=new FileReader("c:\\prog\\one.txt");
do
{
c=fr.read();
ch++;
if(c=='\n')
{
w++;
l++;
}
if(c=='\t'||c==' ')
w++;
}while(c!=-1);
System.out.println("words="+w+"\nlines="+l+"\ncharacters="+ch);
}
}

OUTPUT:
// Test for primes.

class FindPrime {

public static void main(String args[]) {

int num;

boolean isPrime = true;

num = 14;

for(int i=2; i <= num/i; i++)

if((num % i) == 0)

isPrime = false;

break;

if(isPrime)

System.out.println("Prime");

else

System.out.println("Not Prime");

}
14. Aim: Write a java program that prints the meta-data of a given table

package com.javacodegeeks.jdbc.metadata;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
* @author Andres.Cespedes
* @version 1.0 $Date: 24/01/2015
* @since 1.7
*/
public class Metadata {

static Connection connection = null;


static DatabaseMetaData metadata = null;

// Static block for initialization


static {
try {
connection = DBConnection.getConnection();
} catch (SQLException e) {
System.err.println("There was an error getting the connection: "
+ e.getMessage());
}

try {
metadata = connection.getMetaData();
} catch (SQLException e) {
System.err.println("There was an error getting the metadata: "
+ e.getMessage());
}
}

/**
* Prints in the console the general metadata.
*
* @throws SQLException
*/
public static void printGeneralMetadata() throws SQLException {
System.out.println("Database Product Name: "
+ metadata.getDatabaseProductName());
System.out.println("Database Product Version: "
+ metadata.getDatabaseProductVersion());
System.out.println("Logged User: " + metadata.getUserName());
System.out.println("JDBC Driver: " + metadata.getDriverName());
System.out.println("Driver Version: " + metadata.getDriverVersion());
System.out.println("\n");
}

/**
*
* @return Arraylist with the table's name
* @throws SQLException
*/
public static ArrayList getTablesMetadata() throws SQLException {
String table[] = { "TABLE" };
ResultSet rs = null;
ArrayList tables = null;
// receive the Type of the object in a String array.
rs = metadata.getTables(null, null, null, table);
tables = new ArrayList();
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME"));
}
return tables;
}

/**
* Prints in the console the columns metadata, based in the Arraylist of
* tables passed as parameter.
*
* @param tables
* @throws SQLException
*/
public static void getColumnsMetadata(ArrayList tables)
throws SQLException {
ResultSet rs = null;
// Print the columns properties of the actual table
for (String actualTable : tables) {
rs = metadata.getColumns(null, null, actualTable, null);
System.out.println(actualTable.toUpperCase());
while (rs.next()) {
System.out.println(rs.getString("COLUMN_NAME") + " "
+ rs.getString("TYPE_NAME") + " "
+ rs.getString("COLUMN_SIZE"));
}
System.out.println("\n");
}

}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
printGeneralMetadata();
// Print all the tables of the database scheme, with their names and
// structure
getColumnsMetadata(getTablesMetadata());
} catch (SQLException e) {
System.err.println("There was an error retrieving the metadata
properties: " + e.getMessage());
}
}}

OUT PUT:

The connection is successfully obtained


Database Product Name: MySQL
Database Product Version: 5.6.22-log
Logged User: admin@localhost
JDBC Driver: MySQL Connector Java
Driver Version: mysql-connector-java-5.1.34 ( Revision: jess.balint@oracle.com-
20141014163213-wqbwpf1ok2kvo1om )

CITY
idcity INT 10
name VARCHAR 45
population INT 10
department INT 10

COUNTRY
idcountry INT 10
name VARCHAR 45
pib INT 10

DEPARTMENT
idDepartment INT 10
name VARCHAR 6

************** The End ***************

Das könnte Ihnen auch gefallen