Java Programming Lab Guide for MCA Students
Java Programming Lab Guide for MCA Students
Prepared by
Mr. Ashish Nayyar
Programme Director MCA
Ashish K Nayyar
MCA Semester-III
Your preparation before each laboratory session is extremely important. At minimum your
preparation should include reading the entire session and its associated experiments. Your
goal should be to identify the purpose of each experiment within the laboratory session
before the actual session begins. A good approach is to read each experiment and then ask
yourself why that particular experiment was included at that specific point in the laboratory
session. You should approach each session in a spirit of experimentation. The laboratory
activities are not designed to tell you every detail about the topics covered. Instead, are
designed to encourage you to experiment and discover. Once you adapt to this mode of
learning, you will find that a computer installation offers an endless opportunity to explore
and learn. In most cases the laboratory activities involve experimenting with short
programs. Your instructor will tell you how to gain access to this software.
Ashish K Nayyar
Each laboratory session contains more experiments than your students may be able to
complete in a two-hour period. This becomes more pronounced as the sessions progress
into experiments that require the development of entire routines. You are encouraged to
assign those experiments that emphasize the topics you wish to cover.
Many of the experiments consist of running an example program and then modifying it. To
avoid the tedium of typing and to allow students more time for experimentation and
reflection, the initial form of these programs can be stored in files and made available to the
students.
I would like to thank Dr. Prerna Mahajan HOD-IT for her comments and suggestions.
Ashish K Nayyar
Lab No.1
Concept:
To teach how to write and execute simple java Programs.
Objective:
Teach the students how to write and execute a simple program.
Basic terminology related to programming.
High-Level Programming Languages
The Program Preparation Process
A Simple java Program
Modified form of first java program
Laboratory Problems
Pre Lab(Background):
When we consider a Java program it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.
Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a
class.
Class - A class can be defined as a template/ blue print that describes the
behaviors/states that object of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
First Java Program:
Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {
*/
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Java Variables:
We would see following type of variables in Java:
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static variables)
Lab Assignments:
1. Write a program to print Hello world
2. Write a program to compute the area of a circle.
3. Write a program based on type casting & conversions.
4. Write a program to add, subtract, and divide and multiple 2 numbers.
5. Write a program to print the grade of a student.
6. WAP that accepts number as Command line arguments.
7. Write program that randomly generates a number and checks whether it is prime or not.
8. Write program that randomly generates a number from a range 10-99 and checks
whether it is Armstrong or not.
Ashish K Nayyar
Solutions to Lab No 1.
1.
class HelloWorld
{
public static void main(String args[])
{
[Link]("Hello World");
}
}
2. import [Link].*;
class AreaCircle
{
public static void main(String args[]) throws IOException
{
float area,rad;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter radius of circle :- ");
rad=[Link]([Link]());
area=(float)3.14*rad*rad;
[Link]("Area = "+area);
}
}
3.
import [Link].*;
class AreaCircle
{
public static void main(String args[]) throws IOException
{
float area,rad;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter radius of circle :- ");
Ashish K Nayyar
rad=[Link]([Link]());
area=(float)3.14*rad*rad;// typecasting
[Link]("Area = "+area);
}
}
4.
import [Link].*;
class Calc
{
public static void main(String args[]) throws IOException
{
int ch,a,b;
float result;
BufferedReader in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Select Operation to be performed:-");
[Link]("[Link]\[Link]\[Link]\[Link]");
ch=[Link]([Link]());
if(ch>0&&ch<5)
{
[Link]("Enter num1 :- ");
a=[Link]([Link]());
[Link]("Enter num2 :- ");
b=[Link]([Link]());
if(ch==1)
result=a+b;
else if(ch==2)
result=a-b;
else if(ch==3)
result=a*b;
else
result=(float)a/b;
Ashish K Nayyar
}
else
{
[Link]("Invalid Percentage");
}
}
}
6.
class LargestCmdl
{
public static void main(String a[])
{
int n1=0,n2=0,n3=0,e;
n1=[Link](a[0]);
n2=[Link](a[1]);
n3=[Link](a[2]);
e=n1;
if(e<n2)
e=n2;
if(e<n3)
e=n3;
[Link]("The largest no. is :- "+e);
}
}
7.
import [Link];
class RandPrime
{
public static void main(String a[])
{
int flag=1,i,num;
Ashish K Nayyar
sum=sum+(rem*rem*rem);
num=(int)num/10;
}
if(sum==num1)
[Link]("Its a armstrong no. ");
else
[Link]("Its not a armstrong no. ");
}
}
Ashish K Nayyar
Lab No.2
Concept: To teach them how to implement and use Arrays & Strings in Java
Objectives:
To explain advantages of arrays
Functions on arrays
o Searching an element in an array
o Sorting an array
o Copying the array elements to another array.
String Handling through readymade functions.
Vectors
Functions on vectors
Laboratory Problems
Pre Lab(Background):
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
Ashish K Nayyar
Lab Assignments:
1. Write a program to insert an array and print those elements using command line
arguments.
2. Write a program to initialize and print the elements of an array.
3. Write a program to sort an array in ascending and descending order.
4. WAP to perform linear search on an Array of 5 integers.
5. WAP to perform binary search on an Array of 5 integers.
6. WAP to display smallest element of an Array of 5 integers.
Solutions to Lab No 2.
1.
class CmdlArr
{
public static void main(String a[])
{
int l,i;
l=[Link];
[Link]("Elements in the array are :- ");
for(i=0;i<l;i++)
{
[Link](a[i]);
}
}
}
Ashish K Nayyar
2.
class ArrayOne
{
public static void main(String args[])
{
int a[]={10,50,20,70,40};
int i;
[Link]("Elements in the array are :- ");
for(i=0;i<[Link];i++)
{
[Link](a[i]);
}
}
}
3.
import [Link].*;
class ArraySort
{
public static void main(String args[]) throws IOException
{
int a[]=new int[5];
int i,j,temp;
BufferedReader in1=new BufferedReader(new InputStreamReader([Link]));
for(i=0;i<[Link];i++)
{
[Link]("Enter element no."+(i+1)+" :- ");
a[i]=[Link]([Link]());
}
for(i=0;i<[Link];i++)
{
for(j=0;j<[Link];j++)
Ashish K Nayyar
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
[Link]("Elements in ascending order are :- ");
for(i=0;i<[Link];i++)
{
[Link](a[i]);
}
[Link]("Elements in descending order are :- ");
for(i=([Link]-1);i>=0;i--)
{
[Link](a[i]);
}
}
}
4.
import [Link].*;
class LinearSearch
{
public static void main(String args[]) throws IOException
{
int a[]=new int[5];
int i,n,flag=0;
BufferedReader in1=new BufferedReader(new InputStreamReader([Link]));
for(i=0;i<[Link];i++)
Ashish K Nayyar
{
[Link]("Enter element no."+(i+1)+" :- ");
a[i]=[Link]([Link]());
}
[Link]("Enter element to be searched :- ");
n=[Link]([Link]());
for(i=0;i<[Link];i++)
{
if(a[i]==n)
{
[Link]("Element found at position :- "+(i+1));
flag=1;
}
}
if(flag==0)
{
[Link]("Element not found!!!");
}
}
}
5.
import [Link].*;
class BinSearch
{
public static void main(String args[]) throws IOException
{
int a[]=new int[5];
int i,j,temp,n,lb,ub,mid,flag=0;
BufferedReader in1=new BufferedReader(new InputStreamReader([Link]));
for(i=0;i<[Link];i++)
{
Ashish K Nayyar
break;
}
else
{
if(n>a[mid])
lb=mid+1;
else
ub=mid-1;
}
mid=(lb+ub)/2;
}
if(flag==0)
[Link]("Element not found !!");
}
}
6.
import [Link].*;
class SmallElement
{
public static void main(String args[]) throws IOException
{
int a[]=new int[5];
int i,small;
BufferedReader in1=new BufferedReader(new InputStreamReader([Link]));
for(i=0;i<[Link];i++)
{
[Link]("Enter element no."+(i+1)+" :- ");
a[i]=[Link]([Link]());
}
small=a[0];
for(i=1;i<[Link];i++)
Ashish K Nayyar
{
if(small>a[i])
{
small=a[i];
}
}
[Link]("The smallest element is :- "+small);
}
}
Ashish K Nayyar
Lab No.3
Concept: Arrays & Strings in Java
Objective:
To teach them how to implement and use Arrays & Strings in Java
To explain advantages of arrays
Functions on arrays
o Searching an element in an array
o Sorting an array
o Copying the array elements to another array.
String Handling through readymade functions.
Vectors
Functions on vectors
Laboratory Problems
Pre Lab(Background):Same of Lab2
Lab Assignments:
1. WAP to display difference between smallest and largest elements of an Array of 5
integers.
2. Write a program to perform following Matrix operations using arrays.
a. Addition
b. multiplication
3. Write a program to demonstrate the working of any Ten String class functions.
4. WAP to extract surname from complete name
5. Write a program to create a class called StringDemo and declare three strings and use
functions like length, charAt and equals on them.
Solutions to Lab No 3.
1. import [Link].*;
class DiffLargeSmall
{
Ashish K Nayyar
2.
import [Link].*;
class MatOp
{
public static void main(String a[]) throws IOException
{
int[][]m1=new int[3][3];
int[][]m2=new int[3][3];
int[][]m3=new int[3][3];
int i,j,k,op,flag=0;
BufferedReader in = new BufferedReader(new InputStreamReader([Link]));
[Link]("First Matrix :- ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
[Link]("Enter element no. "+i+j+" :- ");
m1[i][j]=[Link]([Link]());
}
}
[Link]("Second Matrix :- ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
[Link]("Enter element no. "+i+j+" :- ");
m2[i][j]=[Link]([Link]());
}
}
[Link]("Select operation");
[Link]("[Link]\[Link]\[Link]");
Ashish K Nayyar
op=[Link]([Link]());
if(op==1)
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}
}
else if(op==2)
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=m1[i][j]-m2[i][j];
}
}
}
else if(op==3)
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=0;
for(k=0;k<3;k++)
{
m3[i][j]+=m1[i][k]*m2[k][j];
Ashish K Nayyar
}
}
}
}
else
{
[Link]("Wrong Operation");
flag=1;
}
if(flag==0)
{
[Link]("First Matrix :- ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
[Link](m1[i][j]+" ");
}
[Link]();
}
[Link]("Second Matrix :- ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
[Link](m2[i][j]+" ");
}
[Link]();
}
[Link]("Result Matrix :- ");
for(i=0;i<3;i++)
Ashish K Nayyar
{
for(j=0;j<3;j++)
{
[Link](m3[i][j]+" ");
}
[Link]();
}
}
}
}
3.
class StringFunc
{
public static void main(String a[])
{
String s1 = new String("My name is Aakash Garg") ;
String s2 = new String("My name is Subhash");
char[] ch = new char[] { 'g', 'G' };
char[] copy;
int i;
[Link]("The char at 1 :- " + [Link](1));
Lab No.4
Concept: To make students learn how to implement Classes and Objects
Objective:
Declaration of a class
Use of constructors and destructors
Methods in a class
Laboratory Problems
Pre Lab(Background):
Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a
class.
Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many
objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging, running
If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Classes in Java:
A class is a blue print from which individual objects are created.
Lab Assignments:
1. Write a program to create a class called Box and calculate its volume by calling its
method.
Ashish K Nayyar
2. Write a program to create a class called Test and pass its object to one of its method to
illustrate usage of reference variables.
3. Write a program to create a class called Use Static and declare some static variables, a
static method that will print those variables and static block which will perform some
operation on that variable.
Solutions to Lab No 4.
1.
import [Link].*;
class Box
{
int l;
int w;
int h;
Box()
{
l=0;
w=0;
h=0;
}
Box(int x)
{
l=x;
w=x;
h=x;
}
Box(int a,int b,int c)
{
l=a;
w=b;
h=c;
}
Ashish K Nayyar
int a,b;
Test()
{
a=10;
b=20;
}
void swap(Test t)
{
int temp;
temp=t.a;
t.a=t.b;
t.b=temp;
}
void Display()
{
[Link]("A="+a+" B= "+b+"\n");
}
}
class RefVarDemo
{
public static void main(String args[])
{
Test to=new Test();
[Link]();
[Link](to);
[Link]();
}
}
3.
class UseStatic
{
Ashish K Nayyar
Lab No.5
Concept: Constructor Function & Function Overloading
Objective:
To teach them the purpose of Constructor Function & Concept of function
overloading
Use of constructors and destructors
Methods in a class
Laboratory Problems
Pre Lab(Background):
Constructors:
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more
than one constructor. Constructor should always be declared in public section of the class.
Destructors:
There is no such thing as destructor in java but we have a finalize method which is similar to
a class.
Lab Assignments:
1. Write a program to create a class called triangle with base and height as the attributes
and calculate its area using parameterized constructor.
2. Write a program to create a class called Rectangle and calculate its area using this
keyword.
3. Write a program to create a class Area and calculate area of rectangle and circle using
method overloading.
Solutions to Lab No 5.
1.
class Triangle
Ashish K Nayyar
{
int b;
int h;
Triangle(int x,int y)
{
b=x;
h=y;
}
float area()
{
return (float)0.5*b*h;
}
}
class TrianDemo
{
public static void main(String args[])
{
Triangle t1=new Triangle(20,30);
float area;
area=[Link]();
[Link]("The area of the triangle is :- "+area);
}
}
2.
class Rectangle
{
int l;
int b;
Rectangle()
{
this.l=0;
Ashish K Nayyar
this.b=0;
}
Rectangle(int a)
{
this.l=a;
this.b=a;
}
Rectangle(int a,int c)
{
this.l=a;
this.b=c;
}
int area()
{
return l*b;
}
}
class RectDemo
{
public static void main(String args[])
{
Rectangle r=new Rectangle(10,20);
int area=[Link]();
[Link]("Area of the rectangle is :- "+area);
}
}
3. import [Link].*;
class Area
{
float calcArea(int r)
{
Ashish K Nayyar
return (float)3.14*r*r;
}
int calcArea(int a,int b)
{
return a*b;
}
}
class AreaDemo
{
public static void main(String a[]) throws IOException
{
int choice,flag=0;
float area=0;
Area a1=new Area();
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Select from below :- ");
[Link]("[Link] of Circle\[Link] Of Rectangle\n Enter choice :- ");
choice=[Link]([Link]());
if(choice==1)
{
int rad;
[Link]("Enter radius :- ");
rad=[Link]([Link]());
area=[Link](rad);
}
else if(choice==2)
{
int l,b;
[Link]("Enter length :- ");
l=[Link]([Link]());
[Link]("Enter breadth :- ");
Ashish K Nayyar
b=[Link]([Link]());
area=[Link](l,b);
}
else
{
[Link]("Wrong Choice");
flag=1;
}
if(flag==0)
{
[Link]("The area is :- "+area);
}
}
}
Ashish K Nayyar
Lab No.6
Concept: Inheritance in java and Use of super, abstract and final keyword
Objective:
To teach them Inheritance in java and Use of super, Abstract and final keyword
Implementation inheritance
Use of abstract
Use of super and this
Laboratory Problems
Pre Lab(Background):
Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical
classifications. Using inheritance, you can create a general class that defines traits common
to a set of related items. This class may then be inherited by other, more specific classes,
each adding only those things that are unique to the inheriting class. In keeping with
standard java terminology, a class that is inherited is referred to as a base class. The class
that does the inheriting is called the derived class. Further, a derived class can be used as a
base class for another derived class. In this way, multiple inheritance is achieved.
When a class inherits another, the members of the base class become members of the
derived class. Class inheritance uses this general form:
class derived-class-name extends base-class-name {
// body of class
}
Lab Assignments:
1. Write a program to create a class called Box with instance variables width, height and
depth. Create another class BoxWeight which inherits class Box with an additional
instance variable weight. Compute the volume of the box using inheritance.
2. Implement the above program using super keyword.
3. Create a class Figure and its 2 subclasses Rectangle and Triangle and calculate its area
using dynamic method dispatch.
Ashish K Nayyar
4. Implement the above program using abstract classes by making Figure class abstract.
5. Write relevant programs to show the usage of final keyword with class, variables and
methods in java.
Solutions to Lab No 6.
1.
import [Link].*;
class Box1
{
int height,width,depth;
}
{
volume=height*width*depth;
}
void print()
{
[Link]("Volume = "+volume+" Weight= "+weight+"Kg");
}
}
class BoxDemo1
{
public static void main(String a[]) throws IOException
{
int h,w,d,we;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter height :- ");
h=[Link]([Link]());
[Link]("Enter width :- ");
w=[Link]([Link]());
[Link]("Enter depth :- ");
d=[Link]([Link]());
[Link]("Enter Weight(In KG) :- ");
we=[Link]([Link]());
BoxWeight bw=new BoxWeight(h,w,d,we);
[Link]();
[Link]();
}
}
2.
import [Link].*;
class Box2
{
Ashish K Nayyar
int height,width,depth;
Box2()
{
height=0;
width=0;
depth=0;
}
Box2(int x,int y,int z)
{
height=x;
width=y;
depth=z;
}
}
class BoxWeight1 extends Box2
{
int weight;
int volume;
BoxWeight1()
{
super();
weight=0;
}
BoxWeight1(int x,int y,int z,int n)
{
super(x,y,z);
weight=n;
}
void calcVolume()
{
volume=height*width*depth;
Ashish K Nayyar
}
void print()
{
[Link]("Volume = "+volume+" Weight= "+weight+"Kg");
}
}
class BoxDemo2
{
public static void main(String a[]) throws IOException
{
int h,w,d,we;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter height :- ");
h=[Link]([Link]());
[Link]("Enter width :- ");
w=[Link]([Link]());
[Link]("Enter depth :- ");
d=[Link]([Link]());
[Link]("Enter Weight(In KG) :- ");
we=[Link]([Link]());
BoxWeight1 bw=new BoxWeight1(h,w,d,we);
[Link]();
[Link]();
}
}
3.
import [Link].*;
class Figure
{
void area()
{
Ashish K Nayyar
[Link]("Calculating Area");
}
}
class Rectangle extends Figure
{
int l,b,area;
Rectangle()
{
l=b=0;
}
Rectangle(int x,int y)
{
l=x;
b=y;
}
void area()
{
area=l*b;
[Link]("Area of rectangle = "+area);
}
}
class Triangle extends Figure
{
int b,h;
float area;
Triangle()
{
b=h=0;
}
Triangle(int x,int y)
{
Ashish K Nayyar
b=x;
h=y;
}
void area()
{
area=(float)0.5*b*h;
[Link]("Area of triangle = "+area);
}
}
class DynDisDemo
{
public static void main(String args[]) throws IOException
{
int choice,l,b;
Figure f=new Figure();
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Select from below :- \[Link] of Rectangle\[Link] of Triangle\nEnter
choice :- ");
choice=[Link]([Link]());
if(choice==1)
{
[Link]("Enter length");
l=[Link]([Link]());
[Link]("Enter breadth");
b=[Link]([Link]());
[Link]();
f=new Rectangle(l,b);
[Link]();
}
else if(choice==2)
{
Ashish K Nayyar
[Link]("Enter Base");
l=[Link]([Link]());
[Link]("Enter Height");
b=[Link]([Link]());
[Link]();
f=new Triangle(l,b);
[Link]();
}
}
}
4.
import [Link].*;
abstract class Figure
{
abstract float area();
}
class Rect extends Figure
{
int l,b;
Rect(int x,int y)
{
l=x;
b=y;
}
float area()
{
return l*b;
}
}
class Trian extends Figure
{
Ashish K Nayyar
int b,h;
Trian(int x,int y)
{
b=x;
h=y;
}
float area()
{
return ((float)0.5*b*h);
}
}
class AbsDemo
{
public static void main(String ar[]) throws IOException
{
int choice=0,a,b;
float area;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Select from below :- \[Link] of Rectangle\[Link] of Triangle\n");
[Link]("Enter choice :- ");
choice=[Link]([Link]());
if(choice==1)
{
[Link]("Enter length :- ");
a=[Link]([Link]());
[Link]("Enter breadth :- ");
b=[Link]([Link]());
Rect r1=new Rect(a,b);
area=[Link]();
[Link]("Area of Rectangle = "+area);
}
Ashish K Nayyar
else if(choice==2)
{
[Link]("Enter base :- ");
a=[Link]([Link]());
[Link]("Enter height :- ");
b=[Link]([Link]());
Trian t1=new Trian(a,b);
area=[Link]();
[Link]("Area of Triangle = "+area);
}
}
}
5.
class A {
final float PI=3.14f;
final void meth() {
[Link]("This is a final method in which value of PI is"+PI);
}
}
class B extends A {
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}
}
Ashish K Nayyar
Lab No.7
Concept: Packages in java
Objective:
How to create and use Packages in java
Pre Lab(Background):
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations
and annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
[Link] - bundles the fundamental classes
[Link] - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is
a good practice to group related classes implemented by you so that a programmer can
easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier
to locate the related classes.
Lab Assignments:
1. Write relevant programs showing the usage of package and access protection in java.
2. Write relevant programs to show the concept of importing a package
Solutions to Lab No 7.
1.
package MyPack;
/* Now, the Balance class, its constructor, and its show() method are public. This means
that they can be used by non-subclass code outside their package.*/
public class Balance {
String name;
Ashish K Nayyar
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
[Link](); // you may also call show()
}
}
Ashish K Nayyar
Lab No.8
Concept: Interface
Objective:
To make them understand the concept of interface
Pre Lab(Background):
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
An interface is similar to a class in the following ways:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The bytecode of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including:
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Lab Assignments:
1. Write a program to implement stacks using interfaces.
2. Write a program to implementing nesting of interface.
Ashish K Nayyar
Solutions to Lab No 8.
1.
interface Stack
{
void push(int item);
void pop();
}
class MyStack implements Stack
{
int st[];
int tos;
MyStack()
{
st=new int[5];
tos=-1;
}
public void push(int item)
{
if(tos==[Link]-1)
{
[Link]("Stack Overflow");
}
else
{
st[++tos]=item;
[Link]("Item Pushed is :- "+item);
}
}
public void pop()
{
if(tos<0)
Ashish K Nayyar
{
[Link]("Stack Underflow");
}
else
{
[Link]("Item popped is :- "+st[tos--]);
}
}
}
class InterStDemo
{
public static void main(String args[])
{
int i;
MyStack ob=new MyStack();
for(i=1;i<=6;i++)
[Link](i);
for(i=1;i<=6;i++)
[Link]();
}
}
2.
// A nested interface example.
// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
Ashish K Nayyar
Lab No.9
Concept: Exception Handling
Objective:
To teach them how to deal with exceptions in Java
Explaining the working of try catch and throw
User defined exceptions
Laboratory Problems
Pre Lab(Background):
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file
is to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you
can rarely do anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.
Exception Hierarchy:
Ashish K Nayyar
All exception classes are subtypes of the [Link] class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen
in case of severe failures, which are not handled by the java programs. Errors are generated
to indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Lab Assignments:
1. Write relevant programs to show the usage of try, catch, throw, throws and finally in
java.
2. Write a program to create user-defined exception class using the extends keyword.
3. WAP that throws exception if age of voter is less than 18.
4. WAP that throws exceptions if stack is full or is empty.
5. WAP that throws exception if bank balance drops below 1000 due to any
transaction.
Solutions to Lab No 9.
1. import [Link].*;
class AgeExcep extends Exception
{
AgeExcep(){};
}
class Voter
{
String vname;
int age;
Voter()
{
vname="NO NAME";
age=0;
Ashish K Nayyar
}
void readVal() throws IOException,AgeExcep
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name:- ");
vname=[Link]();
[Link]("Enter age :- ");
age=[Link]([Link]());
if(age<18)
throw new AgeExcep();
}
void showData()
{
[Link]("Name= "+vname);
[Link]("Age= "+age+"\nVoter is Valid!!!");
}
}
class VoterDemo
{
public static void main(String a[])throws IOException
{
Voter v1=new Voter();
try
{
[Link]();
[Link]();
}
catch(AgeExcep ae)
{
[Link]("Age cannot be less than 18");
}
Ashish K Nayyar
}
}
2.
import [Link].*;
class AgeExcep extends Exception
{
AgeExcep(){};
}
class Voter
{
String vname;
int age;
Voter()
{
vname="NO NAME";
age=0;
}
void readVal() throws IOException,AgeExcep
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name:- ");
vname=[Link]();
[Link]("Enter age :- ");
age=[Link]([Link]());
if(age<18)
throw new AgeExcep();
}
void showData()
{
[Link]("Name= "+vname);
[Link]("Age= "+age+"\nVoter is Valid!!!");
Ashish K Nayyar
}
}
class VoterDemo
{
public static void main(String a[])throws IOException
{
Voter v1=new Voter();
try
{
[Link]();
[Link]();
}
catch(AgeExcep ae)
{
[Link]("Age cannot be less than 18");
}
}
}
3.
import [Link].*;
class AgeExcep extends Exception
{
AgeExcep(){};
}
class Voter
{
String vname;
int age;
Voter()
{
vname="NO NAME";
Ashish K Nayyar
age=0;
}
void readVal() throws IOException,AgeExcep
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name:- ");
vname=[Link]();
[Link]("Enter age :- ");
age=[Link]([Link]());
if(age<18)
throw new AgeExcep();
}
void showData()
{
[Link]("Name= "+vname);
[Link]("Age= "+age+"\nVoter is Valid!!!");
}
}
class VoterDemo
{
public static void main(String a[])throws IOException
{
Voter v1=new Voter();
try
{
[Link]();
[Link]();
}
catch(AgeExcep ae)
{
[Link]("Age cannot be less than 18");
Ashish K Nayyar
}
}
}
4.
class StackFull extends Exception
{
StackFull(){};
}
class StackEmpty extends Exception
{
StackEmpty(){};
}
class MyStack
{
int st[];
int tos;
MyStack()
{
st=new int[5];
tos=-1;
}
void push(int item) throws StackFull
{
if(tos==[Link]-1)
{
throw new StackFull();
}
else
{
st[++tos]=item;
[Link]("Item Pushed is :- "+item);
Ashish K Nayyar
}
}
void pop() throws StackEmpty
{
if(tos<0)
{
throw new StackEmpty();
}
else
{
[Link]("Item popped is :- "+st[tos--]);
}
}
}
class InterStDemo1
{
public static void main(String args[])
{
int i;
MyStack ob=new MyStack();
try
{
for(i=1;i<=6;i++)
[Link](i);
}
catch(StackFull sf)
{
[Link]("Stack Overflow");
}
try
{
Ashish K Nayyar
for(i=1;i<=6;i++)
[Link]();
}
catch(StackEmpty se)
{
[Link]("Stack Underflow");
}
}
}
5.
import [Link].*;
class BalExcep extends Exception
{
BalExcep(){};
}
class Customer
{
String cname;
float bal;
Customer()
{
cname="NO NAME";
bal=0;
}
void readVal() throws IOException,BalExcep
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name:- ");
cname=[Link]();
[Link]("Enter balance :- ");
bal=[Link]([Link]());
Ashish K Nayyar
if(bal<0)
throw new BalExcep();
}
void showData()
{
[Link]("Name= "+cname);
[Link]("Balace= "+bal);
}
}
class CustDemo
{
public static void main(String a[])throws IOException
{
Customer c1=new Customer();
try
{
[Link]();
[Link]();
}
catch(BalExcep be)
{
[Link]("Balance Cannot Be Negative");
}
}
}
Ashish K Nayyar
Lab No.10
Concept: Multithreading in java
Objective:
To teach them design, priorities and Synchronize Multiple threads in java
Pre Lab(Background):
Java is a multithreaded programming language which means we can develop multithreaded
program using Java. A multithreaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time making optimal use
of the available resources especially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources
such as a CPU. Multithreading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. Following diagram shows complete life cycle of a thread.
Above-mentioned stages are explained here:
New: A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
Ashish K Nayyar
Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transition back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY
(a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee
the order in which threads execute and very much platform dependent.
Lab Assignments:
1. Write relevant programs to show the concept of creating Thread through thread
class and Runnable interface
2. WAP to print multiples of 2,3 simultaneously.
Solutions to Lab No 10.
1.
class NewThread1 implements Runnable
{
private Thread t;
private String threadName;
NewThread1(String name)
{
threadName=name;
[Link](threadName+" Created");
[Link]("Starting"+threadName);
t=new Thread(this,threadName);
[Link]();
Ashish K Nayyar
}
public void run()
{
[Link](threadName+" Running");
try
{
for(int i=0;i<=5;i++)
{
[Link](threadName+" "+i);
[Link](500);
}
}
catch(InterruptedException e)
{
[Link](threadName+" Interrupted");
}
}
}
class NewThread extends Thread
{
private Thread t;
private String threadName;
NewThread(String name)
{
threadName=name;
[Link](threadName+" Created");
[Link]("Starting"+threadName);
t=new Thread(this,threadName);
[Link]();
}
public void run()
Ashish K Nayyar
{
[Link](threadName+" Running");
try
{
for(int i=0;i<=5;i++)
{
[Link](threadName+" "+i);
[Link](500);
}
}
catch(InterruptedException e)
{
[Link](threadName+" Interrupted");
}
}
}
2.
//Program that creates multiple threads by implementing Runnable
try{
for(int i=1;i<=10;i++)
{
[Link](name +" : "+(i*2));
[Link](100);
}
}
catch(InterruptedException e)
{
[Link](name +" Interrupted");
}
[Link](name +" Exiting");
[Link](100);
}
}
catch(InterruptedException e)
{
[Link](name +" Interrupted");
}
[Link](name +" Exiting");
Lab No.11
Concept: Thread Priorities and Synchronization
Objective:
To teach them design, priorities and Synchronize Multiple threads in java
Teaching thread synchronization
Teaching thread priority.
{
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{
[Link]();
}
}
class HiLoPri {
public static void main(String args[]) {
[Link]().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
[Link]();
[Link]();
try {
[Link](10000);
}
catch (InterruptedException e)
{
[Link]("Main thread interrupted.");
}
[Link]();
[Link]();
// Wait for child threads to terminate.
try {
Ashish K Nayyar
[Link]();
[Link]();
}
catch (InterruptedException e)
{
[Link]("InterruptedException caught");
}
[Link]("Low-priority thread: " + [Link]);
[Link]("High-priority thread: " + [Link]);
}
}
2.
class Callme {
void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
Ashish K Nayyar
[Link]();
}
public void run() {
[Link](msg);
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Ashish K Nayyar
Lab No.12
Concept: Networking Basics in java
Objective:
To teach them to write Network based programs in java
Pre Lab(Background):
InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address. You interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address. The InetAddress class hides the
number inside. InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress object, you have
to use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class. This is done in lieu of
overloading a constructor with various parameter lists when having unique method names
makes the results much clearer. Three commonly used InetAddress factory methods are
shown here:
static InetAddress getLocalHost( )
throws UnknownHostException
static InetAddress getByName(String hostName)
throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local
host. The getByName( ) method returns an InetAddress for a host name passed to it. If
these methods are unable to resolve the host name, they throw an
UnknownHostException.
TCP/IP Client Sockets
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point,
stream-based connections between hosts on the Internet. A socket can be used to connect
Ashish K Nayyar
Java’s I/O system to other programs that may reside either on the local machine or on any
other machine on the Internet.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The ServerSocket class is designed to be a “listener,” which waits for clients to connect
before doing anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is
designed to connect to server sockets and initiate protocol exchanges. Because client
sockets are the most commonly used by Java applications, they are examined here. The
creation of a Socket object implicitly establishes a connection between the client and
server. There are no methods or constructors that explicitly expose the details of
establishing that connection.
Lab Assignments:
1. Program that accepts a host name and display its IP address.
2. Write a TCP/IP client-server program that echoes whatever is typed on the client to
the server.
Solutions to Lab No12.
1.
// Demonstrate InetAddress.
import [Link].*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}
Ashish K Nayyar
2.
// [Link]: a simple client program
import [Link].*;
import [Link].*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket("",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = [Link]();
DataInputStream dis = new DataInputStream(s1In);
String st = new String ([Link]());
[Link](st);
// When done, just close the connection and exit
[Link]();
[Link]();
[Link]();
}
}
// [Link]: a simple server program
import [Link].*;
import [Link].*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=[Link](); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = [Link]();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
Ashish K Nayyar
Lab No.13
Concept: Remote Method Invocation
Objective:
To make them implement Remote Method Invocation
Pre Lab(Background):
The Remote Method Invocation (RMI) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM. The RMI provides remote communication between the applications
using two objects stub and skeleton.
Understanding stub and skeleton
RMI uses stub and skeleton object for communication with the remote object. A remote
object is an object whose method can be invoked from another JVM. Let's understand the
stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
Ashish K Nayyar
Lab Assignments:
1. WAP to demonstrate client server application using Java RMI.
Solutions to Lab No 13.
1.
import [Link].*;
public interface myintf extends Remote
{int add(int a,int b)throws RemoteException;
}
import [Link].*;
public class myclient
{
public static void main( String s[])
Ashish K Nayyar
{
try
{
myintf mf=(myintf) [Link]("rmi://localhost/server");
[Link](""+[Link](10,20));
}
catch(Exception e)
{ [Link](""+[Link]());
}
}
}
import [Link].*;
import [Link].*;
public class myserver
{
public static void main(String s[])
{
try
{
myimp mp=new myimp();
[Link]("server",mp);
}
catch(Exception e)
{ [Link](""+[Link]());
}
}
}
Ashish K Nayyar
Lab No.14
Concept: Abstract Window Toolkit and Applets
Objective:
To teach them how to write Applets and use AWT controls.
Pre Lab(Background):
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-
alone programs. Instead, they run within either a web browser or an applet viewer. The
illustrations shown in this chapter were created with the standard applet viewer, called
appletviewer, provided by the JDK. But you can use any applet viewer or browser you like.
Execution of an applet does not begin at main( ). Actually, few applets even have main( )
methods. Instead, execution of an applet is started and controlled with an entirely different
mechanism. Output to your applet’s window is not performed by [Link]( ).
Rather, in non-Swing applets, output is handled with various AWT methods, such as
drawString( ), which outputs a string to a specified X,Y location. Input is also handled
differently than in a console application.
Lab Assignments:
1. Program that displays the life cycle of the Applet and other relevant programs that
shows the implementation of Applets in java.
2. Write Programs to draw different figures using AWT.
3. Write programs to add label, Buttons, Textfield, list etc using AWT.
Solutions to Lab No 14.
1.
import [Link].*;
import [Link].*;
/*
<applet code="SecondApplet" width=300 height=300>
</applet>
*/
public class SecondApplet extends Applet
{
Ashish K Nayyar
String msg;
//set the foreground and background color
public void init()
{
setBackground([Link]);
setForeground(new Color(10,12,130));
msg="Inside init( )--";
}
public void start( )
{
msg+="Inside start( )--";
}
public void paint(Graphics g)
{
msg+=" Inside paint( ).";
[Link](msg,30,30);
}
}
2.
// Draw rectangles
import [Link].*;
import [Link].*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet {
public void paint(Graphics g) {
[Link](10, 10, 60, 50);
[Link](100, 10, 60, 50);
Ashish K Nayyar
3.
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="ButtonDemo2" width=300 height=250>
</applet>
*/
public class ButtonDemo2 extends Applet implements ActionListener
{
String msg;
Font f1;
Button b1;
TextField t1;
Label l1,l2;
boolean f;
public void init()
{
setBackground(new Color(255,192,203));
f1=new Font("verdana",[Link],15);
setFont(f1);
Ashish K Nayyar
msg="Number is Odd";
}
f=true;
repaint();
}
}
Lab No.15
Concept: AWT Controls
Objective:
To teach them how to write Applets and use AWT controls.
Pre Lab(Background):
AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java’s largest packages.
Fortunately, because it is logically organized in a top-down, hierarchical fashion, it is easier
to understand and use than you might at first believe.
Lab Assignments:
1. Create a login window to check user name and password using text fields and
command buttons
Ashish K Nayyar
2. Create 3 control boxes for font name, size and style, change font of the text
according to user selection.(Self-Practice Question)
Solutions to Lab No 15.
1.
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="Login" width=300 height=250>
</applet>
*/
public class Login extends Applet
implements ActionListener
{
String msg;
Font f1;
Button b1;
TextField t1,t2;
Label l1,l2;
boolean f;
public void init()
{
setBackground(new Color(255,192,203));
f1=new Font("verdana",[Link],15);
setFont(f1);
b1=new Button(" Login");
t1=new TextField(20);
t2=new TextField(20);
[Link](new Color(255,192,203));
[Link](10,100,150,30);
[Link](10,60,150,30);
[Link](160,60,100,30);
[Link](160,100,100,30);
[Link](75,150,130,40);
add(l1);
add(l2);
add(t1);
add(t2);
add(b1);
[Link](this);
}
public void paint(Graphics g)
{
if(f)
[Link](msg,15,220);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
if(("ashish".equals([Link]()) )&&
("mypassword".equals([Link]())))
{
msg="Login Succesful";
}
Ashish K Nayyar
else
{
msg="Username/Password Mismatch!";
}
f=true;
repaint();
}
}
public void stop()
{
f=false;
}
}
Ashish K Nayyar
Lab No.16
Concept: Layout Managers
Objective:
To teach them various layout managers
Pre Lab(Background):
A layout manager automatically arranges your controls within a window by using some type
of algorithm. If you have programmed for other GUI environments, such as Windows, then
you are accustomed to laying out your controls by hand. While it is possible to lay out Java
controls by hand, too, you generally won’t want to, for two main reasons. First, it is very
tedious to manually lay out a large number of components. Second, sometimes the width
and height information is not yet available when you need to arrange some control, because
the native toolkit components haven’t been realized. This is a chicken-and-egg situation; it is
pretty confusing to figure out when it is okay to use the size of a given component to
position it relative to another. Each Container object has a layout manager associated with
it. A layout manager is an instance of any class that implements the LayoutManager
interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is
made, then the default layout manager is used. Whenever a container is resized (or sized for
the first time), the layout manager is used to position each of the components within it.
The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. If you wish to disable the
layout manager and position components manually, pass null for layoutObj. If you do this,
you will need to determine the shape and position of each component manually, using the
setBounds( ) method defined by Component. Normally, you will want to use a layout
manager.
Lab Assignments:
1. Write a program using layout Manager to add different controls on a frame.
2. Program to demonstrate different event handler.
3. Working with Graphics, colors and fonts in AWT.(Self-Practice Problem)
Ashish K Nayyar
/*
<applet code="BordLays2" width=400 height=400>
</applet>
*/
public class BordLays2 extends Applet
{
Button b1,b2,b3,b4;
TextField t1;
public void init()
{
b1=new Button("PAGE_START");
b2=new Button("LINE_START");
b3=new Button("CENTER");
b4=new Button("LINE_END");
t1=new TextField(20);
setLayout(new BorderLayout(10,10));
add(b1,BorderLayout.PAGE_START);
add(b2,BorderLayout.LINE_START);
add(b3,[Link]);
add(b4,BorderLayout.LINE_END);
add(t1,BorderLayout.PAGE_END);
}
}
c.
import [Link].*;
import [Link].*;
/*<applet code="Gridlayoutdemo" width=300 height=200>
</applet>
*/
Ashish K Nayyar
}
}
}
d.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="CardLayoutDemo" width=300 height=200>
</applet>
*/
public class CardLayoutDemo extends Applet implements
ActionListener,MouseListener
{
Checkbox Win98,winNT,solaris,mac;
Panel osCards;
CardLayout cardLO;
Button Win,Other;
public void init( )
{setBackground([Link]);
Ashish K Nayyar
Win=new Button("Windows");
Other=new Button("Other");
add(Win);
add(Other);
cardLO=new CardLayout( );
osCards=new Panel();
[Link](cardLO);
Win98=new Checkbox("Windows98",null,true);
winNT=new Checkbox("Windows NT/2000");
solaris=new Checkbox("Solaris");
mac=new Checkbox("Macos");
Panel winPan=new Panel();
[Link](Win98);
[Link](winNT);
Panel otherPan=new Panel();
[Link](solaris);
[Link](mac);
[Link](winPan,"Windows");
[Link](otherPan,"Other");
add(osCards);
[Link](this);
[Link](this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
[Link](osCards);
}
public void mouseEntered(MouseEvent me)
{
Ashish K Nayyar
}
public void mouseClicked(MouseEvent me)
{ }
public void mouseExited(MouseEvent me)
{ }
public void mouseReleased(MouseEvent me)
{ }
public void actionPerformed(ActionEvent ae)
{
if([Link]()==Win)
{
[Link](osCards,"Windows");
}
else
{
[Link](osCards,"Other");
}
}
}
2.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="CBG_Button" width=500 height=400>
</applet>
*/
public class CBG_Button extends Applet implements ItemListener,ActionListener
{ Button b1,b2;
Label l1,l2,l3,l4,l5;
TextField t1,t2,t3,t4;
Ashish K Nayyar
Checkbox cb1,cb2,cb3;
Image i1;
Font f;
String msg="";
CheckboxGroup cbg;
public void init()
{
f=new Font("verdana",[Link],14);setFont(f);
i1=getImage(getCodeBase(),"[Link]");//Download any such image
setBackground(newColor(255,192,203));setForeground(new
Color(75,0,130));
b1=new Button("Click to generate bill amount");
[Link](new Color(255,192,203));
b2=new Button("Clear");
[Link](new Color(255,192,203));
l1=new Label("Enter Item Name ");
l2=new Label("Enter price ");
l3=new Label("Enter quantity ");
l4=new Label("Bill Amount ");
l5=new Label("Select Discount ");
t1=new TextField(20);
t2=new TextField(20);
t3=new TextField(20);
t4=new TextField(20);
[Link]("JUICER");
[Link]("2000");
cbg=new CheckboxGroup();
cb1=new Checkbox("10%",cbg,false);
cb2=new Checkbox("20%",cbg,true);
cb3=new Checkbox("30%",cbg,false);
setLayout(null);
Ashish K Nayyar
[Link](10,30,130,30);[Link](160,30,100,30);
[Link](10,80,130,30);[Link](160,80,100,30);[Link](280,150,130,30);
[Link](10,130,130,30);[Link](160,130,100,30)[Link](280,180,50,10);c
[Link](340,180,50,10);[Link](400,180,50,10);
[Link](10,180,150,30);[Link](160,180,100,30);
[Link](40, 240,220,40);[Link](270,240,220,40);
add(b1);add(b2);add(l1);add(l2);add(l3);add(l4);add(l5);add(t1);add(t2);add(t3);add(t4);
add(cb1);add(cb2);add(cb3);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void actionPerformed(ActionEvent e)
{ double a=0,b=0,c=0;
b=[Link]([Link]());
c=[Link]([Link]());
if((b!=0)&&(c!=0))
a=b*c;
if([Link]()==b1)
{
if([Link]()==true)
{
a=a-(a*.10);
}
else if([Link]()==true)
Ashish K Nayyar
{
a=a-(a*.20);
}
else if([Link]()==true)
{
a=a-(a*.30);
}
[Link](""+a);
}
else if([Link]()==b2)
{[Link](" ");[Link](" ");[Link](" ");[Link](" ");}
}
public void paint(Graphics g)
{[Link]("R.R. Enterprises Pvt. Ltd",120,10);
[Link](i1,320,20,this);
}
}
Ashish K Nayyar
Lab No.17
Concept: Java Foundation Classes and Swings
Objective:
To teach them JFC and make them implement Swings
Pre Lab(Background):
Swing Components Are Lightweight
With very few exceptions, Swing components are lightweight. This means that they are
written entirely in Java and do not map directly to platform-specific peers. Because
lightweight components are rendered using graphics primitives, they can be transparent,
which enables nonrectangular shapes. Thus, lightweight components are more efficient and
more flexible. Furthermore, because lightweight components do not translate into native
peers, the look and feel of each component is determined by Swing, not by the underlying
operating system. This means that each component will work in a consistent manner across
all platforms.
Swing Supports a Pluggable Look and Feel
Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is
under the control of Swing. This fact means that it is possible to separate the look and feel
of a component from the logic of the component, and this is what Swing does. Separating
out the look and feel provides a significant advantage: it becomes possible to change the
way that a component is rendered without affecting any of its other aspects. In other words,
it is possible to “plug in” a new look and feel for any given component without creating any
side effects in the code that uses that component. Moreover, it becomes possible to define
entire sets of look-and-feels that represent different GUI styles. To use a specific style, its
look and feel is simply “plugged in.” Once this is done, all components are automatically
rendered using that style.
Lab Assignments:
1. Write a program to implement Swing 2 function calculator.
Ashish K Nayyar
2. Create a Swing login window to check user name and password using text fields and
command buttons(Self- Practice Problem)
3. Create a swing application with 3 control boxes for font name, size and style, change
font of the text according to user selection. (Self- Practice Problem)
Lab No.18
Concept: Java Database Connectivity
Objective:
To teach them various JDBC concepts with different databases
Pre Lab(Background):
The JDBC API defines the Java interfaces and classes that programmers use to connect to
databases and send queries. A JDBC driver implements these interfaces and classes for a
particular DBMS vendor.
A Java program that uses the JDBC API loads the specified driver for a particular DBMS
before it actually connects to a database. The JDBC DriverManager class then sends all JDBC
API calls to the loaded driver.
The four types of JDBC drivers are:
JDBC-ODBC bridge plus ODBC driver, also called Type 1.
Translates JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls
that are then passed to the ODBC driver. The ODBC binary code must be loaded on
every client computer that uses this type of driver.
Native-API, partly Java driver, also called Type 2.
Converts JDBC API calls into DBMS-specific client API calls. Like the bridge driver, this
type of driver requires that some binary code be loaded on each client computer.
JDBC-Net, pure Java driver, also called Type 3.
Sends JDBC API calls to a middle-tier net server that translates the calls into the
DBMS-specific network protocol. The translated calls are then sent to a particular
DBMS.
Native-protocol, pure Java driver, also called Type 4.
Lab Assignments:
1. Program in java to show the connectivity of java with the database using SQL
statement.
2. WAP to insert a record in database.
Ashish K Nayyar
[Link]("[Link]");
while([Link]())
{
[Link]([Link]("cid")+"-"+[Link]("cnum"));
}
[Link]();
}
catch(ClassNotFoundException e)
{[Link]("Driver or Database not found");}
catch(SQLException e)
{[Link]("Invalid SQL"+e);}
catch(Exception e)
{[Link]("General"+[Link]());}
}
}
2.
/* Inserting Data into the Table Employee created using Prepared Statement*/
import [Link].*;
class Mydb2 {
public static void main(String[] args)
{
try {
[Link]("[Link]");
Connection con = [Link]( "jdbc:odbc:employee");
PreparedStatement ps = [Link]("insert into employee
values(?,?,?,?)");
[Link](1,"atul");
[Link](2,"nayyar");
[Link](3,"18000");
[Link](4,"gwldelhi");
[Link]();
Ashish K Nayyar
[Link]();
}
catch(ClassNotFoundException e)
{[Link]("Driver or Database not found");}
catch(SQLException e)
{[Link]("Invalid SQL");}
catch(Exception e)
{[Link]("General"+[Link]());}
}
}
Ashish K Nayyar
Lab No.19
Concept: Java connectivity with different databases
Objective:
To teach them various JDBC concepts with different databases
Lab Assignments:
1. WAP to create a table in database via java.
2. WAP that updates some records.
catch(SQLException e)
{[Link]("Invalid SQL");}
catch(Exception e)
{[Link]("General"+[Link]());}
}
}
2.
/* Inserting Data into Employee Table using simple connection*/
/*Update command */
import [Link].*;
class Mydb4 {
public static void main(String[] args)
{
try {
[Link]("[Link]");
Connection con = [Link]( "jdbc:odbc:employee");
Statement st = [Link]();
[Link]("update employee set basic=basic+1");
[Link]();
}
catch(ClassNotFoundException e)
{[Link]("Driver or Database not found");}
catch(SQLException e)
{[Link]("Invalid SQL");}
catch(Exception e)
{[Link]("General"+[Link]());}
}
}
Ashish K Nayyar
Lab No.20
Concept: Simple Java Beans
Objective:
To teach them how to write simple java bean.
Pre Lab(Background):
A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of the properties, known as
getter and setter methods.
JavaBeans is a portable, platform-independent component model written in the Java
programming language.
JavaBeans is an object-oriented programming interface from Sun Microsystems that lets you
build re-useable applications or program building blocks called components that can be
deployed in a network on any major operating system platform.
Like Java applets, JavaBeans components (or "Beans") can be used to give World Wide Web
pages (or other applications) interactive capabilities such as computing interest rates or
varying page content based on user or browser characteristics.
Lab Assignments:
1. Write a program to create a simple bean.
file->new file
for category choose 'java'
for file type choose 'Java Class'
click 'next'
Enter an appropriate class name. I chose 'grbuttonx'.
Leave everything else untouched.
<manifest>
<attribute name="Main-Class" value="${[Link]}"/>
<attribute name="Class-Path" value="${[Link]}"/>
<attribute name="Java-Bean" value="true"/>
</manifest>