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

Java Lab Manual

The document provides an overview of a computer lab equipped with 72 HCL systems and outlines guidelines for student conduct and lab usage. It details the objectives of the lab, focusing on Java programming skills, and introduces Java as a versatile, object-oriented language. Additionally, it covers the setup of Java development environment, including PATH and CLASSPATH settings, and lists various lab experiments to be conducted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views47 pages

Java Lab Manual

The document provides an overview of a computer lab equipped with 72 HCL systems and outlines guidelines for student conduct and lab usage. It details the objectives of the lab, focusing on Java programming skills, and introduces Java as a versatile, object-oriented language. Additionally, it covers the setup of Java development environment, including PATH and CLASSPATH settings, and lists various lab experiments to be conducted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION ABOUT THE LAB

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

GUIDELINES TO THE STUDENTS

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.

5 Lab records need to be submitted on or before date of submission.

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.

11 Doesn’t bring bags inside the lab.


OBJECTIVES:

After completing this lab section, you will be able to:


 Use Java’s basic data types in your programs

 Writ Java programs using Sequential, Conditional and iterative statements

 Handle arrays of fixed and variable size

 Creating Classes and Objects using Java

 Implementing Constructors and Constructor Overloading

 Solving problems using Inheritance and Polymorphism

 Create your own package

 Create your own interface

 Handling exceptions arising in programs

 Use concept of multithreading in programs writing

 Handle Strings

 Use GUI components in your programs

 Use Layout Manages


INTRODUCTION TO JAVA – THE LANGUAGE:

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

Java is an Object Oriented Programming Language, which serve the purpose of


Object Oriented Paradigm of Programming. An object oriented language use the concept of
abstraction, encapsulation, inheritance, and polymorphism to provide flexibility, modularity,
and reusability for developing software.

MAIN FEATURES JAVA PROGRAMMING LANGUAGE

Simple :

 Java is Easy to write and more readable and eye catching.


 Java has a concise, cohesive set of features that makes it easy to learn and use.
 Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :

 Java program cannot harm other system thus making it secure.


 Java provides a secure means of creating Internet applications.
 Java provides secure way to access web applications.

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 :

 Java is not tied to a specific machine or operating system architecture.


 Machine Independent i.e Java is independent of hardware .

Interpreted :

 Java supports cross-platform code through the use of Java bytecode.


 Bytecode can be interpreted on any platform by JVM.

High performance :

 Bytecodes are highly optimized.


 JVM can executed them much faster .

Distributed :

 Java was designed with the distributed environment.


 Java can be transmit,run over internet.
Dynamic :

 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

If whenever you type on your dos prompt


javac [Link]

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.

Type path at your DOS prompt ,You will get

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.

Now try to run the java commands again.


If it still doesn't work, move your *.java files into the JDK directory -- and you should be
able to work there (or in the bin subdirectory of the JDK directory).
Here is the problem again because you’ll need to reset your path every time you turn your
machine back on and want to work on the Java programs again. But there is a way to fix it
permanently. You need to alter (edit) your [Link] file, which is in your main C:
directory. It is suggested to copy this file first to a back up version, then do required
modifications told to you here.

C: copy [Link] [Link]

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:

1. Right click on "My Computer" and Click on Properties.


2. Click on the Advanced tab.
3. Click on the "Environment Variables" button near the bottom.
4. A dialog box comes up with two boxes: In the bottom box, look for "Path" and highlight
that line. Then click on "Edit" .A small dialog box appears. In the second text field for the
value, at the END of the line, add a semicolon then the path to where your [Link] file is.
For example path is like:C:\jdk1.3….\bin
5. Click "OK."
6. Now, in the top box, click on the "New" button.
7. In the first field, enter "classpath" as one word. For the value in the second field, enter a
single period.

This is all you have to do for setting PATH and CLASSPATH.

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

[Link] Name of the Experiment Page No


A Java Program that uses both recursive and nonrecursive
functions to Print the nth value of the Fibonacci sequence.

1 The Fibonacci sequence is defined by the following rule. The first 2


values in the sequence are 1,[Link] subsequent value is the sum of
the 2 values preceding it.

A Java Program that prompts the user for an integer and then
2 prints out all the prime numbers upto that Integer.

A Java Program that checks whether a given string is a palindrome


3 or not. Ex. MALAYALAM is a palindrome.

A Java Program for sorting a given list of names in ascending


4
order.
5 A Java Program to check the compatibility for multiplication , if
compatible multiply two matrices and find its transpose.
A Java Program that illustrates how runtime polymorphism is
achieved.
6 i. Method Overloading
ii. Constructor Overloading
iii. Method Overriding
7 A Java Program to create and demonstrate packages.
A Java Program that using String Tokenizer class, which reads a
8 line of integers and then displays each integer and the sum of all
integers.
A Java Program that reads on file name form the user then displays
9 information about whether the file exists, whether the file is
readable/writable, the type of file and the length of the file in bytes
and display the content of the File.
10 A Java Program that displays the number of characters, lines and
words in a text/text file.
A Java Program that works as a simple calculator. Use a grid
11 layout to arrange buttons for the digits and for the +-*?%
operations. Add a text field to display the result.

12 A Java Program to handling mouse events.


A Java Program demonstrating the life cycle of a thread.
13
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
14
one of the classes contains only the method numberOfSides(), that
contains the number of sides in the given geometrical figure.

15 A Java program that lets users create Pie charts


Experiment -1:

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.

Recursive Fibonacci Program:


Program:
import [Link];

public class FibonacciSeriesRecursive {

static int fibonacci(int n) {


if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter number of terms: ");


int n = [Link]();

[Link]("Fibonacci Series:");
for (int i = 0; i < n; i++) {
[Link](fibonacci(i) + " ");
}

[Link]();
}
}

Oops Using JAVA Lab Manual Page 1


Output:
D:\vara>javac [Link]

D:\vara>java FibonacciSeriesRecursive
Enter number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Non-Recursive Fibonacci Series (n terms):


import [Link];

public class FibonacciIterative {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter number of terms: ");


int n = [Link]();

int a = 0, b = 1;

[Link]("Fibonacci Series:");

for (int i = 0; i < n; i++) {


[Link](a + " ");

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

Oops Using JAVA Lab Manual Page 2


Experiment:2
AIM : To write a Java Program that prompts the user for an integer and then prints
out all the prime numbers upto that Integer.
Program:
import [Link];

public class PrimeNumbers {

// Function to check prime


static boolean isPrime(int num) {
if (num <= 1)
return false;

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0)
return false;
}
return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter an integer: ");


int n = [Link]();

[Link]("Prime numbers up to " + n + " are:");

for (int i = 2; i <= n; i++) {


if (isPrime(i)) {
[Link](i + " ");
}
}

[Link]();
}
}
Output:
D:\vara>javac [Link]
D:\vara>java PrimeNumbers
Enter an integer: 7
Prime numbers up to 7 are:
2357

Oops Using JAVA Lab Manual Page 3


Experiment:3
AIM : To write a Java Program that checks whether a given string is a palindrome or
not. Ex. MALAYALAM is a palindrome.

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:\>

Oops Using JAVA Lab Manual Page 4


Experiment -4:

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

Oops Using JAVA Lab Manual Page 5


OUTPUT:
D:\>javac [Link]
D:\>java Sortst
How many string u want to enter : 5
Enter string 1 : Hyderabad
Enter string 2 : Nellore
Enter string 3 : Vizag
Enter string 4 : Ongole
Enter string 5 : Guntur

Strings in order are :


Guntur
Hyderabad
Nellore
Ongole
Vizag
D:\>

Oops Using JAVA Lab Manual Page 6


Experiment -5

AIM: To write a Java Program to check the compatibility for multiplication , if


compatible multiply two matrices and find its transpose.

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

[Link]("Enter a matrix column value :");

q=[Link]();

[Link]("Enter b matrix row value :");

m = [Link]();

[Link]("Enter b matrix columnvalue :");

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]();
}

[Link]("Enter matrxi B values :");

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

Oops Using JAVA Lab Manual Page 8


}
// for C matrix Printing

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

Enter matrxi B values :


1

Oops Using JAVA Lab Manual Page 9


2
3
4
5
6

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:\>

Oops Using JAVA Lab Manual Page 10


Experiment -6

AIM: To Write a Java Program that illustrates how runtime polymorphism is


achieved.
i. Method Overloading
ii. Constructor Overloading
iii. Method Overriding

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

Oops Using JAVA Lab Manual Page 11


OUTPUT:
D:\>javac [Link]
D:\>java MethOverload
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of [Link](123.25): 15190.5625
D:\>

ii. Constructor Overloading:


class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class ConsOverload {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();

Oops Using JAVA Lab Manual Page 12


Box mycube = new Box(7);
double vol;
// get volume of first box
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
// get volume of second box
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
// get volume of cube
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}

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:\>

Oops Using JAVA Lab Manual Page 13


iii. Method Overriding:

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:\>

Oops Using JAVA Lab Manual Page 14


Experiment -7

AIM: To write a Java Program to create and demonstrate packages.

PROCEDURE:

Step 1: Create “MyPack” folder in your directory.


Step 2: Create [Link] Program in MyPack folder.
Step 3: Compile [Link] source code as
javac MyPack\[Link]
Step 4: Run the program as
java MyPack. AccountBalance

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

Oops Using JAVA Lab Manual Page 15


OUTPUT:
D:\>javac MyPack\[Link]
D:\>java [Link]
K. J. Fielding: $123.23
Will Tell: $157.02
--> Tom Jackson: $-12.33

Oops Using JAVA Lab Manual Page 16


Experiment -8

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:\>

Oops Using JAVA Lab Manual Page 17


Experiment -9
AIM: To write a Java Program that reads on file name form the user then displays
information about whether the file exists, whether the file is readable/writable,
the type of file and the length of the file in bytes and display the content of the
File.

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

Oops Using JAVA Lab Manual Page 18


Experiment -10

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

Oops Using JAVA Lab Manual Page 19


catch(IOException e)
{
[Link]();
}
}
private static long wordcount(String line)
{
long numWords = 0;

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

Oops Using JAVA Lab Manual Page 20


[Link]("Number of words: " + wordcount(line));
[Link]("Number of lines: " + numLine);
}
else
{
for(int i = 0; i < [Link]; i++)
{
linecount(args[i]);
}
}
}
catch(IOException e){
[Link]();
}
}
}

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:\>

Oops Using JAVA Lab Manual Page 21


Experiment -11

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].*;

public class SimpleCalculator extends JFrame implements ActionListener {

JTextField tf;
String num1 = "", num2 = "", operator = "";

SimpleCalculator() {
tf = new JTextField();
[Link](false);
[Link](new Font("Arial", [Link], 20));

setLayout(new BorderLayout());
add(tf, [Link]);

JPanel panel = new JPanel();


[Link](new GridLayout(5, 4, 5, 5));

String buttons[] = {
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0","%","=","+",
"C","","",""
};

for (String text : buttons) {


Oops Using JAVA Lab Manual Page 22
JButton btn = new JButton(text);
[Link](new Font("Arial", [Link], 16));
[Link](this);
[Link](btn);
}

add(panel, [Link]);

setTitle("Simple Calculator");
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();

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;

Oops Using JAVA Lab Manual Page 23


}

[Link]([Link](result));
}
else if ([Link]("C")) {
[Link]("");
num1 = num2 = operator = "";
}
}

public static void main(String[] args) {


new SimpleCalculator();
}
}

Output:
D:\vara>javac [Link]

D:\vara>java SimpleCalculator

Oops Using JAVA Lab Manual Page 24


Experiment -12
AIM: To write a Java Program to handling mouse events.

PROGRAM:
import [Link].*;
import [Link].*;

public class MouseEventDemo extends Frame implements MouseListener {

String msg = "";

MouseEventDemo() {
addMouseListener(this);

setSize(400, 300);
setTitle("Mouse Event Handling");
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


msg = "Mouse Clicked at (" + [Link]() + "," + [Link]() + ")";
repaint();
}

public void mousePressed(MouseEvent e) {


msg = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent e) {


msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint();

Oops Using JAVA Lab Manual Page 25


}

public void mouseExited(MouseEvent e) {


msg = "Mouse Exited";
repaint();
}

public void paint(Graphics g) {


[Link](msg, 50, 100);
}

public static void main(String[] args) {


new MouseEventDemo();
}
}

Output:
D:\vara>javac [Link]

D:\vara>java MouseEventDemo

Oops Using JAVA Lab Manual Page 26


Oops Using JAVA Lab Manual Page 27
Oops Using JAVA Lab Manual Page 28
Experiment -13

AIM: To write a Java Program demonstrating the life cycle of a thread.

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

Oops Using JAVA Lab Manual Page 29


class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
[Link]("welcome");

}
}

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]();
}
}

Oops Using JAVA Lab Manual Page 30


OUTPUT:
D:\Java\Lab>javac [Link]
D:\Java\Lab>java ThreadDemo
good morning
good morning
hello
good morning
welcome
hello
good morning
good morning
good morning
hello
welcome
good morning
hello
good morning
welcome
good morning
good morning
hello
good morning
good morning
welcome
hello
D:\Java\Lab>

Oops Using JAVA Lab Manual Page 31


Experiment -14

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

Oops Using JAVA Lab Manual Page 32


public class ShapeDemo {
public static void main(String[] args) {

Shape t1 = new Triangle();


Shape t2 = new Trapezoid();
Shape t3 = new Hexagon();

[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>

Oops Using JAVA Lab Manual Page 33


Experiment -15

AIM: To write a Java program that lets users create Pie charts.

Program:

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

public class PieChart extends Frame {

int values[];
int total = 0;

PieChart(int v[]) {
values = v;

for (int i = 0; i < [Link]; i++) {


total += values[i];
}

setSize(400, 400);
setTitle("Pie Chart");
setVisible(true);
}

public void paint(Graphics g) {


int startAngle = 0;

for (int i = 0; i < [Link]; i++) {


int arcAngle = (int) [Link](((double) values[i] / total) * 360);

// Random color for each slice


[Link](new Color((int)([Link]()*255),
(int)([Link]()*255),
(int)([Link]()*255)));

Oops Using JAVA Lab Manual Page 34


[Link](100, 100, 200, 200, startAngle, arcAngle);

startAngle += arcAngle;
}
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of categories: ");


int n = [Link]();

int values[] = new int[n];

[Link]("Enter values:");
for (int i = 0; i < n; i++) {
values[i] = [Link]();
}

new PieChart(values);
}
}

Oops Using JAVA Lab Manual Page 35


Oops Using JAVA Lab Manual Page 36

You might also like