Lab Manual JAVA
Lab Manual JAVA
Year: II Semester: IV
Prepared by
Course Outcomes: Students will learn how to write programs and develop projects in Java.
Develop Java programs to cover the following topics:
1. Simple Java program with one or more classes
2. Exception Handling
3. Inheritance
4. Packages
5. Interfaces
6. Event Handling
7. File Handling
8. Thread Handling
9. AWT controls/Java Swings/Struts framework
10. Applets
11. RMI
12. JDBC
Objectives
Intel based desktop PC with minimum of 2.6GHZ or faster processor with at least 256 MB
RAM and 40GB free disk space.
Operating system: WINDOWS.
Software
o j2sdk1.7.
o MySQL.
o Eclipse or Net bean.
Guidelines to Students
Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab. Students must use the equipment with care.
Students are instructed to come to lab in formal dresses only.
Students are supposed to occupy the systems allotted to them and are not supposed to talk
or make noise in the lab.
Students are required to carry their observation book and lab records with completed
exercises while entering the lab.
Lab records need to be submitted every week. 6. Students are not supposed to use pen
drives in the lab.
Lab Objective
Lab Outcome
Able to use Java compiler and eclipse platform to write and execute java program.
Understand and Apply Object oriented features and Java concepts.
Able to apply the concept of multithreading and implement exception handling.
Able to access data from a Database with java program.
Develop applications using Console I/O and File I/O,GUI applications
LIST OF EXPERIMENTS
32. Write an Applet that draws a dot at a random location in its display area every 200ms. Any
existing dots are not erased. Therefore dots accumulate as the applet executes.
33. Write an Applet that illustrates how to process mouse click, enter, exit, press and release
events. The background color changes when the mouse is entered, clicked, pressed, re-
leased or exited.
34. Write an Applet that displays your name whenever the mouse is clicked.
35. Use adapter classes to write an Applet those changes to cyan while the mouse is being
dragged. At all other times the applet should be white.
36. Write RMI based client-server programs.
37. Write programs of database connectivity using JDBC drivers.
38. Create a simple web page using HTML
39. Create a simple web page using Java Script(Client side Scripting)
40. Create a web application using Servlet
PROJECTS TO BE ALLOTED
Students will be divided into a group of four/five and projects are allotted to those groups..
Each practical which student is performing in the lab should have the following details :
a) Program Name
b) Aim
c) Algorithm
d) Source Code
e) Output
f) Viva questions
Regularity:
Performing program in each turn of the lab 40
Attendance of the lab
Record Submission
Viva Voce 10
Total 50
It is taken by the concerned faculty of the batch and by an external examiner. In this exam
student needs to perform the experiment allotted at the time of the examination , viva voce
conducted and the paper is evaluated
Program/Source Code 20
Viva Voice:: 10
Total 50
NOTE:
Index
Pgm. Page
Date Program Name
No No.
Simple Java Programs
B. Reversing a Number 23
C. Factorial of a Number 25
C. Constructor 42
D. Function Overloading 45
E. Nested Classes 47
F. String Classes 50
3 Exception Handling
4 Inheritance
A. Single Inheritance 63
B. Hierarchical Inheritance 67
5 Package 72
6 Interface 76
7 Threads Programming
A. Multi-Threads 81
B. Runnable Interface 84
8 Applet Programming
A. Simple Applet 89
B. Event Handler 91
9 Colour Palette 96
10 Layouts
10 AWT-Controls 104
Java Version
There are sophisticated IDEs for Java programming that are available.
There are other products similar to JCreator, for Windows and for other operating systems.
After installing Oracles’ Software Development Kit for Java, one can use the commands "javac",
"java", and "appletviewer" for compiling and running Java programs and applets. These
commands must be on the "path" where the operating system searches for commands.
Make a directory to hold Java programs. Create program with a text editor, or copy the program to
be compiled into program directory
If program contains more than a few errors, most of them will scroll out of the window. In Linux
and UNIX, a command window usually has a scroll bar that can be used to review the errors. In
Windows 2000 to 2010/NT/XP (but not Windows 95/98), one can save the errors in a file which
can be viewed later in a text editor.
The ">& errors.txt" redirects the output from the compiler to the file, instead of to the DOS
window. It is possible to compile all the Java files in a directory at one time. Use the command
"javac *.java".
After compiled class files are made, run application or applet. For running a stand-alone
application -- one that has a main ( ) routine -- use the "java" command from the SDK to run the
application. If the class file that contains the main ( ) routine is named Main. class, then run the
program with the command:
java Main
4. C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.7.0\bin
Note:
You should only have one bin directory for a JDK in the path at a time. Those following
the first instance are ignored.
If you are not sure where to add the JDK path, append it.
The new path takes effect in each new command window you open after setting
the PATH variable.
4. Compile the file with JAVA compiler (javac filename.java) and create class file.
5. Run the class file with JAVA interpreter (java classname.class) and check the output.
To compile
javac Message.java
To Execute
java Message
Output
Java Programming
Simple Programs
Aim
Algorithm
Code
import java.io.*;
import java.util.*;
class Inputs
{
public static void main(String args[])
{
int a;
float b;
String c;
double d;
String e;
Scanner inp=new Scanner(System.in);
System.out.println("\nFloat b = "+b);
System.out.println("\nString c = "+c);
System.out.println("\nDouble d = "+d);
System.out.println("\nLine e = "+e);
}
OUTPUT:
RESULT
AIM
ALGORITHM
CODE
mport java.io.*;
import java.util.Scanner;
class NumRev
{
public static void main(String args[])
{
int n,rev=0;
System.out.println(" Number Reverse Program In Java ");
System.out.print(" Enter a number : ");
Scanner inp = new Scanner (System.in);
n = inp.nextInt();
while(n!=0)
{
rev=rev*10;
rev=rev+n%10;
n=n/10;
}
System.out.println("Reversed number is : "+rev);
}
}
OUTPUT
RESULT:
AIM
ALGORITHM
PROGRAM:
import java.io.*;
import java.util.Scanner;
OUTPUT:
RESULT:
The JAVA program to find factorial of a given number has been executed successfully.
AIM
ALGORITHM
PROGRAM
import java.io.*;
class Student3
{
int Sno;
String Sname;
public void getdata(int x,String y)
{
Sno=x;
Sname=y;
}
public void display()
{
System.out.print("\n"+Sno);
System.out.println(" "+Sname);
}
public static void main(String args[])
{
Student3 S1=new Student3();
S1.getdata(15,"Aravindan");
Student3 S2=new Student3();
S2.getdata(30,"Prabhakar");
System.out.println("\nStudent Details");
S1.display();
S2.display();
}
}
OUTPUT
RESULT
The JAVA program to understand class and object has been executed successfully.
AIM
ALGORITHM
PROGRAM
import java.io.*;
class Staticv
{
static int count=0;
obj1.increment();
obj2.increment();
obj3.increment();
System.out.println("Obj3: count is= "+obj3.count);
OUTPUT
RESULT
The JAVA program using static variable has been executed successfully.
QUESTION: 1
Given
4. String #name = "Jane Doe";
5. int $age = 24;
6. Double _height = 123.5;
7. double ~temp = 37.5;
QUESTION: 2
QUESTION: 3
Given:
• public class LineUp {
• public static void main(String[] args) {
• double d = 12.345;
• // insert code here
• }
• }
QUESTION: 4
Given:
• public class TestString1 {
• public static void main(String[] args) {
• String str = "420";
• str += 42;
• System.out.print(str);
• }
• }
QUESTION: 5
Given:
• public class Mud {
• //insert code here
• System.out.println("h
i"); }
• }
And the following five fragments:
public static void main(String...a)
{ public static void main(String.* a)
{ public static void main(String... a)
{ public static void main(String[]... a)
{ public static void main(String...[] a)
{
QUESTION: 6
Given:
class Hexy {
public static void main(String[] args) {
Integer i = 42;
String s = (i<40)?"life":(i>50)?"universe":"everything";
System.out.println(s);
}}
QUESTION: 7
Given:
class Feline {
public static void main(String[] args) {
Long x = 42L;
Long y = 44L;
System.out.print(" " + 7 + 2 + " ");
System.out.print(foo() + x + 5 + " ");
System.out.println(x + y + foo());
}
static String foo() { return "foo"; }
}
Given:
class Maybe {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
System.out.print(!false ^ false);
System.out.print(" " + (!b1 & (b2 = true)));
System.out.println(" " + (b2 ^ b1));
}
}
QUESTION: 9
Given:
class Sixties {
public static void main(String[] args) {
int x = 5;
int y = 7;
System.out.print(((y * 2) % x));
System.out.print(" " + (y % x));
}
}
QUESTION: 10
Given:
public class Bar {
static void foo( int... x ) {
// insert code here
}
}
Which two code fragments, inserted independently at line 12, will allow the class to
compile? (Choose two.)
A. foreach( x ) System.out.println(z);
B. for( int z : x ) System.out.println(z);
C. while( x.hasNext() ) System.out.println( x.next() );
D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);
QUESTION: 1
Given:
public class Hello {
String title;
int value;
public Hello() {
title += " World";
}
public Hello(int value) {
this.value = value;
title = "Hello";
Hello();
}
} and:
Hello c = new Hello(5);
System.out.println(c.title);
QUESTION: 2
Given:
class Foo {
static void alpha() { /* more code here */ }
void beta() { /* more code here */ }
}
QUESTION: 3
Given:
public class ItemTest {
private final int id;
public ItemTest(int id) { this.id = id; }
public void updateId(int newId) { id = newId; }
QUESTION: 4
Given:
/ class Snoochy {
/ Boochy booch;
/ public Snoochy() { booch = new Boochy(this); }
/ }
/ class Boochy {
/ Snoochy snooch;
/ public Boochy(Snoochy s) { snooch = s; }
/ }
And the statements:
public static void main(String[] args) {
Snoochy snoog = new Snoochy();
snoog = null;
// more code here
}
Which statement is true about the objects referenced by snoog, snooch, and booch immediately
after line 23 executes?
A. None of these objects are eligible for garbage collection.
B. Only the object referenced by booch is eligible for garbage collection.
C. Only the object referenced by snoog is eligible for garbage collection.
D. Only the object referenced by snooch is eligible for garbage collection.
E. The objects referenced by snooch and booch are eligible for garbage collection.
Which, inserted independently at line 6, will compile? (Choose all that apply.)
A. static void doStuff(int... doArgs) { }
B. static void doStuff(int[] doArgs) { }
C. static void doStuff(int doArgs...) { }
D. static void doStuff(int... doArgs, int y) { }
E. static void doStuff(int x, int... doArgs) { }
QUESTION: 6
public class A
{
private int counter=0;
public static int getInstanceCount()
{
return counter;
}
public A()
{
counter++;
}
}
Given this code from Class B:
A a1 = new A();
A a2 = new A();
A a3 = new A();
System.out.println(A.getInstanceCount());
QUESTION: 7
Given:
public class Batman {
int squares = 81;
public static void main(String[] args) {
new Batman().go();
}
void go() {
incr(++squares);
System.out.println(squares);
}
void incr(int squares) { squares += 10; }
}
QUESTION: 10
Given:
/ public class ClassA {
/ public int getValue() {
int value=0;
boolean setting = true;
String title=”Hello”;
if (value || (setting && title == “Hello”)) { return 1; }
if (value == 1 & title.equals(”Hello”)) { return 2; }
}
}
And:
ClassA a = new ClassA();
a.getValue();
42
Ex.No.:1(f) Constructor
AIM
ALGORITHM
PROGRAM
import java.io.*;
class Student1
{
int Sno;
String Sname;
public Student1( int no, String name)
{
Sno = no ;
Sname = name ;
}
43
OUTPUT:
RESULT
44
Ex.No.:(g) Function Overloading
AIM
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
class Add
{
public void sum(int a,int b)
{
System.out.println("Sum is : "+(a+b));
}
public void sum(int a,int b,int c)
{
System.out.println("Sum is : "+(a+b+c));
}
45
break;
default:
System.out.println("Enter valid choice");
}
}
OUTPUT
RESULT
46
Ex.No.:1(h) Nested Class
AIM
ALGORITHM
47
PROGRAM
class OuterDemo
{
int num;
void displayInner()
{
InnerDemo inner = new InnerDemo();
inner.print();
}
}
class Myclass
{
public static void main(String args[])
{
OuterDemo outer=new OuterDemo();
outer.displayInner();
}
48
OUTPUT:
RESULT
49
Ex.No.:1(i) String Class
AIM
ALGORITHM
PROGRAM
if(x.equalsIgnoreCase(y))
{
System.out.println("Both strings are equal in Ignore case block.");
}
else
{
System.out.println("Both strings are not equal Ignore case block.");
}
}
}
50
OUTPUT
RESULT
51
Practice Exercises:
52
Java – Exception Handling
53
Ex.No.:2(a) Exception Handling - Multiple Catch
AIM
To write a JAVA program to understand the concept of exception handling using multiple
catch.
ALGORITHM
PROGRAM
import java.io.*;
import java.util.*;
54
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array is out of Bounds" +e);
}
catch (ArithmeticException e)
{
System.out.println ("Can't divide by Zero" +e);
}
catch(Exception e)
{
System.out.println("Exception caught");
}
}
}
55
OUTPUT
RESULT
56
Ex.No.:2(b) Exception Handling - Array Index Out Of Bound
AIM
To write a JAVA program to understand the concept of exception handling for array index out
of bound exception.
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
public class SingleArray
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter number of elements");
int n=s.nextInt();
int arr[]=new int[5];
System.out.println("Enter elements");
for(int i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
System.out.println("The numbers are ...");
for(int i = 0; i <n; i++)
{
System.out.println(".."+arr[i]);
}
}
}
57
OUTPUT:
RESULT
The Array index out of bound exception program has been executed successfully.
58
Ex.No.:2(c) User Defined Exception
AIM
To write a JAVA program to understand the concept of exception handling using user defined
exception.
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
59
public static void main(String args[])
{
int a;
Scanner s=new Scanner(System.in);
System.out.print("\nEnter Your Age : ");
a=s.nextInt();
try
{
validate(a);
}
catch(Exception m)
{
System.out.println("Exception Occured : "+m);
}
}
}
60
OUTPUT:
RESULT
61
Java – Inheritance
62
Ex.No.:3(a) Single Inheritance
AIM
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
class Student
{
public
int regno;
int year;
String name;
public void method()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter student name:");
name=ob.nextLine();
System.out.print("Enter register number:");
regno=ob.nextInt();
System.out.print("Enter year:");
year=ob.nextInt();
}
63
class Marks extends Student
{
int arr[]=new int[5],tot;
public void method2()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter Student marks : ");
for (int i=0;i<5;i++)
{
arr[i]=ob.nextInt();
tot = tot + arr[i];
}
}
public static void main(String[] arg)
{
Marks s=new Marks();
s.method();
s.method2();
s.display();
}
64
OUTPUT:
RESULT
65
Ex.No.:3(b) Inheritance – Hierarchical
AIM
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
class Player
{
public
int number;
String name;
String role;
String country;
public void method()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter player name :");
name=ob.nextLine();
System.out.print("Enter Jersey number :");
number=ob.nextInt();
System.out.print("Enter the Nationality :");
country=ob.nextLine();
country=ob.nextLine();
}
66
class Batsman extends Player
{
float avg;
public void method1()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter the Role of Batsman :");
role=ob.nextLine();
System.out.print("Enter Batting Average:");
avg=ob.nextFloat();
}
67
class Heirarchical
{
public static void main(String[] arg)
{
Batsman ba=new Batsman();
Bowler bo=new Bowler();
System.out.println("Batsman Details ... ");
ba.method();
ba.method1();
System.out.println("Bowler Details .... ");
bo.method();
bo.method2();
System.out.println("\n\t\t\t *****PLAYER'S DETAILS*****");
ba.display();
bo.display();
}
}
68
OUTPUT
RESULT
69
Practice Exercise:
70
Java – Packages
71
Ex.No.:4 Package
AIM
ALGORITHM
PROGRAM
package pack;
import java.io.*;
public class Compute
{
int a,b;
public void add(int a,int b)
{
System.out.println("The result of addition is :" +(a+b));
}
public void sub(int a,int b)
{
System.out.println("The result of subtraction is :" +(a-b));
}
public void mul(int a,int b)
{
System.out.println("The result of multiplication is :" +(a*b));
}
public void div(int a,int b)
{
System.out.println("The result of division is :" +(a/b));
}
}
72
import pack.Compute;
import java.io.*;
import java.util.Scanner;
class Calculate
{
public static void main(String args[])
{
int a,b,ch;
Scanner s1=new Scanner(System.in);
System.out.println("Enter two numnber : ");
System.out.print(" A : ");
a=s1.nextInt();
System.out.print(" B : ");
b=s1.nextInt();
System.out.println("Enter the operation to be performed : ");
System.out.println(" 1. Addition \n 2. Subtraction" );
System.out.println(" 3. Multiplication \n 4. Division ");
System.out.print("Enter the choice :");
ch=s1.nextInt();
Compute c=new Compute();
switch(ch)
{
case 1: c.add(a,b);
break;
case 2: c.sub(a,b);
break;
case 3: c.mul(a,b);
break;
case 4: c.div(a,b);
break;
default: System.out.println("Invalid choice...");
}
}
}
73
OUTPUT:
RESULT
74
Java – Interface
75
Ex.No.:5 Interface
AIM
ALGORITHM
PROGRAM
interface ISports
{
public void SetTeam(String t1,String t2, int score1, int score2);
public void ShowResult();
}
76
else
{
System.out.println("\t"+team2+" Won");
}
}
}
77
class Sports
{
public static void main(String args[])
{
Cricket c = new Cricket();
Hockey h = new Hockey();
c.SetTeam("India", "England",240,220);
h.SetTeam("India", "Germany",3,2);
c.ShowResult();
h.ShowResult();
}
}
78
OUTPUT
RESULT
79
Java – Thread
80
Ex.No.:6(a) Multi-Thread
AIM
ALGORITHM
PROGRAM
import java.io.*;
import java.util.Scanner;
}
System.out.println(i);
}
}
}
class MyThread
{
81
public static void main(String args[])
{
int l,m;
Scanner s= new Scanner(System.in);
System.out.println("Enter two starting numbers");
l=s.nextInt();
m=s.nextInt();
ThreadA t1=new ThreadA(l);
ThreadA t2=new ThreadA(m);
t1.start();
t2.start();
}
}
82
OUTPUT:
RESULT
83
Ex.No.:6(b) Thread Using Runnable Interface
AIM
ALGORITHM
PROGRAM:
import java.io.*;
import java.util.Scanner;
84
class RunThread
{
public static void main(String[] args)
{
ThreadA t1 = new ThreadA ("Hello");
ThreadA t2 = new ThreadA ("Folks");
Thread s = new Thread(t1);
Thread t = new Thread(t2);
s.start();
t.start();
}
}
}
85
OUTPUT:
RESULT
86
Practice Exercise
1. 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.
87
Applet Application
Small Program Large Program
88
Ex. No: 7(a) SIMPLE APPLET
AIM
ALGORITHM
1. Create a class that extends “Applet” class and implements “ActionListener” interface.
2. Define Label boxes, Buttons and Text Fields (i.e., Components) in the “init()” method.
3. Override the “actionPerformed()” method with specified action.
4. Compile and view the output in “appletviewer”.
PROGRAM
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
89
public void actionPerformed(ActionEvent ae)
{
t1.setText(" ");
t2.setText(" ");
}
OUTPUT:
RESULT
The Java simple applet program has been executed successfully.
90
Ex. No: 7(b) EVENT HANDLER
AIM
ALGORITHM
1. Create a class that extends “Applet” class and implements “ActionListener” interface.
2. Define two buttons and an image(Components) in “init()” method.
3. Add the two buttons to a panel.
4. Set the panel to be Grid Layout.
5. Add the panel to the Layout and add Action Listeners for the buttons.
6. Perform the action(select the image) with respect to the button selected.
PROGRAM
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
Panel p1;
Button b,c;
Image backGround;
b = new Button("Autumn");
c = new Button("Winter");
p1.add(b);
p1.add(c);
setLayout(new GridLayout(10,1));
add(p1);
b.addActionListener(this);
c.addActionListener(this);
91
}
92
OUTPUT:
RESULT
93
Practice Exercises
2. 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.
3. 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.
94
Ex. No: 8 COLOUR PALLET
AIM
ALGORITHM
1. Create a class that extends “Applet” class and implements “ActionListener” and “ItemListener”
interfaces.
2. In “init()” method, define and initialize the objects.
3. Change the colour of Background and Foreground of a Text area based on the choice and button
selected.
4. Change the image being displayed based on choice
5. Use Grid Layout and set the panels
6. In “actionPerformed” method, text area is edited.
7. In “itemStateChanged” method, image is repainted.
8. The applet is executed in “appletviewer”.
PROGRAM
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=colorpalette.class width=500 height=400>
</applet>
*/
95
Panel p2 = new Panel();
Panel p3 = new Panel();
Panel p4 = new Panel();
colour=new CheckboxGroup();
backcolor=new Checkbox("Background",colour,true);
forecolor=new Checkbox("Foreground",colour,false);
p2.add(backcolor);
p2.add(forecolor);
p3.add(text);
p4.add(image1);
p4.add(image2);
setLayout(new GridLayout(10,1));
add(p1);
add(p2);
add(p3);
add(p4);
image1.addItemListener(this);
image2.addItemListener(this);
}
96
public void paint(Graphics g)
{
g.drawImage(backGround,0,100,this);
}
public void actionPerformed(ActionEvent e)
{
Color col= Color.white;
if(e.getSource()==b1)
{
col = Color.green;
}
else if(e.getSource()==b2)
{
col = Color.red;
}
else if(e.getSource()==b3)
{
col = Color.yellow;
}
else if(e.getSource()==b4)
{
col = Color.orange;
}
if(flag==1)
{
text.setBackground(col);
}
else
{
text.setForeground(col);
}
repaint();
}
97
public void itemStateChanged(ItemEvent ie)
{
s1=colour.getSelectedCheckbox().getLabel();
if(s1.equals("Background"))
{
flag=1;
}
else
{
flag=0;
}
s2=images.getSelectedCheckbox().getLabel();
if(s2.equals("Mountain"))
{
backGround = getImage(getCodeBase(), "Mountain.jpg");
}
else
{
backGround = getImage(getCodeBase(), "sunrise.jpg");
}
repaint();
}
}
98
OUTPUT
RESULT
99
Ex. No: 9(a) BORDER LAYOUT
AIM
To set the layout of the Applet as Border layout.
ALGORITHM:
1. Create a class that extends “JFrame”.
2. In Constructor of the class, create buttons and place them at different areas of the same “JPanel”
that is created with a BorderLayout.
3. In Main method, create an object for the class.
4. Resize the window to see the layout design during execution.
PROGRAM:
import java.awt.*;
import javax.swing.*;
panel.add(B1,BorderLayout.PAGE_START);
panel.add(B2,BorderLayout.LINE_START);
panel.add(B3,BorderLayout.CENTER);
panel.add(B4,BorderLayout.LINE_END);
panel.add(B5,BorderLayout.PAGE_END);
add(panel);
setSize(200, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
100
OUTPUT:
RESULT
101
Ex. No: 9(b) FLOW LAYOUT
AIM
To set the layout of the Applet as Flow layout
ALGORITHM
panel.add(B1);
panel.add(B2);
panel.add(B3);
panel.add(B4);
panel.add(B5);
panel.add(B6);
panel.add(B7);
panel.add(B8);
panel.add(B9);
add(panel);
setSize(200, 150);
this.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
FlowLay f = new FlowLay();
}
}
102
OUTPUT
RESULT
The Buttons have been set Flow layout in the Applet.
103
Ex. No: 10 AWT - CONTROLS
AIM
ALGORITHM
1. Create a class “AwtControl” that extends Frame and implements “ActionListener” interface.
2. Define components of the applet.
3. In Constructor of the class, initialize the components and add them to the applet.
4. Include the “actionPerformed” method and “windowclosing” method to the class.
5. In Main method, create an object for the class.
6. View the output in an “appletviewer”
PROGRAM
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public AwtControl()
{
setLayout(new GridLayout(10, 2));
t1 = new TextField(20);
t2 = new TextField(20);
104
t3 = new TextField(20);
ch1 = new Choice();
ch1.addItem("CSE");
ch1.addItem("IT");
ch1.addItem("MCA");
ch1.addItem("ECE");
p1 = new Panel();
p1.add(cb1);
p1.add(cb2);
It = new List();
It.addItem("Sports");
It.addItem("Graphics");
It.addItem("Mobile Technology");
b1 = new Button("Show");
b1.addActionListener(this);
b2 = new Button("Exit");
b2.addActionListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(ch1);
add(l5);
add(p1);
add(l6);
add(It);
add(b1);
add(b2);
add(ta);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b2)
{
System.exit(0);
}
ta.setText(""); //Clear
ta.append(t1.getText() + "\n");
ta.append(t2.getText()+ "\n");
ta.append(t3.getText()+ "\n");
ta.append(ch1.getSelectedItem()+ "\n");
ta.append(cbg.getSelectedCheckbox().getLabel()+ "\n");
ta.append(It.getSelectedItem()+ "\n");
}
105
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
106
OUTPUT:
RESULT
107
Java Database Connectivity
108
Ex. No: 11 JDBC
AIM
ALGORITHM
PROGRAM
import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","smvec");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3) +" "+ rs.getInt(4));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
109
}
OUTPUT:
110
RESULT
The JDBC Program for Database Connectivity to java has been executed successfully.
111
Practice Exercise
1. Write a java program that connects to a database using JDBC and does add, deletes, modify
and retrieve operations?
112
Remote Method Invocation
113
Ex. No: 12 Remote Method Invocation
AIM
ALGORITHM
PROGRAM
// Interface code:
import java.rmi.*;
public interface RmiInterface extends Remote
{
double add(double d1, double d2) throws RemoteException;
double sub(double d1, double d2) throws RemoteException;
double mul(double d1, double d2) throws RemoteException;
double div(double d1, double d2) throws RemoteException;
}
114
// Implementation code:
import java.rmi.*;
import java.rmi.server.*;
//Server code:
import java.net.*;
import java.rmi.*;
public class RmiServer
{
public static void main(String args[])
{
try
{
RmiImplementation rmiImp = new RmiImplementation();
Naming.rebind("AddServer", rmiImp);
}
catch(Exception e)
{
System.out.println("Exception: " + e);
}
}
}
115
//Client code :
import java.rmi.*;
public class RmiClient
{
public static void main(String args[])
{
try
{
RmiInterface rmiIntf = (RmiInterface)Naming.lookup("rmi://" + args[0] + "/AddServer");
System.out.println("The first number is: " + args[1]);
double d1 = Double.valueOf(args[1]).doubleValue();
116
OUTPUT:
RESULT
117
Content Beyond the Syllabus
118
JavaScript
Aim:
To create a simple web page using Java Script
Procedure:
Function with arguments, that returns a value
4 .Open the file in the browser. Browser will show the output as shown in the sample program
output.
Source Code :
<html>
<head>
<script type="text/javascript">
function product(a,b)
return a*b
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3))
</script>
<p>The script in the body section calls a function with two parameters (4 and 3).</p>
<p>The function will return the product of these two parameters.</p> </body>
</html>
119
Output :
Result:
Thus a simple Client side web page is created using java script.
120
Servlet
Aim:
To create a dynamic web page using servlet
Procedure:
1. Open Netbeans IDE, Select File -> New Project
2. Select Java Web -> Web Application, then click on Next,
3. Give a name to your project and click on Next,
4. The complete directory structure required for the Servlet Application will be created
automatically by the IDE.
5. To create a Servlet, open Source Package, right click on default packages -> New -
> Servlet.
6. Give a Name to your Servlet class file,
7. Write some code inside your Servlet class.
8. Create an HTML file, right click on Web Pages -> New -> HTML
9. Give it a name. We recommend you to name it index, because browser will always pick up
the index.html file automatically from a directory. Index file is read as the first page of the
web application.
10. Write some code inside your HTML file. We have created a hyperlink to our Servlet in our
HTML file.
11. Edit web.xml file. In the web.xml file you can see, we have specified the url-pattern and
the servlet-name, this means when hello url is accessed our Servlet file will be executed.
12. Run your application, right click on your Project and select Run
Source Code:
ExampleHttpServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Creating Http Servlet by Extending HttpServlet class
public class ExampleHttpServlet extends HttpServlet
{
private String mymsg;
index.html
index<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Http Servlet Demo</title>
121
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
web.xml
<web-app>
<display-name>BeginnersBookServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServlet</servlet-name>
<servlet-class>ExampleHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
122
Output:
Result:
Thus the dynamic web page is created using servlet
123
Viva Voce Questions
1. What is the most important feature of Java?
Java is a platform independent language.
2. What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one
platform (eg Windows) and can execute the class in any other supported platform eg
(Linux,Solaris,etc).
3. What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class
files.
4. Are JVM's platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation
provided by the vendor.
5. What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution
environment also. But JVM is purely a run time environment and hence you will not be able to
compile your source files using a JVM.
8. Does Java support multiple inheritance? Java doesn't support multiple inheritance.
10. Are arrays primitive data types? In Java, Arrays are objects.
Path and Classpath are operating system level environment variales. Path is used define
where the system can find the executables(.exe) files and classpath is used to specify the
location .class files.
12. What are local variables?
Local varaiables are those which are declared within a block of code like methods. Local
variables should be initialised before accessing them
124
13. Can a class declared as private be accessed outside it's package? Not possible.
A final variable's value can't be changed. final variables should be initialized before using them.
A method declared as final can't be overridden. A sub-class can't have the same method
signature with a different implementation.
18. I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final. But you can't define your class as final, if it is an
abstract class. A class declared as final can't be extended by any other class.
19. Can you give few examples of final classes defined in Java API?
java.lang.String, java.lang.Math are final classes.
{
static class InnerClass
{
public static void InnerMethod()
{
System.out.println("Static Inner Class!"); }
}
125
public static void main(String args[])
{
Test.InnerClass.InnerMethod();
}
}
//output: Static Inner Class!
23. What are the restriction imposed on a static method or a static block of code?
A static method should not refer to instance variables without creating an instance and
cannot use "this" operator to refer the instance.
24. I want to print "Hello" even before main() is executed. How will you acheive that?
Print the statement inside a static block of code. Static blocks get executed when the class
gets loaded into the memory and even before the creation of an object. Hence it will be executed
before the main() method. And it will be executed only once.
25. How-will-you-communicate-between-two-Applets
The simplest method is to use the static variables of a shared class since there's only one
instance of the class and hence only one copy of its static variables. A slightly more reliable
method relies on the fact that all the applets on a given page share the same AppletContext. We
obtain this applet context as follows:
AppletContext ac = getAppletContext();
27. How do you cause the applet GUI in the browser to be refreshed when data in it may have
changed?
You invoke the repaint() method. This method causes the paint method, which is required
in any applet, to be invoked again, updating the display.
126
You use the start() method when the applet must perform a task after it is initialized,
before receiving user input. The start() method either performs the applet's work or (more likely)
starts up one or more threads to perform the work.
29. True or false: An applet can make network connections to any host on the Internet. False: An
applet can only connect to the host that it came from.
30. How do you get the value of a parameter specified in the APPLET tag from within the applet's
code?
You use the getParameter("Parameter name") method, which returns the String value
of the parameter.
31. True of false: An applet can run multiple threads.
True. The paint and update methods are always called from the AWT drawing and event
handling thread. You can have your applet create additional threads, which is recommended for
performing time-consuming tasks.
127
COURSE OUTCOMES AND PROGRAM OUTCOMES
List of PSO’s
PSO 1: Establishment of Mathematical and computer systems concepts: To use mathematical
and system concepts to solve multidisciplinary problems using appropriate mathematical
analysis, system and programming concepts on various computing environments.
PSO 2: Establishment of communication and information concepts: To inculcate good breadth of
knowledge to apply and enhance informatics and communication technologies
PSO 3: Establishment of Business, Technological concepts: The ability to interpret and respond to
business agility with relevant software tools and skills and provide newer ideas and innovations in
information technology research
List of Program Outcomes
Engineering Knowledge: Apply knowledge of mathematics and science, with
PO1 fundamentals of
Engineering and Technology to be able to solve complex engineering problems related
to IT.
Problem Analysis: Identify, Formulate, review research literature and analyze
complex engineering
problems related to IT and reaching substantiated conclusions using first principles of
PO2 mathematics,
natural sciences and engineering sciences
Design/Development of solutions: Design solutions for complex engineering
problems related to IT
and design system components or processes that meet the specified needs with
PO3 appropriate
consideration for the public health and safety and the cultural societal and
environmental
considerations
Conduct Investigations of Complex problems: Use research–based knowledge
and research
methods including design of experiments, analysis and interpretation of data, and
PO4 synthesis of the
information to provide valid conclusions.
Modern Tool Usage: Create, Select and apply appropriate techniques, resources
and modern
engineering and IT tools including prediction and modeling to computer science
PO5 related complex
engineering activities with an understanding of the limitations
The Engineer and Society: Apply Reasoning informed by the contextual
knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities
PO6 relevant to the IT
128
professional engineering practice
Environment and Sustainability: Understand the impact of the IT professional
engineering solutions
in societal and environmental contexts and demonstrate the knowledge of, and need
PO7 for sustainable
development
Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities
PO8 and norms of
the engineering practice
Individual and Team Work: Function effectively as an individual and as a member
PO9 or leader in
diverse teams and in multidisciplinary Settings
Communication: Communicate effectively on complex engineering activities with
the engineering
community and with society at large such as able to comprehend and with write
PO10 effective reports and
design documentation, make effective presentations and give and receive clear
instructions.
Project Management and Finance: Demonstrate knowledge and understanding of
the engineering
management principles and apply these to one’s own work, as a member and leader in
PO11 a team, to
manage projects and in multi-disciplinary environments
Life-Long Learning: Recognize the need for and have the preparation and ability to
PO12 engage in
independent and life-long learning the broadest context of technological change
129
Java Lab Manual
Department of IT 130