0% found this document useful (0 votes)
2 views124 pages

Java Programming Lab Guide for MCA Students

Uploaded by

Ashish Nayyar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views124 pages

Java Programming Lab Guide for MCA Students

Uploaded by

Ashish Nayyar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Ashish K Nayyar

Institute of Information Technology and Management


Affiliated to Guru Gobind Singh Indraprastha University, New Delhi.

Prepared by
Mr. Ashish Nayyar
Programme Director MCA
Ashish K Nayyar

MCA Semester-III

Paper ID Paper Paper L T/P Credit


Code
044251 MCA 251 Computer Graphics Lab 0 2 1
044253 MCA 253 Java Programming Lab 0 4 2
044255 MCA 255 C# Programming Lab. 0 4 2
Ashish K Nayyar

Special Note to Students

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

Special Note to Instructors

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

Subject Title: Java Programming Lab

Subject Code: MCA 253


S. Lab Objective Problem Statement No. of Lab
N Hours Outcome
o.
1 To teach how to 1. Write a program to print 2
write and execute Hello world
simple java 2. Write a program to
Programs. 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

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
2 To teach them 9. Write a program to insert 2
how to implement an array and print those
and use Arrays & elements using command
Strings in Java line arguments.
10. Write a program to
initialize and print the
elements of an array.
11. Write a program to
sort an array in ascending
and descending order.
12. WAP to perform linear
search on an Array of 5
integers.
13. WAP to perform binary
search on an Array of 5
integers.
14. WAP to display
smallest element of an
Array of 5 integers.
3 To teach them 15. WAP to display 2
how to implement difference between
and use Arrays & smallest and largest
Strings in Java elements of an Array of 5
integers.
16. Write a program to
perform following Matrix
operations using arrays.
a. Addition
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
b. multiplication
17. Write a program to
demonstrate the working
of any Ten String class
functions.
18. WAP to extract
surname from complete
name
19. Write a program to
create a class called
StringDemo and declare
three strings and use
functions like length,
charAt and equals on them.
4 To make students 20. Write a program to 2
learn how to create a class called Box
implement and calculate its volume by
Classes and calling its method.
Objects 21. Write a program to
create a class called Test
and pass its object to one
of its method to illustrate
usage of reference
variables.
22. Write a program to
create a class called Use
Static and declare some
static variables, a static
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
method that will print
those variables and static
block which will perform
some operation on that
variable.
5 To teach them the 23. Write a program to 2
purpose of create a class Add that will
Constructor add to numbers by using a
Function default constructor.
Concept of 24. Write a program to
function create a class called
overloading triangle with base and
height as the attributes and
calculate its area using
parameterized constructor.
25. Write a program to
create a class called
Rectangle and calculate its
area using this keyword.
26. Write a program to
create a class Area and
calculate area of rectangle
and circle using method
overloading.
6 To teach them 27. Write a program to 2
Inheritance in java create a class called Box
and Use of super, with instance variables
Abstract and final width, height and depth.
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
keyword Create another class
BoxWeight which inherits
class Box with an additional
instance variable weight.
Compute the volume of the
box using inheritance.
28. Implement the above
program using super
keyword.
29. Create a class Figure
and its 2 subclasses
Rectangle and Triangle and
calculate its area using
dynamic method dispatch.
30. Implement the above
program using abstract
classes by making Figure
class abstract.
31. -Write relevant
programs to show the
usage of final keyword with
class, variables and
methods in java.
7 To teach them the 32. Write relevant 2
benefits of programs showing the
Packages in java usage of package and
access protection in java.
33. Write relevant
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
programs to show the
concept of importing a
package
8 To make them 34. Write a program to 2
understand the implement stacks using
concept of interfaces.
interface 35. Write a program to
implementing nesting of
interface.
9 To teach them 36. Write relevant 2
how to deal with programs to show the
exceptions in Java usage of try, catch, throw,
throws and finally in java.
37. Write a program to
create user-defined
exception class using the
extends keyword.
38. WAP that throws
exception if age of voter is
less than 18.
39. WAP that throws
exceptions if stack is full or
is empty.
40. WAP that throws
exception if bank balance
drops below 1000 due to
any transaction.
10 To teach them 41. Write relevant 2
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
design, priorities programs to show the
and Synchronize concept of creating Thread
Multiple threads through thread class and
in java Runnable interface
42. WAP to print multiples
of 2,3,4 simultaneously.
11 To teach them 43. WAP to show that high 2
design, priorities priority thread gets more
and Synchronize CPU attention than a low
Multiple threads priority thread.
in java 44. Write relevant
programs to show the
concept of thread
synchronization and inter-
thread communication.
12 To teach them to 45. Program that accepts a 2
write Network host name and display its IP
based programs in address.
java 46. Write a TCP/IP client-
server program that echoes
whatever is typed on the
client to the server.
13 To make them 48. WAP to demonstrate 2
implement client server application
Remote Method using Java RMI.
Invocation
14 To teach them 49. Program that displays 2
how to write the life cycle of the Applet
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
Applets and use and other relevant
AWT controls. programs that shows the
implementation of Applets
in java.
50. Write Programs to
draw different figures using
AWT.
51. Write programs to add
label, Buttons, Textfield, list
etc using AWT.
15 To teach them 52. Create a login window 2
how to write to check user name and
Applets and use password using text fields
AWT controls. and command buttons
53. Create 3 control boxes
for font name, size and
style, change font of the
text according to user
selection.
16 To teach them 54. Write a program using 2
various layout layout Manager to add
managers different controls on a
frame.
55. Program to
demonstrate different
event handler.
56. Working with Graphics,
colours and fonts in AWT.
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
17 To teach them JFC 57. Write a program to 2
and make them implement Swing 2
implement Swings function calculator.
58. Create a Swing login
window to check user
name and password using
text fields and command
buttons
59. Create a swing
application with 3 control
boxes for font name, size
and style, change font of
the text according to user
selection.

18 To teach them 60. Program in java to 2


various JDBC show the connectivity of
concepts with java with the database
different using SQL statement.
databases 61. WAP to insert a record
in database.
19 To teach them 62. WAP to create a table 2
various JDBC in database via java.
concepts with 63. WAP that updates
different some records.
databases
20 To teach them 64. Write a program to 2
how to write create a simple bean.
Ashish K Nayyar

S. Lab Objective Problem Statement No. of Lab


N Hours Outcome
o.
simple java beans.
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 {

/* This is my first java program.


* This will print 'Hello World' as the output
Ashish K Nayyar

*/

public static void main(String []args) {


[Link]("Hello World"); // prints Hello World
}
}
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Example class MyFirstJavaClass
 Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Example public void myMethodName()
 Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class
name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as '[Link]'
 public static void main(String args[]) - Java program processing starts from the
main() method which is a mandatory part of every Java program..
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
Ashish K Nayyar

 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

[Link]("The result is :- "+result);


}
else
{
[Link]("Invalid Choice!!!");
}
}
}
5.
import [Link].*;
class GradeStu
{
public static void main(String args[]) throws IOException
{
float per;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
per=0.0F;
[Link]("Enter percentage :- ");
per=[Link]([Link]());
if(per>=0&&per<=100)
{
if(per>90)
[Link]("Grade is A");
else if(per>75)
[Link]("Grade is B");
else if(per>60)
[Link]("Grade is C");
else if(per>=50)
[Link]("Grade is D");
else
[Link]("FAIL");
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

Random r1=new Random();


num=1+[Link](100);
[Link]("The randomly generated no. is :- "+num);
for(i=2;i<num;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
if(flag==1&&num!=1)
[Link]("Its a prime no. ");
else
[Link]("Its not a prime no. ");
}
}
8.
import [Link];
class RandArm
{
public static void main(String a[])
{
int flag=1,i,num,rem,sum=0,num1=0;
Random r1=new Random();
num=1+[Link](500);
num1=num;
[Link]("The randomly generated no. is :- "+num);
while(num>0)
{
rem=num%10;
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

String greeting = "Hello world!";


Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has eleven constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.

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

[Link]("Enter element no."+(i+1)+" :- ");


a[i]=[Link]([Link]());
}
for(i=0;i<[Link];i++)
{
for(j=0;j<[Link];j++)
{
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]("Enter element to be searched :- ");
n=[Link]([Link]());
lb=0;
ub=4;
mid=(lb+ub)/2;
while(lb<=ub)
{
if(a[mid]==n)
{
[Link]("Element found at position :- "+(mid+1));
flag=1;
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

public static void main(String args[]) throws IOException


{
int a[]=new int[5];
int i,small,large;
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];
large=a[0];
for(i=1;i<[Link];i++)
{
if(small>a[i])
{
small=a[i];
}
}
for(i=1;i<[Link];i++)
{
if(large<a[i])
{
large=a[i];
}
}
[Link]("The smallest element is :- "+small);
[Link]("The largest element is :- "+large);
[Link]("The difference is :- "+(large-small));
}
}
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));

[Link]("The string is :- " + s1);


[Link]("The second string is :- " + s2);
[Link]("The existence of Garg in string1 is :- " + [Link]("Garg"));
[Link]("The letter a from starting is at index in string 1 :- "
+[Link]("a"));
[Link]("The letter a fron ending is at index in string 1 :- "
+[Link]("a"));
[Link]("The substring from index 11 in string 1 :- " + [Link](11));
Ashish K Nayyar

[Link]("The length of string1 is :- " + [Link]());


if ([Link](s2) == 0)
{
[Link]("First and second string are equal");
}
else
{
[Link]("First and second string are not equal");
}
[Link]("First and second string are equal"+[Link](s2));
[Link]("The concatenation of strings is :- ");
[Link]([Link](s2));
[Link]("The existence of arg in end in string1 is :- "+[Link]("arg"));
[Link]("The existence of My in starting in string1 is :- " +
[Link]("My"));
copy=[Link]();
for(i=0;i<[Link];i++)
{
[Link](copy[i]);
}
}
}
4.
import [Link].*;
class FindSurname
{
public static void main(String args[]) throws IOException
{
String name;
int i=0,index;
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
Ashish K Nayyar

[Link]("Enter name :- ");


name=[Link]();
index=[Link](" ");
index++;
[Link]("The surname is :- " + [Link](index));
}
}
5.
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' };
[Link]("The char at 1 :- " + [Link](1));
[Link]("The string is :- " + s1);
[Link]("The second string is :- " + s2);
[Link]("The length of string1 is :- " + [Link]());
[Link]("First and second string are equal"+[Link](s2));
}
}
Ashish K Nayyar

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

void readData() throws IOException


{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter length :- ");
l=[Link]([Link]());
[Link]("Enter width :- ");
w=[Link]([Link]());
[Link]("Enter height :- ");
h=[Link]([Link]());
}
int calcVol()
{
int vol;
vol=l*w*h;
return vol;
}
}
class BoxDemo
{
public static void main(String args[]) throws IOException
{
int vol;
Box b1=new Box();
[Link]();
vol=[Link]();
[Link]("The volume is :- "+vol);
}
}
2.
class Test
{
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

static int a=10,b=20;


static void func()
{
[Link]("A= "+a+" B= "+b);
}
static
{
a=a+5;
b=b/2;
}
}
class StatDemo
{
public static void main(String args[])
{
[Link]();
}
}
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;
}

class BoxWeight extends Box1


{
int weight;
int volume;
BoxWeight()
{
height=0;
width=0;
depth=0;
weight=0;
}
BoxWeight(int x,int y,int z,int n)
{
height=x;
width=y;
depth=z;
weight=n;
}
void calcVolume()
Ashish K Nayyar

{
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

class B implements [Link] {


public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
[Link] nif = new B();
if([Link](10))
[Link]("10 is not negative");
if([Link](-12))
[Link]("this won't be displayed");
}
}
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

class NewThread_MO2 implements Runnable{


String name;
Thread t;
NewThread_MO2(String threadName)
{
//create a new second thread
name=threadName;
t=new Thread(this,name);
[Link]("New Thread :"+t);
[Link]();
}
public void run(){
Ashish K Nayyar

try{
for(int i=1;i<=10;i++)
{
[Link](name +" : "+(i*2));
[Link](100);
}
}
catch(InterruptedException e)
{
[Link](name +" Interrupted");
}
[Link](name +" Exiting");

}//run ends here


}
class NewThread_MO3 implements Runnable{
String name;
Thread t;
NewThread_MO3(String threadName)
{
//create a new second thread
name=threadName;
t=new Thread(this,name);
[Link]("New Thread :"+t);
[Link]();
}
public void run(){
try{
for(int i=1;i<=10;i++)
{
[Link](name +" : "+(i*3));
Ashish K Nayyar

[Link](100);
}
}
catch(InterruptedException e)
{
[Link](name +" Interrupted");
}
[Link](name +" Exiting");

}//run ends here


}
class MultiThreadDemoMO23 {
public static void main(String[] args)
{
new NewThread_MO2("Multiples of two");
new NewThread_MO3("Multiples of three");
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]("Main Thread Interrupted");
}
[Link]("Main Thread Exiting ");
}//main ends here
}//class ends here
Ashish K Nayyar

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.

Pre Lab (Background): Refer Lab No.10


Lab Assignments:
1. WAP to show that high priority thread gets more CPU attention than a low priority
thread.
2. Write relevant programs to show the concept of thread synchronization and inter-
thread communication.
Solutions to Lab No 11.
1.
// Demonstrate thread priorities.
class clicker implements Runnable
{
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p)
{
t = new Thread(this);
[Link](p);
}
public void run()
{
while (running)
Ashish K Nayyar

{
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

[Link]("This textll is comming from server");


// Close the connection, but not the server socket
[Link]();
[Link]();
[Link]();
}
}
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

3. It writes and transmits (marshals) the result to the caller.

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;

int sub(int a,int b) throws RemoteException;


}
import [Link].*;
import [Link].*;
public class myimp extends UnicastRemoteObject implements myintf
{
myimp() throws RemoteException
{}

public int add(int a,int b)throws RemoteException


{return(a+b);}

public int sub(int a,int b)throws RemoteException


{return(a-b);}

}
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

[Link](190, 10, 60, 50, 15, 15);


[Link](70, 90, 140, 100, 30, 40);
[Link](0, 0, 100, 100);
[Link](0, 100, 100, 0);
[Link](40, 25, 250, 180);
[Link](75, 90, 400, 400);
[Link](20, 150, 400, 40);
[Link](5, 290, 80, 19);
}
}

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

b1=new Button(" Click to check");


t1=new TextField(20);
l1=new Label("Enter a number");
l2=new Label("Even-Odd Checker");
setLayout(null);
[Link](new Color(255,192,203));
[Link](60,15,160,30);
[Link](10,60,130,30);
[Link](160,60,100,30);
[Link](75,110,130,40);
add(l1);
add(l2);
add(t1);
add(b1);
[Link](this);
}
public void paint(Graphics g)
{
if(f)
[Link](msg,15,180);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
if([Link]([Link]())%2==0)
{
msg="Number is even";
}
else
{
Ashish K Nayyar

msg="Number is Odd";
}
f=true;
repaint();
}
}

public void stop()


{
f=false;
}
}
Ashish K Nayyar

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);

l1=new Label("Enter user name");


l2=new Label("Enter Password");
setLayout(null);
Ashish K Nayyar

[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

Solutions to Lab No 16.


1.
a.
import [Link].*;
import [Link].*;
/*
<applet code="BordLays" width=400 height=400>
</applet>
*/
public class BordLays extends Applet
{
Button b1,b2,b3,b4;
TextField t1;
public void init()
{
b1=new Button("East");
b2=new Button("West");
b3=new Button("South");
b4=new Button("North");
t1=new TextField(20);
setLayout(new BorderLayout());
add(b1,[Link]);
add(b2,[Link]);
add(b3,[Link]);
add(b4,[Link]);
add(t1,[Link]);
}
}
b.
import [Link].*;
import [Link].*;
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

public class Gridlayoutdemo extends Applet


{
static final int n=4;
public void init()
{
setLayout(new GridLayout(n,n));
setFont(new Font("SansSerif",[Link],24));
for(int i=1;i<=16;i++)
{
add(new Button(" "+i));

}
}
}
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)

Solutions to Lab No 17.


1.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="[Link]" height=300 width=400>
</applet>
*/
public class Calculator extends JApplet implements ActionListener
{
JTextField t1,t2,t3,t4;
JLabel l1,l2,l3,l4;
JButton b1,b2;
public void init()
{
Container cn=getContentPane();
[Link](new FlowLayout());
[Link]([Link]);
[Link]([Link]);
[Link](null);
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
t4=new JTextField(20);
Ashish K Nayyar

l1=new JLabel("Enter First Number :");


l2=new JLabel("Enter Second Number :");
l3=new JLabel("Enter Third Number :");
l4=new JLabel("Largest Number is:");
b1=new JButton("+");
b2= new JButton("-");
[Link](20,20,160,30);
[Link](190,20,160,30);
[Link](20,60,160,30);
[Link](190,60,160,30);
[Link](20,100,160,30);
[Link](190,100,160,30);
[Link](20,140,160,30);
[Link](190,140,160,30);
[Link](20,180,150,30);
[Link](180,180,100,30);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](t4);
[Link](l1);
[Link](l2);
[Link](l3);
[Link](l4);
[Link](b1);
[Link](b2);
[Link](this);
[Link](this);
}
Ashish K Nayyar

public void actionPerformed(ActionEvent e)


{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
if([Link]()==b1)
{
[Link](" "+(a+b));
}
else if([Link]()==b2)
{ [Link](" "+(a-b));
}
}
}
3.
Ashish K Nayyar

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

Solutions to Lab No 18.


[Link] [Link].*;
class Mydb_SQLSERVER {
public static void main(String[] args)
{
try {

[Link]("[Link]");

Connection con = [Link](


"jdbc:sqlserver://localhost:1433;databaseName=Customer","sa","12345");

PreparedStatement ps = [Link]("select * from Customer");


/*To execute the command we need to copy folder conatining [Link] on c
drive ;also [Link] class library requires a Java Runtime Environment (JRE) of version
6.0 or 7.0. Using [Link] on JRE 5.0 will throw an exception;and then execute dos
command to set classpath as
c:\program files\java\jdk1.7.0_51\bin>set classpath=.;C:\Microsoft SQL Server JDBC Driver
3.0\sqljdbc_3.0\enu\[Link]
and then
You need to Go to Start > Microsoft SQL Server > Configuration Tools > SQL Server
Configuration Manager When it opens Go to SQL Server Configuration Manager > SQL
Server Network Configuration > Protocols for SQLExpress Where you'll find the Protocol
TCP/IP, if disabled then Enable it Click on TCP/IP, You'll find its properties. In this properties
Remove All the TCP Dynamic Ports(only TCP Dynamic Ports) and Add value of 1433 to all TCP
Port and restart your SQL Server Services > SQL Server */
ResultSet rs=[Link]();
[Link]("The output of Customer Table :");
[Link](" cid "+"-"+"cnum");
Ashish K Nayyar

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

Pre Lab(Background):Refer Lab No 18.

Lab Assignments:
1. WAP to create a table in database via java.
2. WAP that updates some records.

Solutions to Lab No 19.


1.
/* Program to Create a table and insert data into it using simple connection */
import [Link].*;
class Mydb5 {
public static void main(String[] args)
{
try {
[Link]("[Link]");
Connection con = [Link]( "jdbc:odbc:employee");
Statement st = [Link]();
//[Link]("CREATE TABLE EMP2"+"(EMPNO NUMBER PRIMARY
KEY,"+"ENAME VARCHAR(20) NOT NULL,"+"SAL NUMBER,"+"COMM NUMBER)");
[Link]("insert into emp2 values(100,'ashish',50000,2000)");
[Link]();
}
catch(ClassNotFoundException e)
{[Link]("Driver or Database not found");}
Ashish K Nayyar

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.

Solutions to Lab No 20.

Step 1 - Create a library


From a fresh opening of netbeans, do:
file->new project
for category choose 'java'
for project choose 'java class library'
Then choose an appropriate location and name for your library. I chose grlib1 for the name.

Step 2 - Create an empty class


Ashish K Nayyar

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.

Step 3 - Make code changes


 All beans must contain a constructor with no parameters. My constructor initializes my only
property/member variable (img).
 All beans must contain 'implements Serializable'. You don't need to override any of these
functions but you have to have that in your class definition. Serializable lets the IDE save
your property values during design time.
 Any properties of your bean must have get and set functions if you want to have them show
up in property lists. I only have one property and it is write only so I created a function called
'setImage()'.
 Beans apparently need to meet security considerations and so probably won't let you do
certain things like access local files.
I wanted a button with a cool image so I inherited from JButton. This gave me all kinds of properties
and it already serializes everything I care about (don't care about the image as this is loaded in
runtime). This is very basic implementation - there is no focus image, no down image, no roll over
image. Here's my code:
package grlib1;
import [Link];
import [Link].*;
import [Link];
/**
* @author gr@[Link]
*/
public class grbuttonx extends JButton implements Serializable {
private Image img;
public grbuttonx() {
img=null;
}
Ashish K Nayyar

public void setImage(Image i) {


img=i;
}

public void paint(Graphics g) {


if (img != null)
[Link](img, 0, 0,null);
else {
[Link]([Link]);
Dimension size = getSize();
[Link](0, 0, [Link], [Link]);
}
}
}

Step 4 - Fix manifest to show this is a bean library


First get to the files tab of your project (ctrl/2 should get you there). In the top level of the tree view
it shows your projects. The next level down should have a file called [Link]. Click the plus sign
next to it. Then double click any element below [Link]. You should be now editing a file called
[Link].
Search for "<manifest" (I include the open < to simplify the search). There should only be
one such tag in the file and you should be in the jar building section (scroll up to see the
next comment block if you want to double check).
There should already be 2 attributes in the manifest. Add one called Java-Bean as shown:

<manifest>
<attribute name="Main-Class" value="${[Link]}"/>
<attribute name="Class-Path" value="${[Link]}"/>
<attribute name="Java-Bean" value="true"/>
</manifest>

Click on Clean and build icon


Ashish K Nayyar

Step 5 - test it!


Create a new project or open an existing project. Open a frame or a form or something that allows
you to drop buttons onto it. Get into design mode so you can see the palette window (if you can't
see it you can open the palette window and you might want to pin it open with the pin in the title
bar).
In menu system do: tools -> palette -> Swing/AWT Components ->Add From Project->choose
your library project created in step 1. Click next.
Your component should show up. Click it and click 'next' again.
Select a folder to put your bean into - I always choose "Beans". Click 'finish'.
Now you should see your been in the pallette near the bottom in the Beans section. Open
up the beans section if it isn't already. Click your bean and then click in your window to
place it. That's it.

You might also like