Beruflich Dokumente
Kultur Dokumente
TABLE OF CONTENTS
1. Lab Plan
2. Introduction to Java
3. Unit – I (Basic Java)
a. Introduction to main concepts used in Unit – 1
b. Experiment – 1 (Quadratic Equation Roots)
c. Experiment – 2 (Fibonacci Series)
d. Experiment – 3 (Prime Numbers)
e. Experiment – 4 (Matrix Multiply)
f. Experiment – 5 (Tokenize Integers and get SUM)
g. Experiment – 6 (Palindrome)
h. Experiment – 7 (Names Sorting)
2
JAVA LAB MANUAL BIET
Introduction to JAVA
Java Programming Language:
Java is a very popular and widely used programming language and it was not be an
exaggeration to say it is the most widely used programming language in industry now.
The reason for its wide popularity was probably the well thought of goals of the
programming language. Among other attractive features, the following stand out in
ensuring it gets wide acceptability.
1. Ease of use
2. Object Oriented
3. Very strong API
4. Focus on removing hard to use and error-prone constructs
5. Platform Independence
6. Open Source encouraging collaborative development.
7. Security (Sandbox)
When people refer to the term JAVA, they are actually referring to any one or all three
of the following.
All three together along with the numerous tools that provide for a strong programming
environment, making programming easy and encouraging rapid application development
has made Java one of the most popular programming languages.
3
JAVA LAB MANUAL BIET
encouraged vendors in developing the same for almost all machine architectures by
providing the reference implementation.
Since the byte code is machine independent, JAVA programs can be compiled once (into
byte code) and executed on any machine architecture provided there is a JVM
implementation on that architecture.
Installation:
The latest version of JAVA (1.6 at the time of writing this revision of manual) is freely
downloadable from www.java.sun.com. All machines in our Java lab have JAVA 1.5 or
higher installed at C:\Program Files\Java.
On the Linux/Solaris side, the students should run the command “which javac” on their
shell to figure out the path of Java installation.
Java Compiler:
Java Compiler is the utility that compiles Java programs to their corresponding Byte
Code(.class files). Javac is platform independent, for the simple reason that both
source(input) and output of the javac program are platform independent. Java Compiler
or “javac” as it is commonly called would be available in C:\Program
Files\Java\jdk1.5.0_01\bin.
Java Interpreter:
Java interpreter or the Java Virtual Machine (It is called so because interpreter is a
machine emulator executing each instruction in byte-code, line by line) is the software
which executes Byte-Code. The interpreter is machine dependent because it interprets
machine independent byte-code on a given machine architecture. The Java interpreter
or “java” as it is commonly called would be available in C:\Program
Files\Java\jdk1.5.0_01\bin
Environment Variables:
PATH: This should have the path of “javac” and other utilities, so they can be invoked
directly without having to give the full absolute path.
4
JAVA LAB MANUAL BIET
CLASS PATH:
This environment variable is used to hold all paths in which Java Byte code of all c lasses
which one hopes to use in his or her program. For example, classpath environment
variable should have the path till lib directly in Java installation if we plan to use the
Java API classes which we most certainly will. CLASSPATH should also have path of all
user defined packages that would be used.
Packages:
Packages are actually groups of related classes and also serve the purpose of avoiding
namespace cluttering. You can define your own packages and put your classes in that
package.
Example:
Let us say I want to create 2 classes called Stack and Queue. I would create a package
called edu.biet.cse.generic and put these classes in that package. To do so, I have to do
the following:
1. Create a directory structure edu/biet/cse/generic is some folder x.
2. Put my Stack and Queue classes in that directory with the first line of these .java
files indicating that they belong to package edu.biet.cse.generic.
3. Compile all files in the package by going into the generic directory and saying
“javac *.java”
4. If I want to use these classes, I put the path “x” in CLASSPATH environment
variable.
5. In the java file where I want to use the classes in this package, I would put an
import edu.biet.cse.generic.* statement before going ahead and using the class.
Java.lang package offers the basic data types and basic classes and is automatically
imported without any explicit import from programmers. All other packages have to be
explicitly imported by the programmers depending on the need. Importing classes means
that the classes would be loaded by the Java Loader into JVM and takes time. So, it is
advisable to only import those packages and classes which would be used.
Other commonly used packages in JAVA API are java.io, java.util, java.sql, java.awt,
javax.swing, java.net, etc.
5
JAVA LAB MANUAL BIET
recommended that we use JAVA Doc to generate similar documentation for all JAVA
classes we write as a matter of practice.
Where is it available?
JAVA API documentation is a must for all JAVA programmers and can be downloaded
from Java.sun.com. Without documentation handy, it is highly unlikely you would be
using the API support in JAVA to a good extent. Java API is available on all our machines
in C:\Program Files\Java\jdk1.5.0_01\docs.
How to use?
Clicking on C:\program files\Java\jdk1.5.0_01\docs\index.html will lead you to a page
where there will be a link to API specification. Click on the framed version. From the
resultant page, you can navigate to any package, class, interface and look at its
documentation and go to any related classes following the necessary navigation links.
Note: Compiler will generate HelloWorld.class which is the byte code. The Interpret will
interpret HelloWorld.class by invoking HelloWorld.main().
6
JAVA LAB MANUAL BIET
Introduction to Unit - I
This unit covers the basics of Java. In this unit, students work on programs that expose
them to basic syntactic structures of Java, arithmetic operations, classes, objects,
access specifiers, core Java API libraries java.lang, java.util, class methods among other
things.
I. User Defined Data Types (Classes): One of the fundamental concepts in any object
oriented language (Java is no exception) is the concept of creating user defined
data types that encapsulate properties and behavior and selectively exposing public
behavior.
II. Class Methods & Object Methods: For any user defined data type, there will
possibly be properties at an instance (one instance of that data type) level called
instance variables or member variables and class variables or class properties which
have the same value across all instances of the class. These properties are
meaningful at the class level and have values irrespective of whether a member of
the class has been instantiated or not. These properties can be variables or
methods.
III. Member Variables: Properties of instances of class are called member variables.
Mathematically speaking, class is a set and objects are members of a set. Every
element of a set is identified by certain behavior (methods) which is the c ommon
behavior and properties whose values might vary from member of the set to
another or stay the same.
IV. Access Specifiers (Private, Public): To allow for data hiding, there are different
specifiers through which access to class members (variables & methods) can be
controlled. Public means the member is available for use directly outside the class.
Private means only available for internal methods.
7
JAVA LAB MANUAL BIET
VI. Basic Data Types (int, float, Boolean): Though java is object based, a few basic
data types have both a class equivalent and a basic data type. Example: int is a
basic data type and Integer is its class equivalent.
VII. Conditional Statement (if), loop statements (for): The conditional and looping
constructs are pretty much the same as C type languages.
8
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java Program that prints all real solutions to the quadratic equation ax**2+bx+c
= 0. Read in a, b, c and use the quadratic formula. If the discriminant b**2 – 4ac is
negative, display a message stating that there are no real solutions.
2. Solution Design:
Design a class named QuadEq which has the constants a, b and c and member variables
and the two roots as member variables. All member variables have to be private. Design
3 public methods, one to computeRoots, the other two methods are getter methods to
give the roots stored in member variables. Write a public method called hasRealRoots()
that return Boolean true if the equation has real roots and otherwise returns false.
4. Test Cases:
Test 1:
Input: a = 1, b = 4, c = 4
Expected Output: Root1 = 2, Root2 = 2
Test 2:
Input: a = 9, b = 2, c = 5
Expected Output: No real roots
9
JAVA LAB MANUAL BIET
5. Reference Implementation:
###########################################################
File name: QuadEq.java
10
JAVA LAB MANUAL BIET
class QuadEquationTest
{
public static void main(String[] args)
{
int a = 9, b = 2, c = 5;
}
}
###########################################################
6. Execution:
1. javac QuadEq.java
2. java QuadEquationTest
11
JAVA LAB MANUAL BIET
Output:
1. Problem Statement:
The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it.
Write a Java program that uses both recursive and non-recursive functions to print the
nth value in the Fibonacci sequence.
2. Solution Design:
Write a class Fibonacci with 2 static methods. The methods are static because nth
Fibonacci number is property of Fibonacci class and there is no concept of object of
Fibonacci series because there is really only one Fibonacci series in the world. The 2
static methods return nth element in Fibonacci series given n and can be names
nthFiboRecursive and nthFiboNonRecursive. Both yield the same result for a given n, but
each follow a different implementation style (one is a recursive algorithm and the other
non-recursive) and hence could lead to different performance times for high values of n.
The idea is for the student to appreciate the time-overhead of using recursive
algorithms and how it can exponentially increase with n vs. the conceptual simplicity of
a recursive algorithm.
4. Test Cases:
Test 1:
Input: n = 30
12
JAVA LAB MANUAL BIET
5. Reference Implementation:
####################################################################
File name: Fibonacci.java
13
JAVA LAB MANUAL BIET
count--;
}
return Higher;
}
}
}
class FibonacciTest
{
public static void main(String[] args)
{
int n = 30;
System.out.println(Fibonacci.nthFiboRecursive(n));
System.out.println(Fibonacci.nthFiboNonRecursive(n));
}
}
##################################################################################
6. Execution:
1. javac Fibonacci.java
2. java FibonacciTest
OUT PUT:
14
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java Program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
2. Solution Design:
Write a class called Prime that has two static methods, one (isPrime) which returns true
if a given number is prime and false otherwise and another which takes n and prints all
prime numbers less than n by calling the previous method to determine if a number is
prime or not.
The reason these methods are static is because these are class methods and there are no
properties that are object specific.
4. Test Cases:
Test1:
Input: n = 23
Output: All prime numbers less than or equal to 23.
15
JAVA LAB MANUAL BIET
5. Reference Implementation:
###########################################################
File name: Prime.java
public class Prime
{
public static boolean isPrime(int n)
{
if((n == 0) || (n == 1))
{
return false;
}
else if(n == 2)
{
return true;
}
else
{
int Median = (n/2) + 1;
boolean isPrime = true;
for(int i=2; i<=Median; i++)
{
if((n % i) == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
16
JAVA LAB MANUAL BIET
}
}
###########################################################
6. Execution:
1. javac Prime.java
2. java PrimeTest
OUT PUT:
17
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java program to multiply two given matrices.
2. Solution Design:
Write a class Matrix which encapsulates all properties of a matrix including number of
rows, columns, the values of the matrix and whether the matrix is populated with data.
The class should provide access methods to get rows, cols, cell data, whether data is
populated or not. The class should also have public methods to display matrix and
multiply this matrix with another matrix. The class should provide a constructor which
takes number of rows and cols only and another which takes number of rows and cols
and a String which has blank separated matrix data. For unpopulated Matrix, the class
should provide a method which will allow copying of data from another Matrix. We also
want a method which checks whether we can multiply this matrix with another matrix
checking the rows and cols.
4. Test Cases:
Test1:
Input: Create a 3*2 and a 2*3 matrix and multiply them.
Expected output: Check the result to verify output
18
JAVA LAB MANUAL BIET
Test2:
Input: Create a 3*2 and a 3*2 matrix and multiply them.
Expected output: Cannot multiply matrices.
5. Reference Implementation:
####################################################################
File: Matrix.java
import java.util.StringTokenizer;
19
JAVA LAB MANUAL BIET
else
{
for(int row=0;row<mNumRows;row++)
{
for(int col=0;col<mNumCols;col++)
{
mData[row][col] =
(new Integer(str.nextToken())).intValue();
}
}
}
mIsDataPopulated = true;
}
public boolean isDataPopulated()
{
return mIsDataPopulated;
}
20
JAVA LAB MANUAL BIET
return false;
}
else if((anotherMatrix.getNumRows() != mNumRows) ||
(anotherMatrix.getNumCols() != mNumCols))
{
return false;
}
else
{
mIsDataPopulated = true;
for(int i = 0;i < mNumRows;i++)
{
for(int j = 0; j < mNumCols;j++)
{
mData[ i ][ j ] = anotherMatrix.getCellElement(i,j);
}
}
return true;
}
}
public boolean canMultiply(Matrix anotherMatrix)
{
if(mNumCols == anotherMatrix.getNumRows())
{
return true;
}
else
{
return false;
}
}
public Matrix multiply(Matrix anotherMatrix)
{
Matrix resultMatrix = null;
if(canMultiply(anotherMatrix))
{
StringBuffer Result = new StringBuffer("");
21
JAVA LAB MANUAL BIET
}
public void display()
{
for(int i=0;i < mNumRows; i++)
{
for(int j=0; j < mNumCols; j++)
{
System.out.print(getCellElement(i,j) + " ");
}
System.out.println("");
}
}
}
22
JAVA LAB MANUAL BIET
class MatrixMultiplyTest
{
public static void main(String[] args)
{
int Rows1 = 3;
int Cols1 = 2;
String MatrixStr1 = "1 2 3 4 5 6";
Matrix Matrix1 = new Matrix(3,2,MatrixStr1);
System.out.println("Input Matrix 1");
Matrix1.display();
int Rows2 = 2;
int Cols2 = 3;
String MatrixStr2 = "1 2 3 4 5 6";
Matrix Matrix2 = new Matrix(2,3,MatrixStr2);
System.out.println("Input Matrix 2");
Matrix2.display();
if(Matrix1.canMultiply(Matrix2))
{
Matrix Mul = Matrix1.multiply(Matrix2);
System.out.println("The result of multiplying Matrix1 and Matrix 2
is:");
Mul.display();
}
}
}
####################################################################
6. Execution:
1. javac Matrix.java
2. java MatrixMultiplyTest
OUT PUT:
1. Problem Statement:
Write a Java program that read a line of Integers and then displays each integer, and
the sum of all Integers (use StringTokenizer class)
2. Solution Design:
Write a class MyIntegerSeries which encapsulates an ArrayList of Integers (to allow for
dynamic growth depending on how many Integers are there in the String) and a public
method called getSUMofSeries() which will give the sum of all Integers. The constructor
should take a String and tokenize it to populate the ArrayList of Integers.
4. Test Cases:
Test1:
Input: String: “1 2 3 4 5 6 7 8 9 10”
Expected Output: 55
5. Reference Implementation:
24
JAVA LAB MANUAL BIET
###########################################################
File: MyIntegerSeries.java
import java.util.StringTokenizer;
import java.util.ArrayList;
public class MyIntegerSeries
{
private ArrayList<Integer> mIntegerList = null;
public MyIntegerSeries(String str)
{
StringTokenizer st = new StringTokenizer(str);
mIntegerList = new ArrayList<Integer>();
while(st.hasMoreTokens())
{
mIntegerList.add(new Integer(st.nextToken()));
}
}
public int getSUMofSeries()
{
int sum = 0;
for(int i = 0; i < mIntegerList.size(); i++)
{
sum += (mIntegerList.get(i)).intValue();
}
return sum;
}
}
class IntegerSUMTest
{
public static void main(String[] args)
{
String test = "1 2 3 4 5 6 7 8 9 10";
MyIntegerSeries obj = new MyIntegerSeries(test);
System.out.println(obj.getSUMofSeries());
}
}
###########################################################
6. Execution
1. javac MyInetgerSeries.java
2. java IntegerSUMTest
OUTPUT:
Experiment – 6: Palindrome
25
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome.
2. Solution Design:
Write a class Palindrome that has a static method (isPalindrome) which takes a String as
argument and returns true if the String is a palindrome, otherwise returns false. The
algorithm just reverses the String after taking the String into a StringBuffer and
compares both. If the String and its reverse are same, we can say the given input String
is a Palindrome.
4. Test Cases:
Test1:
Input: String = “MALAYALAM”
Expected output: The string MALAYALAM is a Palindrome.
Test2:
Input: String = “Madam”
Expected output: The string Madam is a Palindrome.
Test3:
Input: String = “Hellh”
Expected output: The string Hellh is not a Palindrome.
5. Reference Implementation:
26
JAVA LAB MANUAL BIET
################################################## #########
File: Palindrome.java
class PalindromeTest
{
public static void main(String[ ] args)
{
if(Palindrome.isPalindrome(test.toLowerCase()))
{
System.out.println("The string:" + test + " is a Palindrome");
}
else
{
System.out.println("The string:" + test + " is not a Palindrome");
}
}
}
###########################################################
27
JAVA LAB MANUAL BIET
6. Execution:
1. javac Palindrome.java
2. java PalindromeTest
Out put:
28
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java program for sorting a given list of names in ascending order.
2. Solution Design:
Write a class NameSort that encapsulates a list (array) of names with a constructor that
takes an array of names and stores them in a private array member variable, and two
public methods, one of which sort the list of names in the array member variable and
the other that displays the names in the array.
4. Test Cases:
Test 1:
Input: count = 4; Names = “ABC”, “XYZ”, “HELLO”
Expected Output: “ABC”, “HELLO”, “XYZ”
Test2:
Input: count = 6; Names = “gui”, ”bad”, ”design”, ”other”, “hello”, “what”
Expected output: “bad”, “design”, “gui”, “hello”, “other”, “what”
5. Reference Implementation:
29
JAVA LAB MANUAL BIET
###########################################################
File: NameSort.java
import java.lang.*;
import java.util.*;
class NameSortTest
{
30
JAVA LAB MANUAL BIET
###########################################################
6. Execution:
1. javac NameSort.java
2. java NameSortTest
OUT PUT:
Introduction to Unit - II
31
JAVA LAB MANUAL BIET
This unit introduces Streams, which are the JAVA way of providing API for programmers
to read data or write data from and to different data source. The streams API interface
is all grouped into java.io package and includes Stream Interfaces, Stream Classes,
Buffered Interfaces, Buffered Classes and other general purpose utility classes related to
input/output.
1. Programming to Interface: Java API has Interfaces like DataInput and DataOutput
which are implemented by various Input and Output Stream classes. This kind of
Interface based API allows the users to program at a high level thereby reducing
the program’s dependency on a specific implementation.
2. Reading data from files: This unit shows you how you can use classes from JAVA
API to read from files.
3. Writing data to files: This unit shows you how you can use classes from JAVA API
to write to files.
4. Understanding File related exceptions: This unit exposes you to some of the
exceptions possible while doing IO related operations and what they indicate.
5. Finding out File properties: This unit shows you class that encapsulates file
properties in Java, internally using the local File management system to get the
properties.
6. Common Data Structures: Assuming you are already familiar with common data
structures and their operations, this unit gives you a chance to look at JAVA API
classes implementing the most common data structures that can be directly used
in your JAVA programs without you having to implement the basic data structures.
Of course, it would be good for students to see the public interface o f these data
structures and understand how the interface has been designed and understand
core OO principles of data abstraction which are behind the design of JAVA API.
7. IOStream Library Hierarchy: JAVA API library follows a very logical hierarchy of
interfaces and implementation classes that allows for extensibility either by
extending interfaces or by changing implementations as the user wants.
32
JAVA LAB MANUAL BIET
Understanding the hierarchy and appreciating its design would certainly help
students get the essence of object oriented programming and programming for
extensibility.
Experiment – 8: File Properties
1. Problem Statement:
Write a Java Program that reads one file name from the user then displays information
about whether the file exists, whether the file is read able, whether the file is writable,
the type of file and the length of the file in bytes.
2. Solution Design:
Write a class named MyFile which would have method called displayFileProperties() that
would print all the properties of file like whether the file exists, what is the absolute
path of the file, whether the file is readable and writable, whether it is a regular file or
a directory and size of file in bytes. The constructor of the class should take a path
(absolute or relative) as argument.
4. Test Cases:
Test1: Valid file name with full path
Test2: Valid file name with relative path
Test3: invalid file
5. Reference Implementation:
####################################################################
33
JAVA LAB MANUAL BIET
File: MyFile.java
import java.io.*;
34
JAVA LAB MANUAL BIET
OUTPUT:
1. Problem Statement:
35
JAVA LAB MANUAL BIET
Write a Java program that reads a file and displays a file on the screen, and displays the
file on the screen with a line number before each line.
2. Solution Design:
Write a class called FileDisplay which checks whether a given file exists, i sReadable, is a
file filetype, reads the file using an InputStream and display the file to command line as
is and with line number, one line at a time.
4. Test Cases:
Test1: A valid text file in your file system
5. Reference Implementation:
##################################################################################
File: FileDisplay.java
import java.io.*;
public class FileDisplay
{
private String mName;
private File mFileHandle;
public FileDisplay(String str)
{
mName = new String(str);
mFileHandle = new File(mName);
}
36
JAVA LAB MANUAL BIET
37
JAVA LAB MANUAL BIET
lNextLine = lBr.readLine();
}
lBr.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class FileDisplayTest
{
public static void main(String[] args)
{
String str = "hi.txt";
FileDisplay lDisplay = new FileDisplay(str);
if((lDisplay.isExistsFile()) &&
(lDisplay.isRegularFile()) &&
(lDisplay.isReadableFile()))
{
System.out.println("File Contents of" + str + " are :");
lDisplay.displayFileContents();
System.out.println("File Contents with line number of" + str + " are
:");
lDisplay.displayFileContentsWithLineNumber();
}
}
}
##################################################################################
6. Execution:
1. javac FileDisplay.java
2. java FileDisplayTest
38
JAVA LAB MANUAL BIET
out put:
1. Problem Statement:
39
JAVA LAB MANUAL BIET
Write a Java program that displays the number of characters, lines and words in a text
file.
2. Solution Design:
Write a class FileCharacterCount that has methods to check for basic file properties and
than opens a file using InputStream class and reads one line at a time, tokenizes the line
on spaces, gets word count and takes the length of like and adds it to character count
and this comes up with line count, word count and character count of the file.
4. Test Cases:
Test1: Any valid text file in your file system
5. Reference Implementation:
####################################################################
File: FileCharacterCount.java
import java.io.*;
import java.util.*;
40
JAVA LAB MANUAL BIET
41
JAVA LAB MANUAL BIET
6. Execution:
1. javac FileCharacterCount.java
2. java FileCharacterCount
This unit covers the support for rich user interface development in Java. In this unit,
students work on programs that expose them to various user interface elements/widgets
provided by Java to help construct rich user interface either in desktop applications or
42
JAVA LAB MANUAL BIET
on web using applets which are java objects within HTML. Java supports UI components
starting from the simple ones like button, textbox to complex components like table,
tree and components that can contain other components in them like panels, frames,
etc. Java API packages that would be predominately used are java.awt and javax.swing
and java.awt.event. JAVA also supports an event model which allows programs to
register callbacks on events of interest on a UI object.
2. Event driven programming: It is a concept where the software does some action
based on an action that user performs on the user interface and otherwise stays
idle waiting for a user action. This kind of programming is pretty common for
software which is built for the purpose of users using the services of the software
on an interactive basis as and when they need some functionality supported by
the software.
4. Applets: Java provides support for embedding objects in HTML allowing users to
build rich JAVA powered user interface application accessible from web. Because
applet running on web cannot by default be considered non-malicious, JAVA
implements a sandbox security model which places sufficient restrictions on what
an applet can and cannot do to ensure client’s system is not compromised on a
malicious attack.
5. Model View Controller pattern: JAVA user interface library follows MVC pattern
that allows multiple views to be attached to a given model and java library
43
JAVA LAB MANUAL BIET
automatically ensures all views are updated when the model changes using a
publish-subscribe internal implementation.
1. Problem Statement:
Write an applet that displays a simple message.
44
JAVA LAB MANUAL BIET
2. Solution Design:
Write a class MyDisplayApplet class which extends JApplet class and implements the init
method by adding a JLabel with a message to the content pane of the applet. Set the
size of the applet to some reasonable size.
4. Test Cases:
Test1: go to the AppletTest.html in your favorite browser.
5. Reference Implementation:
####################################################################
File: MyDisplayApplet.java
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
File: AppletTest.html
<html>
<head>
</head>
45
JAVA LAB MANUAL BIET
<body>
<applet code=MyDisplayApplet.class width=600 height=400>
</applet>
</body>
</html>
####################################################################
6. Execution:
1. javac MyDisplayApplet.java
2. goto AppletTest.html in browser.
1. Problem Statement:
Write an applet that computes the payment of a loan based on the amount of the loan,
the interest rate and the number of months. It takes one parameter from the browser:
Monthly rate; if true, the interest rate is per month; other wise the interest rate is
annual.
2. Solution Design:
Design a class called InterestApplet extending JApplet and building a UI that has 3
TextFields that allows the user to enter amount, interest rate and number of months
loaned, a button called Compute which when clicked will compute interest and sho w it
in another TextField labeled Interest. The rate entered is taken as monthly rate or
yearly rate based on parameter input coming from Browser.
4. Test Cases:
Test1: Amount: 100, Months = 12, Interest = 18
Test2: Amount: 1500, Months 29, Interest = 12
5. Reference Implementation:
####################################################################
File: InterestApplet.java
import javax.swing.*;
46
JAVA LAB MANUAL BIET
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
getContentPane().setLayout(new GridLayout(4,2));
47
JAVA LAB MANUAL BIET
getContentPane().add(lLabelAmount);
getContentPane().add(mLoanText);
getContentPane().add(lLabelIntRate);
getContentPane().add(mIntRateText);
getContentPane().add(lLabelMonths);
getContentPane().add(mNumMonthsText);
getContentPane().add(lButtonRepaymentAmount);
getContentPane().add(mRepaymentAmountText);
lButtonRepaymentAmount.addActionListener(
new InterestActionListener());
setPreferredSize(new Dimension(400,300));
setVisible(true);
}
if(mIsMonthlyRate.equals("true"))
{
float totalInterest = mLoan*(mRate/100)*mNumMonths;
totalInterest += mLoan;
mRepaymentAmountText.setText(
(new Float(totalInterest)).toString());
}
else
{
float totalInterest = mLoan*(mRate/(12*100))*mNumMonths;
totalInterest += mLoan;
48
JAVA LAB MANUAL BIET
mRepaymentAmountText.setText(
(new Float(totalInterest)).toString());
}
}
}
File: InterestAppletTest.html
<html>
<head>
</head>
<body>
<applet code=InterestApplet.class width=600 height=100
MonthlyRate=false>
</applet>
</body>
</html>
####################################################################
6. Execution:
1. javac InterestApplet.java
2. go to InterestAppletTest.html in your browser.
1. Problem Statement:
Write a Java Program to handle mouse events.
2. Solution Design:
49
JAVA LAB MANUAL BIET
4. Test Cases:
Test1: Test by moving the mouse into and out of the applet and by clicking the
mouse in the applet and see the applet status message change.
5. Reference Implementation:
####################################################################
File: MouseEventsApplet.java
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
50
JAVA LAB MANUAL BIET
File: MouseEventsAppletTest.html
<html>
<head>
</head>
<body>
<applet code=MouseEventsApplet.class width=600 height=400>
</applet>
</body>
</html>
####################################################################
6. Execution:
1. javac MouseEventsApplet.java
2. go to MouseEventsAppletTest.html in your browser
51
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java Program that allows the user to draw line, rectangles.
2. Solution Design:
Write a class called MyCanvas which encapsulates a Canvas object to which a
mouseListener is added. When the mouse is clicked, the point where the click was done
will be added to the ArrayList of points. When the button called DrawLine is clicked, the
pointsArray is checked for entries and if there are more than 2 points selected a line is
drawn in the paint method from point1 to point 2.
4. Test Cases:
Test1: Click on more than 2 points in canvas and than click button. A line will be
drawn.
Test2: Click on 0 or 1 points in canvas and click draw line button. A message will
be displayed saying line cannot be drawn.
5. Reference Implementation:
####################################################################
File: MyCanvas.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public MyCanvas()
52
JAVA LAB MANUAL BIET
{
setLayout(new BorderLayout());
mCanvas = new Canvas();
mCanvas.addMouseListener(new MyMouseListener());
add(mCanvas, BorderLayout.CENTER);
JPanel lButtonPanel = new JPanel();
lButtonPanel.setLayout(new GridLayout(1,1));
JButton lDrawLineButton = new JButton("Draw Line");
lDrawLineButton.addActionListener(new MyActionListener());
lButtonPanel.add(lDrawLineButton);
add(lButtonPanel, BorderLayout.SOUTH);
mPointsSelected = new ArrayList<Point>();
}
53
JAVA LAB MANUAL BIET
6. Execution:
1. javac MyCanvas.java
2. java MyCanvas
Introduction to Unit - IV
54
JAVA LAB MANUAL BIET
This unit covers JAVA’s features for parallel programming using threads and JAVA’s
support for building client/server application using socket programming. The packages in
JAVA API you would be exposed to are java.lang for Thread related classes and java.net
for socket programming related data.
1. Parallel Programming means we have more than one execution threads running
in parallel as far as the user goes as against conventional programs w hich have
one line of execution
2. Threads is JAVA’s API for providing the users the ability to have multiple lines of
execution in a given program. Threads allow users to start parallel lines of
execution, suspend it and share data across multiple threads.
4. Socket Programming allows users to write server programs that are running on a
machine tied to a socket and listening for client requests for service and respond
to them. Clients need to know the machine and socket on which the service is
running so it can use the server for a service. It also needs to know the protocol
or the message format which the server would understand.
5. Server Socket is distinct from client socket because it is a listening socket only
there to listen to new client connections all the time.
6. Client Socket is used by clients to open a socket on the client side which will
connect to the server through server socket and get linked up to a unique socket
55
JAVA LAB MANUAL BIET
on the server side for a given connection so message can be exchanged between
client and server till one of the parties closes the connection.
7. Reflection API is JAVA’s support for RTTI (runtime type identification) and allows
for objects to be created at runtime, messages to be invoked at runtime with
parameters also constructed at runtime.
1. Problem Statement:
Write a Java Program for creating multiple threads.
2. Solution Design:
56
JAVA LAB MANUAL BIET
Write a class MyThread that extends Thread and has a static Counter and a thread
number as members. The run method should call the method called incrementCounter
which would be a static method the MyThread class and increments the ourCounter
variable value and prints its value with the Thread id of the Thread object which invokes
this method. incrementCounter method should be synchronized so multiple threads do
not try to increment the counter at precisely the same time.
Class: MyThread
Interface: run()
Other Methods: static incrementCounter()
Members: int for thread id and a static ourCounter.
4. Test Cases:
Test1: create 2 threads with ids 0 & 1 and start them.
5. Reference Implementation:
####################################################################
File: MyThread.java
{
e.printStackTrace();
}
}
File: MyThreadTest.java
public class MyThreadTest
{
public static void main(String[] args)
{
MyThread thread1 = new MyThread(0);
MyThread thread2 = new MyThread(1);
thread1.start();
try
{
Thread.sleep(600);
}
catch(Exception e)
{
}
thread2.start();
}
}
####################################################################
6. Execution:
1. javac MyThread.java
2. javac MyThreadTest.java
3. java MyThreadTest
58
JAVA LAB MANUAL BIET
1. Problem Statement:
Write a Java program that correctly implements producer consumer problem using the
concept of inter thread communication.
2. Solution Design:
Write a class called ProducerThread that extends Thread class and implements the run
method by adding in an infinite loop Integer objects into a global stack object. Write a
class called CosumerThread that extends Thread class and implements the run method
by popping from a global stack in an infinite loop. Write a class called
ProducerConsumerExample that create the 2 threads, both running infinitely and one
producing for the other to consume at its convenience.
4. Test Cases:
Test1:
Series of Integers 1, 2, 3, 4, …… being produced with a counter.
5. Reference Implementation:
####################################################################
File: ProducerThread.java
import java.util.*;
59
JAVA LAB MANUAL BIET
File: ConsumerThread.java
import java.util.*;
File: ProducerConsumerExample.java
import java.util.*;
60
JAVA LAB MANUAL BIET
consu.start();
}
}
####################################################################
6. Execution:
1. javac ProducerThread.java
2. javac ConsumerThread.java
3. javac ProducerConsumerExample.java
1. Problem Statement:
Write a Java program that illustrates how run time polymorphism is achieved.
2. Solution Design:
Write a simple class called MyParent which has a default constructor and a public
method called displayMessage which display a message indicating the message is coming
from an object of this class. Write another class called MyChild that inherits from
MyParent and overrides displayMessage() method to print a message indicating that the
object is of MyChild type. Now write a test class which has a main method in which we
create an ArrayList of MyParent type objects and add to it first an object of MyParent
type and then an object of MyChild type. To first see how JAVA’s runtime polymorphism
works, call the displayMessage method on each of the ArrayList objects. Than in another
loop use the JAVA Reflection API’s Classes Class, Object, Method to dynamically get the
type of the object in the ArrayList, get a method reference to displayMessage and
invoke the method on the obj in question with an object array with no elements as
arguments to this method.
4. Test Cases:
Test1:
ArrayList of Base Class Type MyParent populated with at-least 2 objects, one of
Base Class Type and the other of Derived Class Type. Java’s internal Runtime
polymorphism and our implementation of polymorphism should yield the same
result.
61
JAVA LAB MANUAL BIET
5. Reference Implementation:
####################################################################
File: MyParent.java
public class MyParent
{
public MyParent()
{
}
File: MyChild.java
public class MyChild extends MyParent
{
public MyChild()
{
super();
}
File: RuntimePolymorphismTest.java
import java.util.*;
import java.lang.reflect.*;
62
JAVA LAB MANUAL BIET
{
ArrayList<MyParent> lList = new ArrayList<MyParent>();
lList.add(new MyParent());
lList.add(new MyChild());
}
}
####################################################################
6. Execution:
1. javac MyParent.java
2. javac MyChild.java
63
JAVA LAB MANUAL BIET
3. javac RuntimePolymorphismTest.java
4. java RuntimePolymorphismTest
64