28
LAB MANUAL IT 262 Java Programming Lab For II/IV B.Tech Information Technology II Semester Department of Information Technology VELAGAPUDI RAMAKRISHNA SIDDHARTHA ENGINEERING COLLEGE VIJAYAWADA-520 007(A.P) 1

java lab manual IT-262

Embed Size (px)

Citation preview

Page 1: java lab manual IT-262

LAB MANUALIT 262 Java Programming Lab

For II/IV B.TechInformation Technology

II Semester

Department of Information TechnologyVELAGAPUDI RAMAKRISHNA SIDDHARTHA ENGINEERING COLLEGE

VIJAYAWADA-520 007(A.P)

1

Page 2: java lab manual IT-262

INSTRUCTIONS TO BE FOLLOWED IN MAINTAINING THE RECORD BOOK

The Record should be written neatly with ink on the right hand page only. The left hand page being reserved for diagrams.

The Record should contain:

1. The date2. The number and name of the experiment3. The aim of the experiment4. Algorithm5. Program6. On the left hand side, Flow charts should be designed7. On the left hand side, Input & Output should be mentioned.8. Index must be filled in regularly.9. You must get your record certified by the concerned staff on the very next class after completing the

experiment10. You must get your record certified by the concerned staff at the end of every semester.

INSTRUCTIONS TO BE FOLLOWED IN THE LABORATORY

1. You must bring record observations notebook, while coming to the practical class without you may not be allowed to the practical.

2. Don’t touch the equipment which is not connected with our experiment.

3. When the system /apparatus is issued, you are advised to check their conditions.

4. You should not leave the laboratory without obtaining the signature of the concerned lecturer after completing the practical

Note:

1. Damaged caused to the property of the laboratory will be recovered

2. If 75 % of the experiments prescribed are not completed the candidate will not be allowed for attending examinations.

2

Page 3: java lab manual IT-262

INDEX

S.NO NAME OF THE EXPERIMENT PAGE.NO

LAB CYCLE1

1 Write a program using command line arguments.

4

2 Write a program by creating a class vehicle and calculate the range of vehicle.

4

3 Write a program to calculate the area of rectangle using parameterized constructor.

5

4 Write a program using method overloading. 5

5 Write a program using constructor overloading.

6

6 Write a program for single inheritance using overriding concept.

7

7 Calculate the area of triangle and rectangle by using abstract class.

8

8 Demonstrate the functionality of packages. 9 9 Write a program using interface area and

compute area of rectangle and circle. 10

10 Develop an applet for different figures. 10

11 Write a program using AWT to demonstrate Button implementation.

11

12 Write a program using AWT to demonstrate Checkbox implementation.

12

13 Write a program using AWT to demonstrate Radio Button implementation.

14

14 Write a program using AWT to demonstrate Choice implementation.

15

15 Write a program using Swings to demonstrate the implementations of various components.

16

16 Develop an applet that sums given two numbers.

17

17 Program to arrange the given strings in alphabetical order.

18

18 Write a JDBC program to select the values from the department table. 19

19 Write a JDBC program to insert the values into the student table. 20

20 Write a JDBC program to alter and insert the values into table. 21

21 Write a JDBC program to delete a record by taking the input from keyboard. 22

3

Page 4: java lab manual IT-262

22 Write a JDBC program to insert the values into booktable using command line arguments.

22

1.COMMAND LINE ARGUMENTS

class ComLineTest{

public static void main(String args[]){

int count,i=0;String string;count=args.length;System.out.println("Number of Arguments="+count);while(i<count){

string=args[i];i=i+1;System.out.println(i+": Java is "+string+"!");

}}

}

2.Write a program by creating a class vehicle and calculate the range of vehicle.

class Vehicle{

int passengers;int fuelcap;int mpg;int range(){

return mpg*fuelcap;}

}

class RetMeth{

public static void main(String args[]){

Vehicle minivan=new Vehicle();Vehicle sportscar=new Vehicle();int range1,range2;minivan.passengers=7;minivan.fuelcap=16;minivan.mpg=21;sportscar.passengers=2;sportscar.fuelcap=14;

4

Page 5: java lab manual IT-262

sportscar.mpg=12;range1=minivan.range();range2=sportscar.range();System.out.println("Minivan can carry "+minivan.passengers+" with range of

"+range1+" Miles");System.out.println("Sportscar can carry "+sportscar.passengers+" with range of

"+range2+" Miles");}

}

3. Write a program to calculate the area of rectangle using parameterized constructor.class Rectangle{

int length;int width;Rectangle(int x,int y){

length=x;width=y;

}int rectArea(){

return(length*width);}

}

class RectangleArea{

public static void main(String args[]){

Rectangle rect1=new Rectangle(15,10);int area1=rect1.rectArea();System.out.println("Area1="+area1);

}}

4. Write a program using method overloading.

class Overload{

void ovlDemo(){

System.out.println("No Parameters");}void ovlDemo(int a){

System.out.println("One Parameter:"+a);}int ovlDemo(int a,int b)

5

Page 6: java lab manual IT-262

{System.out.println("Two Parameters:"+a+" "+b);return a+b;

}double ovlDemo(double a,double b){

System.out.println("Two Double Parameters:"+a+" "+b);return a+b;

}}

class OverloadDemo{

public static void main(String args[]){

Overload ob=new Overload();int resI;double resD;ob.ovlDemo();System.out.println();ob.ovlDemo(2);System.out.println();resI=ob.ovlDemo(4,6);System.out.println("Result of ob.ovlDemo(4,6): "+resI);System.out.println();resD=ob.ovlDemo(1.1,2.32);System.out.println("Result of ob.ovlDemo(1.1,2.32): "+resD);

}}

5. Write a program using constructor overloading.

class Box{

double width;double height;double depth;Box(double w,double h,double d){

width=w;height=h;depth=d;

}Box(){

width=-1;height=-1;depth=-1;

}Box(double len)

6

Page 7: java lab manual IT-262

{width=height=depth=len;

}double volume(){

return width*height*depth;}

}

class OverloadCons{

public static void main(String args[]){

Box mybox1=new Box(10,20,15);Box mybox2=new Box();Box mycube=new Box(7);double vol;vol=mybox1.volume();System.out.println("Volume of mybox1 is "+vol);vol=mybox2.volume();System.out.println("Volume of mybox2 is "+vol);vol=mycube.volume();System.out.println("Volume of mycube is "+vol);

}}

6. Write a program for single inheritance using overriding concept.

class A {

int i, j;A(int a, int b) {

i = a;j = b;

}void show() {

System.out.println("i and j: " + i + " " + j);}

}

class B extends A {

int k;B(int a, int b, int c) {

super(a, b);k= c;

}void show(String msg)

7

Page 8: java lab manual IT-262

{System.out.println("k: " + k);

}}

class Override {

public static void main(String args[]) {

B subOb = new B(1, 2, 3);subOb.show("This is k");subOb.show();

}}

7. Calculate the area of triangle and rectangle by using abstract class.

abstract class Figure {

double dim1;double dim2;Figure(double a, double b) {

dim1 = a;dim2 = b;

}abstract double area();

}

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b);}double area() {

System.out.println("Inside Area for Rectangle.");return dim1 * dim2;

}}

class Triangle extends Figure {

Triangle(double a, double b) {

super(a, b);}double area()

8

Page 9: java lab manual IT-262

{System.out.println("Inside Area for Triangle.");return dim1 * dim2 / 2;

}}

class AbstractAreas {

public static void main(String args[]) {

Rectangle r = new Rectangle(9, 5);Triangle t = new Triangle(10, 8);Figure figref;figref = r;System.out.println("Area is " + figref.area());figref = t;System.out.println("Area is " + figref.area());

}}

8. Demonstrate the functionality of packages.

package MyPack;

public class Balance{

String name;double bal;public Balance(String n,double b){

name=n;bal=b;

}public void Show(){

if(bal<0){

System.out.print("--> ");}System.out.println(name + ": $" + bal);

}}

TESTBALANCE.JAVA

import MyPack.*;

class TestBalance{

public static void main(String args[])9

Page 10: java lab manual IT-262

{Balance test=new Balance("J.J.Jaspers",99.88);test.Show();

}}

9. Write a program using interface area and compute area of rectangle and circle.

interface Area{

final static float pi=3.14f;float compute(float x,float y);

}

class Rectangle implements Area {

public float compute(float x,float y){

return(x*y);}

}

class Circle implements Area {

public float compute(float x,float y){

return(pi*x*x);}

}

class InterfaceTest{

public static void main(String args[]){

Rectangle rect=new Rectangle();Circle cir=new Circle();Area area;area=rect;System.out.println("Area of Rectangle:"+area.compute(10,20));area=cir;System.out.println("Area of Circle:"+area.compute(10,0));

}}

10. Develop an applet for different figures.

10

Page 11: java lab manual IT-262

import java.awt.*;import java.applet.*;

/*<applet code="GraphicsDemo" width=400 height=400></applet>*/

public class GraphicsDemo extends Applet{

public void paint(Graphics g){

setBackground(Color.pink);setForeground(Color.blue);Font f=new Font("Arial",Font.ITALIC,10);g.setFont(f);g.drawLine(20,20,50,50);g.drawString("Line",20,70);g.drawRect(100,20,50,50);g.drawString("Rectangle",100,100);g.fillRoundRect(200,20,80,50,10,10);g.drawString("Filled Round Rect",200,100);g.drawOval(20,100,50,80);g.drawString("Oval",25,200);g.fillOval(100,130,50,50);g.drawString("Circle",110,200);g.drawString("WELCOME TO GRAPHICS",130,350);

}}

11. Write a program using awt and develop the output as follows.

import java.awt.*;import java.awt.event.*;import java.applet.*;

/*

11

Yes NO May be Yes NO May be

Page 12: java lab manual IT-262

<applet code="ButtonDemo" width=250 height=150></applet>*/

public class ButtonDemo extends Applet implements ActionListener{

String msg="";Button yes,no,maybe;public void init(){

yes=new Button("Yes");no=new Button("No");maybe=new Button("Undecided");add(yes);add(no);add(maybe);yes.addActionListener(this);no.addActionListener(this);maybe.addActionListener(this);

}public void actionPerformed(ActionEvent ae){

String str=ae.getActionCommand();if(str.equals("Yes")){

msg="You pressed Yes.";}else if(str.equals("No")){

msg="You pressed No.";}else{

msg="You pressed Undecided.";}repaint();

}public void paint(Graphics g){

g.drawString(msg,6,100);}

}

12. Write a java program to get the following output .

12

Windows xp

Windows 98

Windows 2000

Dos

Windows xp false Windows 98 false Windows 2000 false

Page 13: java lab manual IT-262

import java.awt.*;import java.awt.event.*;import java.applet.*;

public class Checkboxdemo extends Applet implements ItemListener{

String msg="";Checkbox winxp,winvista,solaris,macos;public void init(){

winxp=new Checkbox("windowsxp",true);winvista=new Checkbox("windows vista");solaris=new Checkbox("solaris");macos=new Checkbox("macos");add(winxp);add(winvista);add(solaris);add(macos);winxp.addItemListener(this);winvista.addItemListener(this);solaris.addItemListener(this);macos.addItemListener(this);

}public void itemStateChanged(ItemEvent ie){

repaint();}public void paint(Graphics g){

msg="current state:";g.drawString(msg,6,80);msg="windows xp:"+winxp.getState();g.drawString(msg,6,100);msg="windows vista:"+winvista.getState();g.drawString(msg,6,120);msg="solaris:"+solaris.getState();g.drawString(msg,6,140);msg="mac os:"+macos.getState();g.drawString(msg,6,160);

}}

13

Page 14: java lab manual IT-262

/*<applet code="Checkboxdemo" width=250 height=200></applet>*/

13. Develop the following applet using awt-

Dos XP

Solarisimport java.awt.*;import java.awt.event.*;import java.applet.*;

public class cbg extends Applet implements ItemListener{

String msg="";CheckboxGroup cbg;Checkbox winxp,winvista,solaris,macos;public void init(){

cbg=new CheckboxGroup();winxp=new Checkbox("windowsxp",cbg,true);winvista=new Checkbox("windows vista",cbg,false);solaris=new Checkbox("solaris",cbg,false);macos=new Checkbox("macos",cbg,false);add(winxp);add(winvista);add(solaris);add(macos);winxp.addItemListener(this);winvista.addItemListener(this);solaris.addItemListener(this);macos.addItemListener(this);

}public void itemStateChanged(ItemEvent ie){

repaint();}public void paint(Graphics g){

msg="current selection:";msg +=cbg.getSelectedCheckbox().getLabel();g.drawString(msg,6,100);

}}

/*<applet code=cbg height=400 width=400>

14

Page 15: java lab manual IT-262

</applet>*/

14. Write a program using AWT to demonstrate Choice implementation.

import java.awt.*;import java.awt.event.*;import java.applet.*;

public class ChoiceDemo extends Applet implements ItemListener{

Choice os,browser;String msg="";public void init(){

os=new Choice();browser=new Choice();os.add("Windows XP");os.add("Windows Vista");os.add("Solaris");os.add("Mac OS");browser.add("Internet Explorer");browser.add("Firefox");browser.add("Opera");add(os);add(browser);os.addItemListener(this);browser.addItemListener(this);

}public void itemStateChanged(ItemEvent ie){

repaint();}public void paint(Graphics g){

msg="Current OS: ";msg+=os.getSelectedItem();g.drawString(msg,6,120);msg="Current Browser: ";msg+=browser.getSelectedItem();g.drawString(msg,6,140);

}}

/*<applet code="ChoiceDemo" width=300 height=180></applet>

15

Page 16: java lab manual IT-262

*/

15. Develop the following application using swings.

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Radio1 extends JApplet{

DrawOn canvas=new DrawOn();ButtonGroup group=new ButtonGroup();JRadioButton square=new JRadioButton("square");JRadioButton circle=new JRadioButton("circle",true);Color thecolor[]={Color.red,Color.blue,Color.green};String colorName[]={"red","blue","green"};JComboBox color=new JComboBox(colorName);public void init(){

Container c=getContentPane();c.setLayout(new FlowLayout());c.add(color);group.add(square);group.add(circle);c.add(square);c.add(circle);c.add(canvas);canvas.setPreferredSize(new Dimension(200,200));color.addItemListener(canvas);circle.addItemListener(canvas);square.addItemListener(canvas);

16

O circle O square

Red

Blue

Green

Orange

Page 17: java lab manual IT-262

}class DrawOn extends JPanel implements ItemListener{

boolean c=true;public void itemStateChanged(ItemEvent ie){

Object source=ie.getItem();if(source==circle)

c=true;else if(source==square)

c=false;repaint();

}public void paintComponent(Graphics g){

super.paintComponent(g);g.setColor(thecolor[color.getSelectedIndex()]);if(c)

g.fillOval(20,20,100,100);else

g.fillRect(20,20,100,100);}

}}

/*<applet code="Radio1" width=300 height=300></applet>*/

16. Develop an applet that Sum’s given two numbers

16. 16. WAP to Sele

import java.awt.*;import java.applet.*;

public class UserIn extends Applet{

TextField text1,text2;

17

123

Input a number in each BoxThe Sum is: 246

123

Page 18: java lab manual IT-262

public void init(){

text1=new TextField(8);text2=new TextField(8);add(text1);add(text2);text1.setText("0");text2.setText("0");

}public void paint(Graphics g){

int x=0,y=1,z=1;String s1,s2,s;g.drawString("INPUT A NUMBER IN EACH BOX ",10,50);try{

s1=text1.getText();x=Integer.parseInt(s1);s2=text2.getText();y=Integer.parseInt(s2);

}catch(Exception ex){}z=x+y;s=String.valueOf(z);g.drawString("THE SUM IS:",10,75);g.drawString(s,100,75);

}public boolean action(Event event,Object object){

repaint();return true;

}}

/*<applet code=UserIn.class width=300 height=200></applet>*/

17. Write a program to Arrange the Given Strings in Alphabetical Order: Madras

DelhiAhmedabadCalcuttaBombay

class StringOrdering18

Page 19: java lab manual IT-262

{static String name[]={"Madras","Delhi","Ahmedabad","Calcutta","Bombay"};public static void main(String args[]){

int size=name.length;String temp=null;for(int i=0;i<size;i++){

for(int j=i+1;j<size;j++){

if(name[j].compareTo(name[i])<0){

temp=name[i];name[i]=name[j];name[j]=temp;

}}

}for(int i=0;i<size;i++){

System.out.println(name[i]);}

}}

18. Write a program to select values from the Department Table Using JDBC.

import java.io.*;import java.sql.*;import sun.jdbc.odbc.*;

class Department{public static void main(String args[]){try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundException e1){System.out.println("error was caught"+e1.getMessage());}try{Connection con=DriverManager.getConnection("jdbc:odbc:Nani","y06it026","");Statement stmt=con.createStatement();

19

Page 20: java lab manual IT-262

ResultSet rs=stmt.executeQuery("select * from emp26");while(rs.next()){System.out.println(rs.getInt(1)+rs.getString(2)+rs.getString(3));}}catch(SQLException e2){System.out.println("error caught"+e2.getMessage());}}}

19. Write a program to insert values into Student Table Using JDBC.

import java.sql.*;

class Emp12{

public static void main(String args[]){

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundException e1){

System.out.println("error was caught" +e1);} try{

Connection conn=DriverManager.getConnection("jdbc:odbc:Nani","y06it026",""); PreparedStatement psmt=conn.prepareStatement("insert into std values(?,?,?)");psmt.setInt(1,104);psmt.setString(2,"ddd");psmt.setString(3,"pmcs");psmt.executeUpdate();psmt.setInt(1,105);psmt.setString(2,"fff");psmt.setString(3,"pmcs");psmt.executeUpdate();Statement stmt=conn.createStatement();ResultSet rs=stmt.executeQuery("select * from std");while(rs.next()){

System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));}conn.close();

20

Page 21: java lab manual IT-262

}catch(SQLException e2){

System.out.println("error caught"+e2.getMessage());}

}}

20. Write a program to alter and Insert the values into Table Using JDBC.

import java.sql.*;

class Stu{

public static void main(String args[])throws Exception{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection conn=DriverManager.getConnection("jdbc:odbc:Nani","y06it026","nani");Statement stmt=conn.createStatement();conn.setAutoCommit(false);stmt.executeUpdate("create table stu999(sno number(5),sname char(10),marks number(5))");stmt.executeUpdate("alter table stu999 add(totalmarks number(5))");System.out.println("table altered");stmt.executeUpdate("insert into stu999 values(101,'aaa',25,50)");stmt.executeUpdate("insert into stu999 values(102,'bbb',35,40)");stmt.executeUpdate("insert into stu999 values(103,'ccc',15,60)");ResultSet rs=stmt.executeQuery("select * from stu999");while(rs.next()){

System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\t"+rs.getInt(4));

}conn.commit();System.out.println("table updated");stmt.executeUpdate("update stu999 set sno=104 where sname='aaa'");Statement stmt1=conn.createStatement();ResultSet rs1=stmt1.executeQuery("select * from stu999");while(rs1.next()){

System.out.println(rs1.getInt(1)+"\t"+rs1.getString(2)+"\t"+rs1.getInt(3)+"\t"+rs1.getInt(4));

}stmt.close();stmt1.close();

}}

21

Page 22: java lab manual IT-262

21. Write a program to delete a Record by giving Input in run-time using keyboard.

import java.sql.*;import java.io.*;

class Emp11q{

public static void main(String args[])throws Exception{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection conn=DriverManager.getConnection("jdbc:odbc:Nani","y06it026","");Statement stmt=conn.createStatement();DataInputStream dis=new DataInputStream(System.in);System.out.println("Write EmpNO:");int no=Integer.parseInt(dis.readLine());int n=stmt.executeUpdate("delete from ja26 where eno="+no+"");System.out.println(n+"rows deleted");conn.close();

}}

22. Write a program to Insert Values into Book table Using Command Line Arguments.

import java.sql.*;

class Book{

public static void main(String args[]){

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundException e1){

System.out.println("error was caught"+e1.getMessage());} try{

Connection conn=DriverManager.getConnection("jdbc:odbc:Nani","y06it026","");Statement stmt=conn.createStatement(); int bookID=Integer.parseInt(args[0]);String bookname=args[1];int price=Integer.parseInt(args[2]);

22

Page 23: java lab manual IT-262

stmt.executeUpdate("create table book(bookID number(5),bookname varchar2(20),price number(5))");

int n=stmt.executeUpdate("insert into book values("+bookID+",'"+bookname+"',"+price+")");

if(n>0)System.out.println("Successfully inserted");

elseSystem.out.println("not Successfully inserted");

conn.close();}catch(Exception e2){

System.out.println("error was caught"+e2.getMessage());}

}

}

23