Java Lab Manual
Java Lab Manual
There are 72 systems (HCL) installed in this Lab. Their configurations are as follows:
Processor : INTEL PENTIUM DUAL CPU 2.0 [Link].
RAM : 2 GB (DDR2)
Hard Disk : 160 GB
Monitor : HCL 17” LCD Monitor
Mouse : USB Optical Mouse.
Key Board : HCL Multimedia Key Board
1 Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.
2 Students are required to carry their observation / programs book with completed
exercises while entering the lab.
3 Students are supposed to occupy the machines allotted to them and are not supposed
to talk or make noise in the lab. The allocation is put up on the lab notice board.
4 Lab can be used in free time / lunch hours by the students who need to use the
systems should take prior permission from the lab in-charge.
6 Students are not supposed to use floppy disks, pen drives and CDs.
7 All the students must wear ID cards, leave their foot wear out side the lab and must
come with a formal dress code.
8 You should come prepared for you lab session to properly utilize the maximum
time of Lab session.
9 You should attempt all lab exercises/assignments given in the list (session wise)
10 You may seek assistance in doing the lab exercises from the available lab
Instructor.
Handle Strings
Java has quickly emerged as one of the most popular languages of the late 1990’s. It
has transitioned from a special-purpose language used in Internet applications to a general
purpose one used in many cases where C, C++ were once used.
This laboratory manual will teach the student the basics of Java, both as a general-
purpose language as well as the Internet language. The most important part of learning any
computer language is to use it. This manual forces the reader to do just that. If the reader is
not able or willing to implement the laboratory sessions, then he/she should look for an
alternative learning instrument.
Java is so popular because its ability to run on any hardware platform. Other high-
level languages that have become standardized (C, C++, Lisp, Fortran and several others) do
in fact have standard source code that, when compiled with a compiler specially designed for
a particular hardware platform and operating system, it will run on that platform. When the
program is to be ported to another platform, the source code must be re-compiled with a
compiler for the new platform. While this avoids having to rewrite the program in a different
way if the language were not standard, in practice, however, a long and complex program
written in one standard language will require some modifications when compiled for another
platform and/or operating system. But object code compiled under one compiler will not run
on a platform for which that compiler was not designed. This is because the microprocessors
and/or the operating system are designed such that they do not operate exactly the same way.
Java object code will run on (almost) any microprocessor. This is important from the
standpoint of the Internet, where one does not always know the type of computer platform
and operating system on which an application will be asked to run. Java originated from an
effort in the early 1990’s at Sun Microsystems to write a language that could be run on all
home appliances, such as microwave ovens, VCR’s, etc. This is actually a difficult task, as
the microprocessors found on such devices are inexpensive and of many variations. Thus, it
had to be compatible with many processors. A few years later, it was determined that the
approach taken by the developers of Java would be more useful in an Internet environment.
The rest is history.
Java embodies portability by “compiling” the source code, not to machine language,
but to byte code. Byte code is an intermediate level representation that represents the way in
which most microprocessors do things. Such a representation is called the Java Virtual
Machine, and is similar to most common microprocessors. Each family of microprocessor
(Intel, Motorola, etc.) has a specific way in which they do things – their instructions, memory
organization, registers, etc. However, as a whole, they do things much more similarly than
they do differently. Java takes advantage of this fact. The byte code is actually representative
of most microprocessors – not exactly any one of them, but very similar to all of the most
common ones. Thus, only one Java compiler is necessary, as its output will be the same (byte
code) regardless of on which machine the Java code will be executed. But, of course, byte
code will not by itself run on any microprocessor. It requires an additional step – the
interpretation step. As the byte code is executed, an interpreter will interpret every
instruction and convert it into the actual machine representation for that platform. The
advantage is that while compilers are highly complex and expensive systems, byte code
interpreters are much easier to write and maintain, since most of the work is already done by
the Java compiler. If every computing platform has its own Java byte code interpreter, then
Java object code can be run seamlessly. The drawback is that being an essentially interpreted
language, Java can be slower than the fully compiled and optimized C and C++ programs.
Other traditionally interpreted languages such as Basic and Lisp lost popularity when
commercial applications were being developed partially due to their interpreted nature
resulting in slow execution. However, the Java interpretation is faster than that of those older
languages because the line of source code is not being interpreted, but rather, an intermediate,
and rather low level implementation.
The Java syntax is suspiciously similar to C and C++. In fact, Java is easy to
understand if you already know those languages. However, there are several significant
differences:
• Java is completely object-oriented. C++, although it allows (and encourages!) the use of
classes, does not require the programmer to do so. Java does.
• Java does not allow pointers. While this greatly reduces the power of the programmer to
dwell at the memory levels, it does provide a level of safety and a program structure that is
better in the end. Students everywhere cheer this aspect of Java after they learn C/C++.
There exist two types of Java programs: applications and applets. Applications are
standalone programs such as would be written in C and C++. This is where the general
purpose aspect of Java comes in. Programs that were previously written in C and C++ can
now be written wholly in Java, notwithstanding the accompanying reduction in execution
speed.
Applets are similar to applications, but they don't run standalone. Instead, applets
adhere to a set of conventions that lets them run within a Java-compatible browser (for
example, Netscape or Internet Explorer). This is the special purpose nature of Java (for which
it was intended originally).
Simple :
Portable :
Java programs can execute in any environment for which there is a Java run-time
system.(JVM)
Java programs can be run on any platform (Linux,Window,Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
Java programming is object-oriented programming language.
Like C++ java provides most of the object oriented features.
Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :
Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded :
Java provides integrated support for multithreaded programming.
Architecture-neutral :
Interpreted :
High performance :
Distributed :
Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time.
APPLICATIONS :
Computer applications
Writing embedded software/firmware for various electronics Industries
Communications products which use micro-controllers
Developing verification software, test code, simulators etc.
Hardware products.
Research
System designing
Networking
Database connectivity
Mobile Applications
SETTING PATH AND CLASSPATH:
To run java programs you need JDK (Java Development Kit) installed on your
machine. Latest version of JDK you can download from [Link] for free. It is
suggested, set PATH and CLASSPATH properly before you try to compile and run your java
programs. Because of the problem related to the path settings on your PC, your program may
not compile and run.
PATH Setting
It does not compile your TestProg program; but instead it spits out some strange message
about a "Bad Command", This message does not mean that your machine is broken or that
you didn't install JDK correctly. The machine says "Bad command" because it doesn't know
what the commands javac or java mean! You need to tell DOS that these commands live in
the Java’s JDK directory and that whenever it doesn't recognize a command like javac that it
should also check the Java’s JDK directory for a possible interpretation of this command.
This problem can be solved in two ways on by using DOS prompt , and another by using
My Computer on your window screen.
PATH=C:WINNT\...;C:\ProgramFiles\.....
where the dots represent all kinds of directory names. This is a list of all the places DOS
looks when it's trying to find out what a particular command means. If your JDK directory is
not on this list, your DOS won't understand the JDK’s commands. So you need to add it to
the list. You can do this by typing
set path=c:\jdkwhateverItIs\bin;%path%
It is in the version of JDK . This adds your JDKdirectory to the rest of the existing path. If
you have put your JDK directory somewhere else, alter the directory name in the command
above appropriately to match the actual location. If there is any spaces in the command above
(except between set and path) path will not be set properly.
Because this is the file that has all the important settings for making your PC run the way you
want it. One of the settings it makes is the PATH. Now edit the [Link] file and find
the line that sets the path. Add your version of the "set path=C:/jdk.2...." command (the one
you used earlier) after the line that sets the rest of the path in the [Link] file. Now save
the file. Then the next time you open a DOS window (it maybe be required to restart your
machine ), the PATH should be set correctly. If you made an error in editing [Link],
things might not work quite right now . In this case, just copy your back up version of
[Link] back into [Link] and try the whole process again.
CLASSPATH Setting
If you find some message during compilation or execution of Java program that a class is not
found .You know where the class file is ? May be in your current working directory. To tell
the path of class files you need to set your CLASSPATH.
At the DOS prompt, type classpath and DOS will respond with
CLASSPATH=C:stuff.....
Now type
set classpath=.;%classpath%
Don’t leave any spaces except after the word set. This should add the current directory (the
directory having your class files ) to your classpath. Then java should know to look in the
current directory for the *.class files that your javac compiles are creating.
In XP/2000/ME machines PATH and CLASSPATH can be set using "My Computer.”
The process is given as follows:
Now you can compile and run your applications and applets without any problem of PATH
and [Link] and CLASSPATH setting need to be done only in the case of, if
you are willing to run programs on DOS prompt. If you write Java programs in some specific
editors like EditPlus, JBbuilderfor etc. then these seting discussed above are editor
dependent.
LIST OF LAB EXPERIMENTS
A Java Program that prompts the user for an integer and then
2 prints out all the prime numbers upto that Integer.
1) The Fibonacci sequence is defined by the following rule. The first 2 values in the
sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it.
Write a Java Program that uses both recursive and non recursive functions to print
the nth value of the Fibonacci sequence.
[Link]("Fibonacci Series:");
for (int i = 0; i < n; i++) {
[Link](fibonacci(i) + " ");
}
[Link]();
}
}
D:\vara>java FibonacciSeriesRecursive
Enter number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
int a = 0, b = 1;
[Link]("Fibonacci Series:");
int c = a + b;
a = b;
b = c;
}
[Link]();
}
}
Output:
D:\vara>javac [Link]
D:\vara>java FibonacciIterative
Enter number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
[Link]();
}
}
Output:
D:\vara>javac [Link]
D:\vara>java PrimeNumbers
Enter an integer: 7
Prime numbers up to 7 are:
2357
PROGRAM:
import [Link].*;
public class Palan
{
public static void main(String a[])
{
[Link]("Enter any string");
String s=new Scanner([Link]).next();
for(int i=0,j=[Link]()-1;i<=j;i++,j--)
{
if([Link](i)==[Link](j));
else
{
[Link]("Not Palindrome");
[Link](1);
}
}
[Link]("Palindrome");
}
}
OUTPUT:
D:\>javac [Link]
D:\>java Palan
Enter any string
MALAYALAM
Palindrome
D:\>java Palan
Enter any string
MADAM
Palindrome
D:\>java Palan
Enter any string
MCA
Not Palindrome
D:\>
AIM : To write a Java Program for sorting a given list of names in ascending
order.
PROGRAM:
import [Link].*;
class Sortst
{
public static void main(String a[])
{
[Link]("How many string u want to enter");
Scanner sc=new Scanner([Link]);
int n=[Link]();
String st[]=new String[n+1];
for(int i=0;i<n;i++)
{
[Link]("Enter string "+(i+1));
st[i]=[Link]();
}
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(st[i].compareTo(st[j])>0)
{
String t=st[i];
st[i]=st[j];
st[j]=t;
}
}
}
[Link]("Strings in order are :\n\n");
for(int i=0;i<n;i++)
[Link](st[i]);
}
}
PROGRAM:
import [Link];
import [Link].*;
import [Link].*;
class MatrixMul
{
public static void main(String[] args) {
int i= 0,j=0,k=0,p,q,m,n;
int a[][] = new int[10][10];
int b[][] = new int[10][10],c[][] = new int[10][10];
Scanner sc = new Scanner([Link]);
[Link]("Enter a matrix row value : ");
p=[Link]();
q=[Link]();
m = [Link]();
n = [Link]();
if(q==m)
{
[Link]("Enter matrxi A values :");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
a[i][j] = [Link]() ;
}
}
Oops Using JAVA Lab Manual Page 7
[Link]("\nMatrix A values ");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
[Link](" "+a[i][j]) ;
}
[Link]();
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j] = [Link]() ;
}
}
[Link]("\nMatrix B values ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
[Link](" "+b[i][j]) ;
}
[Link]();
}
[Link]("\n C Matrix is C = A * B Result");
if(q == m)
{
for(i=0;i<p;i++)
{
for(j=0;j<n;j++)
{
c[i][j]= 0 ;
for(k=0;k<q;k++)
{
c[i][j] = c[i][j] + (a[i][k] * b[k][j]) ;
}
}
for(i=0;i<p;i++)
{
for(j=0;j<n;j++)
{
[Link](" "+c[i][j]) ;
}
[Link]();
}
}else
{
[Link]("Matrix multiplication not possible");
}
}
}
OUTPUT:
D:\>javac [Link]
D:\>java MatrixMul
Enter a matrix row value : 3
Enter a matrix column value :3
Enter b matrix row value : 3
Enter b matrix columnvalue :3
Enter matrxi A values :
1
2
3
4
5
6
7
8
9
Matrix A values
123
456
789
7
8
9
Matrix B values
123
456
789
C Matrix is C = A * B Result
30 36 42
66 81 96
102 126 150
D:\>
i. Method Overloading:
PROGRAM:
class OverloadDemo {
void test() {
[Link]("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
[Link]("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
[Link]("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
[Link]();
[Link](10);
[Link](10, 20);
result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);
}
}
OUTPUT:
D:\>javac [Link]
D:\>java ConsOverload
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
D:\>
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
OUTPUT:
D:\>javac [Link]
D:\>java Override
k: 3
D:\>
PROCEDURE:
PROGRAM:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
AIM: To write a Java Program that using String Tokenizer class, which reads a
line of integers and then displays each integer and the sum of all integers.
PROGRAM:
import [Link].*;
public class Token
{
public static void main(String args[])
{
String s=new String("welcome to java");
StringTokenizer st=new StringTokenizer(s);
int n=[Link]();
[Link]("No of tokents = "+ n);
[Link]("Tokens are as follows");
[Link]("------------------------");
while([Link]())
{
[Link]([Link]());
}
}
}
OUTPUT:
D:\>javac [Link]
D:\>java Token
No of tokents = 3
Tokens are as follows
------------------------
welcome
to
java
D:\>
PROGRAM:
import [Link].*;
import [Link].*;
class Fileattr
{
public static void main(String args[])
{
File f1=new File(args[0]);
[Link]([Link]()?"file exists":"does not exist");
[Link]("Filename:"+[Link]());
[Link]("Filepath:"+[Link]());
[Link]([Link]()?"is a directory":"is a simple file");
[Link]([Link]()?"can be read":"can not be read");
[Link]([Link]()?"can be write":"can not be write");
[Link]("length of file in bytes:"+[Link]());
}
}
OUTPUT:
D:\>javac [Link]
i. Without Commandline Argument
D:\>java Fileattr
Exception in thread "main" [Link]: 0
at [Link]([Link])
ii. With Commandline Argument
D:\>java Fileattr [Link]
file exists
Filename:[Link]
Filepath:D:\\[Link]
is a simple file
can be read
can be write
length of file in bytes:444
AIM: To write a Java Program that displays the number of characters, lines and
words in a text/text file.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;
public class ClwinText
{
private static void linecount(String fName, BufferedReader in) throws
IOException
{
long numChar = 0;
long numLine=0;
long numWords = 0;
String line;
do{
line = [Link]();
if (line != null)
{
numChar += [Link]();
numWords += wordcount(line);
numLine++;
}
}while(line != null);
[Link]("File Name: " + fName);
[Link]("Number of characters: " + numChar);
[Link]("Number of words: " + numWords);
[Link]("Number of Lines: " + numLine);
}
private static void linecount(String fileName)
{
BufferedReader in = null;
try
{
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
linecount(fileName,in);
}
int index = 0;
boolean prevWhiteSpace = true;
while(index < [Link]())
{
char c = [Link](index++);
boolean currWhiteSpace = [Link](c);
if(prevWhiteSpace && !currWhiteSpace)
{
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
public static void main(String[] args)
{
long numChar = 0;
long numLine=0;
String line;
try
{
if ([Link] == 0)
{
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]));
line = [Link]();
numChar = [Link]();
if (numChar != 0)
{
numLine=1;
}
[Link]("Number of characters: " + numChar);
OUTPUT:
D:\>javac [Link]
D:\>java ClwinText
[Link]
Number of characters: 10
Number of words: 1
Number of lines: 1
D:\>java ClwinText
This is test line
Number of characters: 17
Number of words: 4
Number of lines: 1
D:\>
AIM: To write a Java Program that works as a simple calculator. Use a grid
layout to arrange buttons for the digits and for the +-*?% operations. Add a text
field to display the result.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;
JTextField tf;
String num1 = "", num2 = "", operator = "";
SimpleCalculator() {
tf = new JTextField();
[Link](false);
[Link](new Font("Arial", [Link], 20));
setLayout(new BorderLayout());
add(tf, [Link]);
String buttons[] = {
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0","%","=","+",
"C","","",""
};
add(panel, [Link]);
setTitle("Simple Calculator");
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
if ([Link]("[0-9]")) {
[Link]([Link]() + cmd);
}
else if ([Link]("[+\\-*/%]")) {
num1 = [Link]();
operator = cmd;
[Link]("");
}
else if ([Link]("=")) {
num2 = [Link]();
double n1 = [Link](num1);
double n2 = [Link](num2);
double result = 0;
switch (operator) {
case "+": result = n1 + n2; break;
case "-": result = n1 - n2; break;
case "*": result = n1 * n2; break;
case "/": result = n1 / n2; break;
case "%": result = n1 % n2; break;
[Link]([Link](result));
}
else if ([Link]("C")) {
[Link]("");
num1 = num2 = operator = "";
}
}
Output:
D:\vara>javac [Link]
D:\vara>java SimpleCalculator
PROGRAM:
import [Link].*;
import [Link].*;
MouseEventDemo() {
addMouseListener(this);
setSize(400, 300);
setTitle("Mouse Event Handling");
setVisible(true);
}
Output:
D:\vara>javac [Link]
D:\vara>java MouseEventDemo
PROGRAM:
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
[Link]("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
[Link]("hello");
}
}
catch(Exception e)
{}
}
}
}
}
catch(Exception e)
{}
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
[Link]();
[Link]();
[Link]();
}
}
AIM: To write a Java Program to create an abstract class named shape, that
contains an empty method named numberOfSides(). Provide three classes named
Trapezoid, Triangle and Hexagon, such that each one of the classes contains only
the method numberOfSides(), that contains the number of sides in the given
geometrical figure.
PROGRAM:
// Abstract class
abstract class Shape {
abstract void numberOfSides();
}
// Triangle class
class Triangle extends Shape {
void numberOfSides() {
[Link]("Triangle has 3 sides");
}
}
// Trapezoid class
class Trapezoid extends Shape {
void numberOfSides() {
[Link]("Trapezoid has 4 sides");
}
}
// Hexagon class
class Hexagon extends Shape {
void numberOfSides() {
[Link]("Hexagon has 6 sides");
}
}
// Main class
[Link]();
[Link]();
[Link]();
}
}
Output:
D:\vara>javac [Link]
D:\vara>java ShapeDemo
Triangle has 3 sides
Trapezoid has 4 sides
Hexagon has 6 sides
D:\vara>
AIM: To write a Java program that lets users create Pie charts.
Program:
import [Link].*;
import [Link];
int values[];
int total = 0;
PieChart(int v[]) {
values = v;
setSize(400, 400);
setTitle("Pie Chart");
setVisible(true);
}
startAngle += arcAngle;
}
}
[Link]("Enter values:");
for (int i = 0; i < n; i++) {
values[i] = [Link]();
}
new PieChart(values);
}
}