0% found this document useful (0 votes)
7 views69 pages

Java Programming (MDE117A) - Lab Manual

The lab manual provides step-by-step instructions for setting up a Java programming environment, creating projects in Eclipse, and writing various Java programs. It covers topics such as expression evaluation, control statements (if, switch), loops, and the use of arrays and vectors. Additionally, it includes examples of constructors, inheritance, and wrapper classes, along with sample outputs for each program.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views69 pages

Java Programming (MDE117A) - Lab Manual

The lab manual provides step-by-step instructions for setting up a Java programming environment, creating projects in Eclipse, and writing various Java programs. It covers topics such as expression evaluation, control statements (if, switch), loops, and the use of arrays and vectors. Additionally, it includes examples of constructors, inheritance, and wrapper classes, along with sample outputs for each program.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lab Manual

Program 1 : Setup Java Programming development environment using: Command prompt.(Classpath and path setup)
Any IDE (Eclipse, Netbeans, VScode, Jcreatoretc.).
Soln. :

(a) Path setup

1. After installing jdk. Open command prompt.

2. Set Path using.


Set CLASSPATH = C:\jdk\bin

(b) Launch

Step 0 : Launch Eclipse

1. Eclipse by running "[Link]" from the Eclipse installed directory.

2. Choose an appropriate directory for your workspace, i.e., where you would like to save your files
(e.g., c:\myproject\eclipse for Windows).

3. If the "Welcome" screen shows up, close it by clicking the "cross" button next to the "Welcome" title.

Step 1 : Create a new Java Project


To create a new Java project

1. Select "File" menu ⇒ "New" ⇒ "Java project" (or "File" ⇒ "New" ⇒ "Project" ⇒ "Java project").

2. The "New Java Project" dialog pops up.


3. In "Project name", enter "MyProject".

4. Check "Use default location".

5. In "JRE", select "Use default JRE (currently 'JDK10.0.x')". But make sure that your JDK is 1.8 and above.
6. In "Project Layout", check "Use project folder as root for sources and class files".
Click "Next" button.

7. Uncheck "Create [Link] file" box (if it is checked) ⇒ Finish.

Step 2 : Write a Hello-world Java Program


1. In the "Package Explorer" (left side pane) ⇒ Right-click on "MyProject" ⇒ New ⇒ Class.
2. The "New Java Class" dialog pops up.
3. In "Source folder", keep the "MyProject".
4. In "Package", delete the content if it is not empty.
5. In "Name", enter "HelloWorld".
6. Check "public static void main(String ar[ ])".

7. Don't change the rest.


Java Programming L-2 Lab Manual

Push "Finish" button.

8. The source file "[Link]" opens on the editor panel (the center pane). Enter the following codes :
public class HelloWorld {
public static void main(String ar[ ]) {
[Link]("Hello, world!");
}
}

Step 3 : Compile and Execute the Java Program


1. There is no need to compile the Java source file in Eclipse explicitly. It is because Eclipse performs the so-called
incremental compilation, i.e., the Java statement is compiled as and when it is entered.
2. To run the program, right-click anywhere on the source file "[Link]" ⇒ Run As ⇒ Java Application.

3. The output "Hello, world!" appears on the Console panel (the bottom pane).
Java Programming L-3 Lab Manual

Program 2 : Write programs to evaluate different types of expressions.

Soln. :

import [Link];
class ExpressionEvaluation
{
public static void main(String ar[ ])
{
int n1, n2, ad, sub, mult;
int leftShift, rightShift, bitwiseAnd, bitwiseOr;
float div;
Scanner sc = new Scanner([Link]);
[Link]("Enter 2 values");
n1 = [Link]( );
n2 = [Link]( );
ad = n1 + n2;
sub = n1 - n2;
mult = n1 * n2;
div = n1 / (float)n2;
[Link]("Addition is : " + ad);
Java Programming L-4 Lab Manual

[Link]("Subtraction is : " + sub);


[Link]("Multiplication is : " + mult);
[Link]("Division is : " + div);
leftShift = n1 << 2;
rightShift = n1 >> 2;
bitwiseAnd = n1 & n2;
bitwiseOr = n1 | n2;
[Link]("n1 Leftshift 2 is : " + leftShift);
[Link]("n1 rightshift 2 is : " + rightShift);
[Link]("n1 bitwise AND n2 is : " + bitwiseAnd);
[Link]("n1 bitwise OR n2 is : " + bitwiseOr);
}
}
The output of above program will be :

Program 3 : Write programs to demonstrate use of :

if statements (all forms of if statement Switch – Case statement

Different types of Loops(for,while and do..while).


Soln. :

The if statement

import [Link];
class ifdemo
{
public static void main(String ar[ ])
{
int age;
Java Programming L-5 Lab Manual

Scanner s1=new Scanner([Link]);


[Link]("Enter age");
age=[Link]( );
if(age>18)
[Link]("age is above 18");
}
}

Output

The if else Statement


import [Link];
class demo
{
public static void main(String ar[ ])
{
int marks;
Scanner s1=new Scanner([Link]);
[Link]("Enter Marks");
marks=[Link]( );
if(marks>40)
[Link]("Pass!!!");
else
[Link]("Fail!!!");
}
}

Output
Java Programming L-6 Lab Manual

else if Ladder

import [Link].*;
class Exbuff
{
public static void main(String ar[ ]) throws IOException
{
int Java,Sys,IP,total,avg;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter marks of Java: ");
Java = [Link]([Link]( ));
Marks
[Link]("Enter marks of Sys: ");
are
Sys = [Link]([Link]( )); accepted
and
[Link]("Enter marks of IP: ");
converte
IP = [Link]([Link]( )); d in int
total = Java + Sys + IP;
avg = total / 3;
[Link]("Total marks : "+total);
[Link]("Average : "+avg);
if(Java>=40 && Sys>=40 && IP>=40)
{
Student should
if(avg>=80)
pass in all subjects
[Link]("Grade : A");
else if(avg>=60)
[Link]("Grade : B");
else if(avg>=40)
[Link]("Grade : C");
}
else
[Link]("Fail...");
}
}
Output
Java Programming L-7 Lab Manual

Switch Case statement

import [Link].*;
class Exbuff
{
public static void main(String ar[ ]) throws IOException
{
int n1=0,n2=0,r,ch;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("1 : Addition");
[Link]("2 : Subtraction"); Displaying
[Link]("3 : Multiplcation"); menu

[Link]("4 : Division");
[Link]("Select your choice : ");
ch = [Link]([Link]( ));
if(ch>=1 && ch<=4) Accept numbers only
{ for valid choice

[Link]("Enter first number : ");


n1 = [Link]([Link]( ));
[Link]("Enter second number : ");
n2 = [Link]([Link]( ));
}
switch(ch)
{
case 1:
r = n1 + n2;
[Link]("Summation is "+r);
break;
case 2:
r = n1 - n2;
[Link]("Subtraction is "+r);
break;
case 3:
r = n1 * n2;
[Link]("Multiplication is "+r);
break;
case 4:
Java Programming L-8 Lab Manual

if(n2!=0)
Division by zero is
{ not allowed
r = n1 / n2;
[Link]("Division is "+r);
}
else
[Link]("Cannot divide by zero");
break;
default :
[Link]("Invalid choice");
}
}
}

Output

use of Looping Statement ‘for

class testpr
{
public static void main(String ar[ ])
{
int i,sum;
sum = 0;
for(i=101;i<200;i++)
{
if(i%7==0)
{
sum = sum + i;
}
}
Java Programming L-9 Lab Manual

[Link]("Sum is "+sum);
}
}

Output

Do -While

class testpr
{
public static void main(String ar[ ])
{
int a,b,c,i;
a = 1;
b = 2;
i = 1;
[Link]("1 1 2");
do
{
c = a + b;
[Link](" "+c);
a = b;
b = c;
i = i + 1;
}while(i<9);
}
}

Output
Java Programming L-10 Lab Manual

While loop

import [Link].*;
class sumofdig
{
public static void main(String ar[ ])
{
Scanner sc = new Scanner([Link]);
int n,rem,sum;
sum = 0;
[Link]("Enter a number :");
n = [Link]( );
while(n>0)
{
rem = n % 10;
sum = sum + rem ;
n = n / 10;
}
[Link]("Sum of digits : "+sum);
}
}

Output

Program 4 : Write programs for implementation of differentmethods of :


String class.
StringBuffer class.
Soln. :

String class

class exTest
{
public static void main(String ar[ ])
Java Programming L-11 Lab Manual

{
String str = "Kunal";
String str1 = "Phoenix InfoTech";
[Link](str);
[Link](str1);
[Link]([Link](2));
[Link]([Link]( ));
[Link]([Link](1));
[Link]([Link](1,3));
[Link]([Link]("Ku"));
[Link]([Link]("abc"));
[Link]([Link]("KUNAL"));
[Link]([Link]("KUNAL"));
}
}

Output

StringBuffer class

class exTest2
{
public static void main(String ar[ ])
{
String str = "Kunal";
String str1 = "Phoenix InfoTech";
[Link]([Link]('e'));
[Link]([Link]('e'));
[Link]("Hello ".concat(str));
[Link]([Link](str1));
[Link]([Link]( ));
Java Programming L-12 Lab Manual

[Link]([Link]( ));
[Link]([Link]('l','m'));
[Link]([Link]("Info"));
[Link](" Hello ".trim( ));
}
}

Output

Program 5 : Write programs to demonstrate :

Use of Array.

Use of Vectors
Soln. :

Use of Array

One dimensional array

class Exarray
{
public static void main (String ar[ ])
{
int[] myArray; Declares an Array of
integers

myArray = new int[5]; Allocating memory


for 5 integers.

myArray[0] = 10; Initialize the first


elements of the array
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;
for (int i = 0; i < [Link]; i++)
Java Programming L-13 Lab Manual

[Link]("Element at index " + i +


" : "+ myArray[i]);
}
Accessing the elements
} of the specified array

Output

Two dimensional array

class Exarray
{
public static void main (String ar[ ])
{
int myarr[][]={{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](myarr[i][j]+" ");
}
[Link]( );
}
}
}

Output
Java Programming L-14 Lab Manual

Use of Vectors :

import [Link].*;
class coll7
{
public static void main(String ar[ ])
{
Scanner sc = new Scanner([Link]);
Vector v = new Vector(5);
[Link]("Current size "+[Link]( ));

[Link](new Integer(10));
[Link](new Integer(20));
[Link](new Float(4.5));
[Link](new Float(80.90));
[Link]("ABC");
[Link]("XYZ");

[Link]("Current size "+[Link]( ));


[Link]("First : "+[Link]( ));
[Link]("Last : "+[Link]( ));
[Link]("All elements : "+v);

[Link]("Enter element to remove :");


String ele = [Link]( );
[Link](ele);
[Link]("After removal : "+v);
}
}

Output
Java Programming L-15 Lab Manual

Program 6 : Write programs using Wrapper Class :

to convert primitive into object.

to convert object into primitive.


Soln. :

public class ExWrp


{
public static void main(String ar[ ]){

int x=15;
Converting int to
Integer y = [Link](x);
integer

autoboxing, now compiler


Integer z = x;
will write [Link](x)
internally
[Link](x+" "+y+" "+z);
}
}

Output

Wrapper Class to convert object into primitive

public class ExWrp


{
public static void main(String ar[ ]){
Integer x=new Integer(10);

int y=[Link]( ); Converting integer to int

int z=x; Unboxing, now compiler will


write [Link] internally.

[Link](x+" "+y+" "+z);


}
}
Java Programming L-16 Lab Manual

Output

Program 7 : Develop a program for implementation of different types of constructors.


Soln. :

(a) Develop a program for implementation of constructor

class ExCons
{

int n1,n2,sum;

ExCons( )
{

[Link]("This is default constructor");

n1 = 10; Definition of
default constructor
n2 = 5;

}
void cal( )
{
sum = n1 + n2;
[Link]("Summation is "+sum);
}
}
class ExCons1
{

public static void main(String ar[ ])

ExCons obj = new ExCons( );

[Link]( );
Default constructor get called
}
}
Java Programming L-17 Lab Manual

Output

(b) Develop a program for implementation of multiple constructors in a class

class ExCons
{
int n1,n2,sum;
ExCons( )
{
n1 = 0; Definition of default
n2 = 0; constructor

}
ExCons(int x, int y)
{
[Link]("This is parameterized constructor");
n1 = x;
Definition of
n2 = y; parameterized
} constructor

void cal( )
{
sum = n1 + n2;
[Link]("Summation is "+sum);
}
}
class ExCons1
{
public static void main(String ar[ ])
{
new ExCons( ); Default constructor get called
ExCons obj = new ExCons(10,20);
[Link]( ); Parameterized
} constructor get
called
}
Java Programming L-18 Lab Manual

Output

Program 8 : Develop program to implement : Single inheritance, Multilevel inheritance


Soln. :

Single Inheritance

class A
{
void displayBase( )
{
[Link]("Base Class Method");
}
}

Extends keyword is
class B extends A used to inherit a
{ class

void displayDerived( )
{
[Link]("Derived Class Method");
}
}
class inh
{
public static void main(String ar[ ])
{
Base class method
B obj = new B( ); can be accessed
[Link]( ); using derived class
object
[Link]( );
}
}
Java Programming L-19 Lab Manual

Output

Multilevel Inheritance
class A
{
void display1( )
{
[Link]("Class A Method");
}
}
class B extends A
{
void display2( )
{
[Link]("Class B Method");
}
}
class C extends B
{
void display3( )
{
[Link]("Class C Method");
}
}
class inh
{
public static void main(String ar[ ])
{
C obj = new C( );
obj.display1( ); Object of class C can
access members of
obj.display2( ); both class A and B
obj.display3( );
}
}
Java Programming L-20 Lab Manual

Output

Program 9 : * Develop program for implementation of interface .

Soln. :
interface Animal
{
public void sound( );
public void foundin( );
}
class Dog implements Animal
{
public void sound( )
{
[Link]("Dog Barks");
}

public void foundin( )


{
[Link]("Dogs are found in home and streets");
}
}
class Monkey implements Animal
{
public void sound( )
{
[Link]("Monkey Gibbers");
}
public void foundin( )
{
[Link]("Monkeies are found in jungle and streets");
}
}
Java Programming L-21 Lab Manual

class InterfaceTest
{
public static void main(String ar[ ])
{
Dog d1 = new Dog( );
[Link]( );
[Link]( );

[Link]( );
Monkey m1 = new Monkey( );
[Link]( );
[Link]( );
}
}
The output of above program will be :

Program 10 : Write programs to demonstrate use of :

Built in packages

User defined packages.


Soln. :

Program 10.1 : Builtinpackages

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Java Programming L-22 Lab Manual

class DemoBuiltinPackages
{
public static void main(String ar[ ]) throws UnknownHostException, IOException
{
// Accepting 3 Strings using class Scanner
Scanner sc = new Scanner([Link]);
[Link]("Enter 3 Names");
String s1 = [Link]( );
String s2 = [Link]( );
String s3 = [Link]( );

// Accepting integer, float and String using DataInputStream


DataInputStream dis = new DataInputStream([Link]);
[Link]("Enter integer, float and String values");
int n1 = [Link]([Link]( ));
float f1 = [Link]([Link]( ));
String s4 = [Link]( );

// Obtianing InetAddress of localhost


[Link]("Obtaining InetAddress of localhost");
InetAddress i1 = [Link]( );

// Adding all above objects into Vector


Vector v1 = new Vector(5);
[Link]("Adding elements into Vector");
[Link](s1);
[Link](s2);
[Link](s3);
[Link](n1);
[Link](f1);
[Link](s4);
[Link](i1);

[Link]("All Elements added in Vector");

}
}
Java Programming L-23 Lab Manual

The output of above program will be :

Program 10.2 : Userdefinedpackages.

File 1 : [Link]

package mypack1;
public class ArithmeticOperations
{
public int getAddition(int x, int y)
{
return(x+y);
}
public int getSubtraction(int x, int y)
{
return(x-y);
}
}
File 2 : [Link]
package mypack1;
public class RelationalOperations
{
public int getLargest(int x, int y)
{
return x>y ? x : y;
}
Java Programming L-24 Lab Manual

public int getSmallest(int x, int y)


{
return x<y ? x : y;
}
}
File 3 : [Link]

import [Link];
import [Link];
class DemoUserDefinedPackages
{
public static void main(String ar[ ])
{
[Link] op1 = new [Link]( );
[Link] op2 = new [Link]( );

[Link]("Addition of 10 and 20 is : " + [Link](10,20) );


[Link]("Subtraction of 10 and 20 is : " + [Link](10,20) );

[Link]("Largest of 10 and 20 is : " + [Link](10,20) );


[Link]("Smallest of 10 and 20 is : " + [Link](10,20) );
}
}
The output of above program will be :
Java Programming L-25 Lab Manual

Program 11 : Write programs for implementation of try, catch and finally block.

Soln. :

class Exception2

public static void main (String ar[ ])

int a=0,b=0,res;

try

a=[Link](args[0]);

b=[Link](args[1]);

res = a/b;

[Link]("Division is "+res);

catch(ArithmeticException e)

[Link]("Can not divide by zero");

catch(ArrayIndexOutOfBoundsException e)

[Link]("Insufficient arguments");

finally

res = a + b;

[Link]("Addition is "+res);

} Executes even if
exception is not
} handled
}
Java Programming L-26 Lab Manual

Output

Program 12 : Write programs for implementation of throw,throws clause.

Soln. :

import [Link].*;
class Exbuff
{
public static void main(String ar[ ]) throws IOException
{
String nm;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name : ");
nm = [Link]( );
Creating object for
[Link]("Hello : "+nm); BufferedReader
}
}

Output

Programs for implementation of throw, throws clause. Part – II.

class test
{
static void divide( )
{
int x,y,z;
try
Java Programming L-27 Lab Manual

{
x=5;
y=0;
z = x/y ;
[Link](x + "/"+ y +" = " + z);
}
catch(ArithmeticException e)
{
[Link]("Exception Caught in Divide( )");
[Link]("Cannot Divide by Zero in Integer Division");
throw e Re-throwing the exception
}
}
}
public class RethrowingExceptions
{
public static void main(String ar[ ])
{
[Link]("Start of main( )");
try
{
[Link]( );
}
catch(ArithmeticException e)
{
[Link]("Caught in Main");
[Link](e);
}
}
}

Output
Java Programming L-28 Lab Manual

Program 13 : Write programs using multithreading.

Soln. :

Program for implementation of multhreading operation Part - I.

class thread1
{
public static void main(String ar[ ])
{
Thread t = [Link]( );
[Link]("Current Thread : "+t);

t prints : name of
[Link]("My Thread");
thread(default-main), priority
(default-5), group of
thread(default-main)

[Link]("After Name changed : "+t);


try
{
for(int n=5;n>0;n--)
{
[Link]("\t"+n);
[Link](1000);
Sleep( ) halts the execution
} for 1 second
}
catch(InterruptedException e)
{
[Link]("Thread interrupted");
}
}
}
Output
Java Programming L-29 Lab Manual

Program for implementation of multithreading operation Part - II.

class MyThread extends Thread


{
public void run( )
{
for(int i=1;i<6;i++)
[Link](i+"\t");
}
}
class thread3
{
public static void main(String ar[ ])
{
MyThread t = new MyThread( );
[Link](t);
[Link]( );
}
}

Output

Program 14 : Write program to design any type of form using AWT components.

Soln. :

import [Link].*;
class GUIForm extends Frame
{
public GUIForm( )
{
setLayout(null);
Font f1 = new Font("Arial", [Link], 21);
Font f2 = new Font("Times New Roman", [Link], 18);
Java Programming L-30 Lab Manual

Label lb1 = new Label("Enter First Name : ");


[Link](f1);
Label lb2 = new Label("Enter Last Name : ");
[Link](f1);
Label lb3 = new Label("Select Country : ");
[Link](f1);
Label lb4 = new Label("Select Gender : ");
[Link](f1);

TextField tf1 = new TextField(15);


[Link](f2);
TextField tf2 = new TextField(15);
[Link](f2);

Choice ch = new Choice( );


[Link](f2);
[Link]("Australia");
[Link]("Bangladesh");
[Link]("India");
[Link]("Nepal");
[Link]("SriLanka");

CheckboxGroup gr = new CheckboxGroup( );


Checkbox ch1 = new Checkbox("Male", true, gr);
[Link](f2);
Checkbox ch2 = new Checkbox("Female", false, gr);
[Link](f2);

Button btn1 = new Button("Submit");


[Link](f1);
Button btn2 = new Button("Reset");
[Link](f2);

add(lb1); add(lb2); add(lb3); add(lb4);


add(tf1); add(tf2); add(ch1); add(ch2); add(ch);
add(btn1); add(btn2);
Java Programming L-31 Lab Manual

[Link](50, 50, 190, 40);


[Link](50, 120, 190, 40);

[Link](280, 55, 250, 30);


[Link](280, 125, 250, 30);

[Link](50, 190, 190, 40);


[Link](50, 260, 190, 40);

[Link](280, 195, 250, 40);


[Link](280, 265, 100, 40);
[Link](380, 265, 100, 40);

[Link](120, 340, 120, 35);


[Link](320, 340, 120, 35);
}
public static void main(String ar[ ])
{
GUIForm fr = new GUIForm( );
[Link](620,450);
[Link]("Demonstrating GUI Form");
[Link](true);
}
}
The output of above program will be :
Java Programming L-32 Lab Manual

Program 15 : Write program to create a menu bar with variousmenu items and sub menu items.

Soln. :
import [Link].*;
class MenuDemo extends Frame
{
public MenuDemo( )
{
MenuBar mb = new MenuBar( );
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
Menu m3 = new Menu("Format");
Menu m4 = new Menu("Open");
MenuItem mi1 = new MenuItem("New");
MenuItem mi2 = new MenuItem("Save");
MenuItem mi3 = new MenuItem("Save As");
MenuItem mi4 = new MenuItem("Cut");
MenuItem mi5 = new MenuItem("Copy");
MenuItem mi6 = new MenuItem("Paste");
MenuItem mi7 = new MenuItem("Font");
MenuItem mi8 = new MenuItem("File 1");
MenuItem mi9 = new MenuItem("File 2");
CheckboxMenuItem cmi1 = new CheckboxMenuItem("Word Wrap",true);
[Link](m1);
[Link](m2);
[Link](m3);
[Link](mi1);
[Link](mi2);
[Link](mi3);
[Link](mi4);
[Link](mi5);
[Link](m4); // nesting of menu
[Link](mi6);
[Link](mi7);
[Link](cmi1);
[Link](mi8);
[Link](mi9);
setMenuBar(mb);
}
Java Programming L-33 Lab Manual

public static void main(String ar[ ])


{
MenuDemo fr = new MenuDemo( );
[Link](400, 400);
[Link]("Demonstrating Menu and MenuItems");
[Link](true);
}
}
The output of above program will be :

Program 16 : Write program to demonstrate the use of border layout. The layout shows four buttons at four sides with
captions “left”, “right”, “top” and “bottom” using Swing Components.
Soln. :

import [Link].*;
import [Link];
import [Link];
public class BorderLayoutDemo extends JFrame
{
public BorderLayoutDemo( )
{
setLayout(new BorderLayout( ));
JButton bt1 = new JButton("TOP HEADER - NORTH");
add(bt1, [Link]);

JButton btn2 = new JButton("BOTTOM FOOTER - SOUTH");


add(btn2 ,[Link]);

JButton btn3 = new JButton("RIGHT - EAST");


Java Programming L-34 Lab Manual

add(btn3, [Link]);

JButton btn4 = new JButton("LEFT - WEST");


add(btn4, [Link]);

String s = "This program shows another\n" + " way of creating and\n" + "adding components.\n";
JTextArea ta = new JTextArea(s);
add(ta, [Link]);
}
public static void main(String ar[ ])
{
BorderLayoutDemo fr = new BorderLayoutDemo( );
[Link](400, 400);
[Link]("Demonstrating BorderLayout");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
The output of above program will be :

Program 17 : Write program to design a calculator to demonstrate the use of grid layout using swingcomponents.

Soln. :

import [Link].*;
import [Link].*;
public class GridLayoutDemo extends JFrame
Java Programming L-35 Lab Manual

{
public GridLayoutDemo( )
{
Container ct = getContentPane( );
GridLayout gl = new GridLayout(4,3);
[Link](gl);
for(int i = 1;i <=9; i++)
{
[Link](new JButton("" + i));
}
JButton bt1 = new JButton("*");
JButton bt2 = new JButton("0");
JButton bt3 = new JButton("#");
[Link](bt1);
[Link](bt2);
[Link](bt3);
}
public static void main(String ar[ ])
{
GridLayoutDemo fr = new GridLayoutDemo( );
[Link](400, 400);
[Link]("Demonstrating GridLayout");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
The output of above program will be :
Java Programming L-36 Lab Manual

Program 18 : Write program using swing to display a JComboBoxin a JFrame .

Soln. :

import [Link].*;
import [Link].*;

public class JComboBoxDemo extends JFrame


{
public JComboBoxDemo( )
{
Container ct = getContentPane( );
[Link](null);

// Creating combo box


JLabeljl = new JLabel("Select Country :");
JComboBoxjc = new JComboBox( );
[Link]("France");
[Link]("Germany");
[Link]("Italy");
[Link]("Japan");

//adding combo box to content pane


[Link](jl);
[Link](jc);

//aligning components
[Link](30,50,100,30);
[Link](150,50,100,30);
}
public static void main(String ar[ ])
{
JComboBoxDemo fr1 = new JComboBoxDemo( );
[Link]("Demonstrating combo box");
[Link](300,400);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Java Programming L-37 Lab Manual

The output of above program will be :

Program 19 : Write program to create JTree and JTable

Soln. :

Program 19.1 : Program to create JTree.

import [Link].*;
import [Link].*;
import [Link].*;

public class JTreeDemo extends JFrame


{
public JTreeDemo( )
{
// Get content pane
Container ct = getContentPane( );

// Set layout manager


[Link](new BorderLayout( ));

// Create top node of tree


DefaultMutableTreeNode root = new DefaultMutableTreeNode("Options");

// Createsubtree of "A"
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
[Link](a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
[Link](a1);
Java Programming L-38 Lab Manual

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");


[Link](a2);

// Createsubtree of "B"
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
[Link](b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
[Link](b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
[Link](b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
[Link](b3);

// Create tree
JTree tree = new JTree(root);

// Add tree to a scroll pane


int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);

// Add scroll pane to the content pane


[Link](jsp, [Link]);
}

public static void main(String ar[ ])


{
JTreeDemo fr = new JTreeDemo( );
[Link](400, 400);
[Link]("Demonstrating BorderLayout");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}

}
Java Programming L-39 Lab Manual

The output of above program will be :

Program 19.2 : Program to create JTable.

[Link].*;
[Link].*;

public class JTableDemo extends JFrame


{
public JTableDemo( )
{
// Get content pane
Container ct = getContentPane( );

// Set layout manager


[Link](new BorderLayout( ));

// Initialize column headings


final String[ ] colHeads = {"Roll", "Name", "city", "phone"};

// Initialize data
final Object[ ][ ] data = {
{ "1", "Amit", "Ahmedabad", "559847" },
{ "2", "Ketan", "Rajkot", "756655" },
{ "3", "Vivek", "Junagadh", "563458" },
{ "4", "Mahendra", "Rajkot", "734592" },
{ "5", "Ankita", "Surat", "123733" },
{ "6", "Jayesh", "Baroda", "565614" },
Java Programming L-40 Lab Manual

{ "7", "Rajshree", "Jamnagar", "567221" },


{ "8", "Suresh","Surat", "674142" },
{ "9", "Hiren", "Rajkot", "902375" }
};
// Create the table
JTable table = new JTable(data, colHeads);

// Add table to a scroll pane


int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPanejsp = new JScrollPane(table, v, h);

// Add scroll pane to the content pane


[Link](jsp, [Link]);
}
public static void main(String ar[ ])
{
JTableDemo fr = new JTableDemo( );
[Link](400, 400);
[Link]("Demonstrating JTable");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
The output of above program will be :
Java Programming L-41 Lab Manual

Program 20 : Write program to handle key events and mouseevents.

Soln. :

Program 20.1 : Demonstrating KeyEvent.

(Copy text of one TextField into another TextField, on keypress event)

import [Link].*;
import [Link].*;
class KeyEventDemo extends Frame implements KeyListener
{
TextField tf1, tf2;

public KeyEventDemo( )
{
setLayout(new FlowLayout( ));

tf1 = new TextField(25);


tf2 = new TextField(25);

[Link]( new Font("Arial", [Link], 25) );


[Link]( new Font("Arial", [Link], 25) );

add(tf1); add(tf2);

[Link](false);
[Link](this);
}

public static void main(String ar[ ])


{
KeyEventDemo fr = new KeyEventDemo( );
[Link](400,400);
[Link]("Demonstrating KeyEvent");
[Link](true);
}

public void keyReleased(KeyEvent ke)


{
String current_text = [Link]( );
Java Programming L-42 Lab Manual

[Link](current_text);
}
public void keyTyped(KeyEvent ke)
{}
public void keyPressed(KeyEvent ke)
{}
}
The output of above program will be :

Program 20.2 : Demonstrating MouseEvent.

(Performing Addition when on mouse-enter event and clear TextFields on mouse-exit event)

import [Link].*;
import [Link].*;
class MouseEventDemo extends Frame implements MouseListener
{
TextField tf1, tf2, tf3;
Button btn;

public MouseEventDemo( )
{
setLayout(new FlowLayout( ));
Font f = new Font("Arial", [Link], 25);

tf1 = new TextField(25);


[Link](f);
tf2 = new TextField(25);
Java Programming L-43 Lab Manual

[Link](f);
tf3 = new TextField(25);
[Link](f);
[Link](false);
btn = new Button("ADD");
[Link](f);
[Link]([Link]);

add(tf1); add(tf2); add(btn); add(tf3);

[Link](this);
}
public static void main(String ar[ ])
{
MouseEventDemo fr = new MouseEventDemo( );
[Link](400, 400);
[Link]("Demonstrating MouseEvent");
[Link](true);
}
public void mouseEntered(MouseEvent me)
{
[Link]([Link]);
int a = [Link]([Link]( ) );
int b = [Link]([Link]( ) );

int c = a + b;
[Link]("" + c);
}
public void mouseExited(MouseEvent me)
{
[Link]([Link]);
[Link](null);
[Link](null);
[Link](null);
}
public void mouseClicked(MouseEvent me)
{}
Java Programming L-44 Lab Manual

public void mousePressed(MouseEvent me)


{}

public void mouseReleased(MouseEvent me)


{}
}
The output of above program will be :

Program 21 : Write program to implement action event in frameusing swing components.

Soln. :

import [Link].*;
import [Link].*;
import [Link].*;
class ActionEventDemo extends JFrame
{
JTextField tf1, tf2, tf3;
JButton adbtn, subbtn, larbtn, smbtn;

public ActionEventDemo( )
{
setLayout(new FlowLayout( ));
Font f = new Font("Arial", [Link], 25);
Font f2 = new Font("Comic Sans MS", [Link], 20);

tf1 = new JTextField(25);


[Link](f);
Java Programming L-45 Lab Manual

tf2 = new JTextField(25);


[Link](f);

tf3 = new JTextField(25);


[Link](f);
[Link](false);

adbtn = new JButton("ADD");


[Link](f2);

subbtn = new JButton("SUBTRACT");


[Link](f2);

larbtn = new JButton("LARGEST");


[Link](f2);

smbtn = new JButton("SMALLEST");


[Link](f2);

add(tf1); add(tf2); add(adbtn); add(subbtn); add(larbtn); add(smbtn); add(tf3);

[Link](new Inner1( ) );
[Link](new Inner2( ) );
[Link](new Inner3( ) );
[Link](new Inner4( ) );
}
class Inner1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int a = [Link]([Link]( ) );
int b = [Link]([Link]( ) );
int c = a + b;
[Link]("Addition is : " + c);
}
}
Java Programming L-46 Lab Manual

class Inner2 implements ActionListener


{
public void actionPerformed(ActionEvent ae)
{
int a = [Link]([Link]( ) );
int b = [Link]([Link]( ) );
int c = a - b;
[Link]("Subtraction is : " + c);
}
}
class Inner3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int a = [Link]([Link]( ) );
int b = [Link]([Link]( ) );
int c = a > b ? a : b;
[Link]("Largest is : " + c);
}
}
class Inner4 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int a = [Link]([Link]( ) );
int b = [Link]([Link]( ) );
int c = a < b ? a : b;
[Link]("Addition is : " + c);
}
}
public static void main(String ar[ ])
{
ActionEventDemo fr = new ActionEventDemo( );
[Link](400, 400);
[Link]("Demonstrating ActionEvent");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Java Programming L-47 Lab Manual

The output of above program will be :

Program 22 : Write program to handle text event on swing components.

Soln. :

(TextEvent is not applicable on Swing’s JTextField and JTextArea. Instead we have to use DocumentListener)

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class SwingTextEvent extends JFrame implements DocumentListener
{
JTextField tf1;
public SwingTextEvent( )
{
setLayout(new FlowLayout( ) );
tf1 = new JTextField(15);
[Link](new Font("Arial", [Link], 22) );

add(tf1);

[Link]( ).addDocumentListener(this);
}

public void changedUpdate(DocumentEvent e)


{
[Link]("changed update");
}
Java Programming L-48 Lab Manual

public void removeUpdate(DocumentEvent e)


{
[Link]("remove update");
}

public void insertUpdate(DocumentEvent e)


{
[Link]("insert update");
}

public static void main(String ar[ ])


{
SwingTextEvent fr = new SwingTextEvent( );
[Link](400, 400);
[Link]("Demonstrating TextEvent on Swing");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}

}
The output of above program will be :
Java Programming L-49 Lab Manual

Program 23 : Write program to retrieve hostname and IP addressusing InetAddress class

Soln. :

import [Link].*;
class InetAddressFactoryMethods
{
public static void main(String ar[ ]) throws UnknownHostException
{
InetAddress addr1 = [Link]( );
[Link]("Inet of LocalHost is : " + addr1);

InetAddress addr2 = [Link]("[Link]");


[Link]("Inet of IRCTC is : " + addr2);

InetAddress addr3[ ] = [Link]("[Link]");


for (int i=0; i<[Link]; i++)
{
[Link](addr3[i]);
}
}
}
The output of above program will be :

Program 24 : Write program to demonstrate various methods of:


URL class.
URLConnection.
Soln. :

Program 24.1 : Demonstrating methods of class URL.

import [Link].*;
import [Link].*;
Java Programming L-50 Lab Manual

class URLDemo
{
public static void main (String ar[ ]) throws IOException
{
URL url = new URL ("[Link]
[Link] ("Authority = " + [Link]( ));
[Link] ("File = " +[Link]( ));
[Link] ("Host = " +[Link]( ));
[Link] ("Path = " +[Link]( ));
[Link] ("Port = " +[Link]( ));
[Link] ("Protocol = " +[Link]( ));
[Link] ("Query = " +[Link]( ));
[Link] ("Ref = " +[Link]( ));
[Link] ("User Info = " +[Link]( ));
}
}
The output of above program will be :

Program 24.1 : Demonstrating methods of class URLConnection.

import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Java Programming L-51 Lab Manual

public class URLConnectionDemo


{
public static void main(String ar[ ])
{
try
{
URL url = new URL("[Link]

//open the connection to the above URL.


URLConnection urlcon = [Link]( );

[Link]("Result of getAllowUserInteraction( ) : " + [Link]( ));


[Link]("Result of getContentType( ) : " + [Link]( ));
[Link]("Result of getURL( ) : " + [Link]( ));
[Link]("Result of getDoInput( ) : " + [Link]( ));
[Link]("Result of getDoOutput( ) : " + [Link]( ));
[Link]("Result of getLastModified( ) : " + new Date([Link]( )));

[Link]("Result of getContentEncoding( ) : " + [Link]( ));

Map<String, List<String>> header = [Link]( );


for ([Link]<String, List<String>> mp : [Link]( ))
{
[Link]([Link]( ) + " : ");
[Link]([Link]( ).toString( ));
}
[Link]( );

/*
Following code will print complete source code of ---> [Link]

[Link]("Complete source code of the URL is-");


[Link]("---------------------------------");

BufferedReader br = new BufferedReader(new InputStreamReader([Link]( )));


String i;
while ((i = [Link]( )) != null)
Java Programming L-52 Lab Manual

{
[Link](i);
}
*/

}
catch (Exception e)
{
[Link](e);
}
}
}
The output of above program will be :

Program 25 : Write program that demonstrates connectionoriented communication using socket.

Soln. :

File 1 : [Link]

import [Link].*;
import [Link].*;
class ClientApplication
{
public static void main(String ar[ ]) throws IOException, UnknownHostException
{
[Link]("Client application Starts");
InetAddress i = [Link]( );
Socket client = new Socket(i, 100);
Java Programming L-53 Lab Manual

DataInputStream dis = new DataInputStream([Link]( ));


DataOutputStream dos = new DataOutputStream([Link]( ));

[Link]("5"); // sent 5 to obtain factorial of it


// the request value is sent. Now client waits for response.

String s2 = [Link]( );
[Link]("Server Responded : " + s2);

[Link]( );

[Link]("Client application ends");


}
}

File 2 : [Link]

import [Link].*;
import [Link].*;
class ServerApplication
{
public static void main(String ar[ ]) throws IOException
{
[Link]("Server application Starts");

ServerSocket ser = new ServerSocket(100);


Socket soc = [Link]( );

DataInputStream dis = new DataInputStream([Link]( ));


DataOutputStream dos = new DataOutputStream([Link]( ));

String s = [Link]( );
int num = [Link](s);

long f = 1;
for(int i=1; i<=num; i++)
{
f = f * i;
}
Java Programming L-54 Lab Manual

[Link]("" + f);

[Link]( );
[Link]( );

[Link]("Server application Ends");


}
}
The output of above program will be : (First run Server application, then run Client application)

Program 26 : Write program to demonstrate sending and receiving data through datagram.

Soln. :

File 1 : [Link]
import [Link].*;
public class DataSender
Java Programming L-55 Lab Manual

{
public static void main(String ar[ ]) throws Exception
{
DatagramSocket ds = new DatagramSocket( );
String str = "Welcome java";
InetAddress ip = [Link]( );
DatagramPacket dp = new DatagramPacket([Link]( ), [Link]( ), ip, 3000);
[Link](dp);
[Link]( );
[Link]("Message Sent..");
}
}

File 2 : [Link]

import [Link].*;
public class DataReceiver
{
public static void main(String ar[ ]) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte buf[ ] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
[Link](dp);
String str = new String([Link]( ), 0, [Link]( ));
[Link](str);
[Link]( );
}
}
The output of above program will be : (Run Sender application first, then run receiver application)
Java Programming L-56 Lab Manual

Program 27 : Write program to : Create sample database.

Make connectivity with database


Soln. :

import [Link].*;
class DatabaseDemo
{
public static void main(String ar[ ])
{
try
{
// String query ="Write any insert / update / deleteQuery here”;

[Link]("[Link]");
//loading JDBC driver for Derby Database

Connection con = [Link]


("jdbc:derby://localhost:1527/sample", "app", "app");
// obtaining connection with Database URL

Statement st = [Link]( );
// using interface Statement
// [Link](query);
// uncomment above statement to fire query

[Link]( );
//closing connection

[Link]("Connection Successful..!");
}
Java Programming L-57 Lab Manual

catch (Exception e)
{
[Link]("Got an exception! ");
[Link]([Link]( ));
}
}
}

Program 28 : Write program to implement following operationson database :

Insert record.

Update record.

Delete record.
Soln. :
import [Link].*;
import [Link].*;
import [Link].*;
class DatabaseOperations extends Frame
{
TextField tf1, tf2, tf3, tf4;
Label lb5;
public DatabaseOperations( )
{
setLayout(null);
Font f1 = new Font("Arial", [Link], 21);
Font f2 = new Font("Times New Roman", [Link], 18);
Font f3 = new Font("Times New Roman", [Link], 25);

Label lb1 = new Label("Enter Employee ID : ");


[Link](f1);
Label lb2 = new Label("Enter Name : ");
[Link](f1);
Label lb3 = new Label("Enter Post : ");
[Link](f1);
Label lb4 = new Label("Enter Department : ");
[Link](f1);
lb5 = new Label("See Results Here");
[Link](f3);
tf1 = new TextField(15);
[Link](f2);
Java Programming L-58 Lab Manual

tf2 = new TextField(15);


[Link](f2);
tf3 = new TextField(15);
[Link](f2);
tf4 = new TextField(15);
[Link](f2);

Button btn1 = new Button("Insert Record");


[Link](f1);
Button btn2 = new Button("Update Record");
[Link](f1);
Button btn3 = new Button("Delete Record");
[Link](f1);

add(lb1); add(lb2); add(lb3); add(lb4);


add(tf1); add(tf2); add(tf3); add(tf4);
add(btn1); add(btn2); add(btn3); add(lb5);

[Link](90, 50, 190, 40);


[Link](90, 120, 190, 40);
[Link](90, 190, 190, 40);
[Link](90, 260, 190, 40);

[Link](320, 55, 280, 30);


[Link](320, 125, 280, 30);
[Link](320, 195, 280, 30);
[Link](320, 265, 280, 30);

[Link](60, 340, 180, 35);


[Link](290, 340, 180, 35);
[Link](500, 340, 180, 35);

[Link](200, 400, 250, 45);


[Link]([Link]);

[Link](new Inner1( ) );
[Link](new Inner2( ) );
[Link](new Inner3( ) );
}
Java Programming L-59 Lab Manual

public static String fireQuery(String q, String m)


{
try
{
String query = q;
[Link]("[Link]");
Connection con = [Link]
("jdbc:derby://localhost:1527/sample", "app", "app");
Statement st = [Link]( );
[Link](query);
[Link]( );
return m;
}
catch (Exception e)
{
return [Link]( );
}
}
class Inner1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String s1 = [Link]( );
String s2 = [Link]( );
String s3 = [Link]( );
String s4 = [Link]( );

String q = "insert into emp_info values


(" + s1 + ",'" + s2 + "','" + s3 + "','" + s4 + "')";
String res = fireQuery(q, "Employee Record Inserted..");
[Link](res);
}
}
class Inner2 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String s1 = [Link]( );
String s2 = [Link]( );
Java Programming L-60 Lab Manual

String s3 = [Link]( );
String s4 = [Link]( );
String q = "update emp_info set
emp_name='" + s1 + "', emp_post='" +
s2 + "', emp_dept='" + s4 + "' where emp_id=" + s1;
fireQuery(q, "Employee Record Updated..");
}
}
class Inner3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String s1 = [Link]( );
String q = "delete from emp_info where emp_id=" + s1;
fireQuery(q, "Employee Record Deleted");
}
}
public static void main(String ar[ ])
{
DatabaseOperations fr = new DatabaseOperations( );
[Link](730, 500);
[Link]("Demonstrating Database Operations");
[Link](true);
}
}
The output of above program will be :
Java Programming L-61 Lab Manual

Program 29 : Write program to demonstrate the use of PreparedStatement.

Soln. :

import [Link].*;
import [Link].*;
import [Link].*;
class DatabaseOperations extends Frame
{
TextField tf1, tf2, tf3, tf4;
Label lb5;
public DatabaseOperations( )
{
setLayout(null);
Font f1 = new Font("Arial", [Link], 21);
Font f2 = new Font("Times New Roman", [Link], 18);
Font f3 = new Font("Times New Roman", [Link], 25);

Label lb1 = new Label("Enter Employee ID : ");


[Link](f1);
Label lb2 = new Label("Enter Name : ");
[Link](f1);
Label lb3 = new Label("Enter Post : ");
[Link](f1);
Label lb4 = new Label("Enter Department : ");
[Link](f1);
lb5 = new Label("See Results Here");
[Link](f3);

tf1 = new TextField(15);


[Link](f2);
tf2 = new TextField(15);
[Link](f2);
tf3 = new TextField(15);
[Link](f2);
tf4 = new TextField(15);
[Link](f2);

Button btn1 = new Button("Insert Record");


[Link](f1);
Java Programming L-62 Lab Manual

Button btn2 = new Button("Update Record");


[Link](f1);
Button btn3 = new Button("Delete Record");
[Link](f1);

add(lb1); add(lb2); add(lb3); add(lb4);


add(tf1); add(tf2); add(tf3); add(tf4);
add(btn1); add(btn2); add(btn3); add(lb5);

[Link](90, 50, 190, 40);


[Link](90, 120, 190, 40);
[Link](90, 190, 190, 40);
[Link](90, 260, 190, 40);

[Link](320, 55, 280, 30);


[Link](320, 125, 280, 30);
[Link](320, 195, 280, 30);
[Link](320, 265, 280, 30);

[Link](60, 340, 180, 35);


[Link](290, 340, 180, 35);
[Link](500, 340, 180, 35);

[Link](200, 400, 250, 45);


[Link]([Link]);

[Link](new Inner1( ) );
[Link](new Inner2( ) );
[Link](new Inner3( ) );
}

class Inner1 implements ActionListener


{
public void actionPerformed(ActionEvent ae)
{
int s1 = [Link]([Link]( ));
String s2 = [Link]( );
Java Programming L-63 Lab Manual

String s3 = [Link]( );
String s4 = [Link]( );
try
{
String query = "insert into emp_info values(?, ?, ?, ?)";
[Link]("[Link]");
Connection con = [Link]
("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement psmt = [Link](query);

[Link](1,s1);
[Link](2,s2);
[Link](3,s3);
[Link](4,s4);

[Link]( );
[Link]( );
[Link]("Employee Record Inserted..");
}
catch (Exception e)
{
[Link]([Link]( ));
}
}
}
class Inner2 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int s1 = [Link]([Link]( ));
String s2 = [Link]( );
String s3 = [Link]( );
String s4 = [Link]( );

try
{
String query = "update emp_info set emp_name=?,
emp_post=?, emp_dept=? where emp_id=?";
Java Programming L-64 Lab Manual

[Link]("[Link]");
Connection con = [Link]
("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement psmt = [Link](query);

[Link](1,s2);
[Link](2,s3);
[Link](3,s4);
[Link](4,s1);

[Link]( );
[Link]( );
[Link]("Employee Record Updated..");
}
catch (Exception e)
{
[Link]([Link]( ));
}
}
}
class Inner3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int s1 = [Link]([Link]( ));
try
{
String query = "delete from emp_info where emp_id=?";
[Link]("[Link]");
Connection con = [Link]
("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement psmt = [Link](query);

[Link](1,s1);

[Link]( );
[Link]( );
Java Programming L-65 Lab Manual

[Link]("Employee Record Deleted..");


}
catch (Exception e)
{
[Link]([Link]( ));
}
}
}
public static void main(String ar[ ])
{
DatabaseOperations fr = new DatabaseOperations( );
[Link](730, 500);
[Link]("Demonstrating Database Operations");
[Link](true);
}
}
The output of above program will be:

Program 30 : Write program to retrieve data from table using ResultSet interface.(Use various methods of navigation
methods).
Soln. :

Program 30.1 : Program to demonstrate SELECT query to fetch every record from Employee Table and
showing it in console.

import [Link].*;
public class SelectQueryDemo1
Java Programming L-66 Lab Manual

{
public static void main(String ar[])
{
String id, nm, pst, dep;
try
{

String query = "select emp_id, emp_name, emp_post, emp_dept from emp_info";


[Link]("[Link]");

Connection con = [Link]

("jdbc:derby://localhost:1527/sample", "app", "app");

Statement st = [Link]( );

ResultSet rs = [Link](query);

while([Link]( ))
{
id = [Link]("emp_id");
nm = [Link]("emp_name");
pst = [Link]("emp_post");
dep = [Link]("emp_dept");

[Link](id + "\t" + nm + "\t" + pst + "\t" + dep);


}

[Link]( );

catch(ClassNotFoundException cnfe)

[Link]("Unable to Load JDBC Driver");

catch(SQLException sqe)

[Link]([Link]( ));

}
}
Java Programming L-67 Lab Manual

Program 30.2 : Demonstrating SELECT query to fetch record of specific employee and filling it in TextField
objects.

import [Link].*;
import [Link].*;
import [Link].*;
public class SelectQueryDemo2 extends Frame implements ActionListener
{
TextField tf1, tf2, tf3, tf4;
Label lb5;
public SelectQueryDemo2( )
{
setLayout(null);
Font f1 = new Font("Arial", [Link], 21);
Font f2 = new Font("Times New Roman", [Link], 18);
Font f3 = new Font("Times New Roman", [Link], 25);

Label lb1 = new Label("Enter Employee ID : ");


[Link](f1);
Label lb2 = new Label("Employee Name : ");
[Link](f1);
Label lb3 = new Label("Employee Post : ");
[Link](f1);
Label lb4 = new Label("Employee Department : ");
[Link](f1);
lb5 = new Label("See Exception Result Here.");
[Link](f1);

tf1 = new TextField(15);


[Link](f2);
tf2 = new TextField(15);
[Link](f2);
[Link](false);
tf3 = new TextField(15);
[Link](f2);
[Link](false);
tf4 = new TextField(15);
[Link](f2);
Java Programming L-68 Lab Manual

[Link](false);

Button btn1 = new Button("Fetch Record");


[Link](f1);

add(lb1); add(lb2); add(lb3); add(lb4);


add(tf1); add(tf2); add(tf3); add(tf4);
add(btn1); add(lb5);

[Link](90, 50, 190, 40);


[Link](90, 120, 190, 40);
[Link](90, 190, 190, 40);
[Link](90, 260, 190, 40);

[Link](320, 55, 280, 30);


[Link](320, 125, 280, 30);
[Link](320, 195, 280, 30);
[Link](320, 265, 280, 30);

[Link](200, 400, 250, 45);


[Link]([Link]);

[Link](230, 340, 180, 45);


[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
String query = "select emp_name, emp_post, emp_dept from
emp_info where emp_id=" + [Link]( );
[Link]("[Link]");
Connection con = [Link]
("jdbc:derby://localhost:1527/sample", "app", "app");
Statement st = [Link]( );
ResultSet rs = [Link](query);
if([Link]( ))
{
[Link]([Link]("emp_name"));
Java Programming L-69 Lab Manual

[Link]([Link]("emp_post"));
[Link]([Link]("emp_dept"));
}
else
{
[Link]("Invalid Employee ID");
}
}
catch(ClassNotFoundException cnfe)
{
[Link]([Link]( ));
}
catch(SQLException sqe)
{
[Link]([Link]( ));
}
}
public static void main(String ar[ ])
{
SelectQueryDemo2 fr = new SelectQueryDemo2( );
[Link](730, 500);
[Link]("Demonstrating use of Select Query");
[Link](true);
}
}
The output of above program will be :



You might also like