You are on page 1of 8

Java Lab Exercise

LAB 1 (Arrays and Control Structures)


1. Concatenate two strings and display the result
2. Write a Java program to create a jagged array to store the following pattern
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
Display the jagged array using for-each style for loop.
3. Write a program to accept two integers as command line parameters and print
their sum and average. If parameters are few (less than 2), then display the
usage syntax for the program (java Sum number1 number2) and quit.
4. Modify the above program to show an error message if parameter is not an
integer (Use try-catch).
5. Declare an integer, a byte and a double variable. Do type conversion and display
result.
6. Write a program to add and multiply 2 matrices.
7. Write a program that prints the average of 5 random numbers.
8. Write a program that generates a random integer N in the range 0 to 10 and
then tabulate the tangent function for n equally spaced value for x in the range 0
to 1/2 use the constant Math.PI and Math.tan() method.
9. Write an application that calculates the number of days from a given date
begin of the year.

to

10. A popular children's song goes like this:


1 man went to mow, went to mow a meadow,
1 man and his dog went to mow a meadow.
2 men went to mow, went to mow a meadow,
2 men, 1 man and his dog, went to mow a meadow.
3 men went to mow, went to mow a meadow,
3 men, 2 men, 1 man and his dog, went to mow a meadow.
Etc.
Write a program that will print this song. Store the number of men in a variable
and make sure that your program can handle any number of verses. Test it by
changing the number of men. Try printing out 100 men went to mow.
HINT - you will need nested loops for this (i.e. a loop inside a loop), and don't
forget your grammar (it is 2 men but 1 man)!!

LAB 2(Object Arrays and Methods)


1. Define a class student with three data members name (string type), roll no (int) and
mark (int) check status of student whether he is passed or not. For a pass one
should have marks >=50 for first class marks>=60 ,distinction marks>=75.check
marks and print status with name and roll number. Store the student details in an
array.
2. Define a class Clock with three private integer data members hour, min and sec.
Define a no argument constructor to initialize time value to 12:00:00. Define a three
argument constructor to initialize the time.
Define a methods to
a. Increment time to next second.
b. Display the time value.
c. Return the hour (int getHour())
d. Return the minute (int getMinute())
e. Return the seconds (int getSeconds())
f.

Compare two Clock objects (int compareTo(Clock clock))


example :clock1.compareTo(clock2)
return 1 if first time is bigger, 0 if both are equal, else return 1

Write a program to create two Clock objects and test the methods.
3. Design a class to represent a Bank account with the following members (name of the
depositor, account number, type of account, balance amount). Include necessary
constructor and methods to deposit an amount, withdraw amount after checking
balance and to display name and balance.
4. Write an application to display the current date. Also find new date by adding 10
months to the current date. (Hint : use java.util.Calendar class)
5. Write a java program to sort the numbers, which are randomly generated. Use the
static method sort (double []) from java.util.Arrays class for sorting and display the
sorted list using another method.
6. Write a "day calculator". This should prompt for the current day of the week (i.e. an
integer from 0 to 6 representing Sunday to Saturday), and it should then prompt for
any number of days in the future (also an integer) and display the result. The output
might look something like the following:
Day Calculator
Enter the day (integer): 3
Enter the number of days to add: 9

Today is Wednesday, in 9 days time it will be Friday

LAB 3 (Inheritance, Abstract Classes and Interfaces)


1. Define a class Staff with protected data members
staffId, salary, staffName
Derive class Faculty from Staff and include properties and methods regarding faculty.

Include a parameterized constructor and use super to initialize the base class
members.
2. Create an abstract class Student that has data member rollNum and methods
setRollNum(int ) and getRollNum() and contains abstract method show(). Derive
class Test from Student which has two data members of type float (mark1 and
mark2) and methods called setMarks(float, float) and getMarks(). Class Test must
override show() method.
3. Assume the bank maintain two types of accounts for customer, one is called saving
account and the other is current account .the saving account provides compound
interest and withdrawal facilities but no cheque book facility. The current account
provides chequebook facility but no interest. Current account holders should also
maintain a minimum balance falls below this, a service charge is imposed. Create a
class Account that stores customer name, account number and account type. From
this, derive two classes CurrentAccount and SavingsAccount to make them more
specific requirements. Include necessary methods in order to achieve following tasks
a.
b.
c.
d.
e.
f.

Accept deposit from the customer and update the balance


Display the balance
Compute and deposit interest.
Permit withdrawal and update balance
Check the minimum balance, impose penalty, if necessary update the
balance
Use constructors to initialize class members for the three classes

4. Create an interface Area having a method compute .Use this interface to find the
area of rectangle and circle. Create separate class for shapes circle and rectangle,
both implements Area.
5. Create a package called homepack. Create two classes called Expenditure and
Income and include them in homepack. The Expenditure class has data-members
food, clothing, educational expenses etc. The Income class has data-members
salary, allowance and rent. Create a class Budget (outside of the package) which
uses classes of the packages to calculate saving of the family.
LAB 4( Exception Handling and Multithreading)
1. Define
checked
exception
classes
NoSufficientAmountException
and
NegativeAmountException. Create a class to encapsulate a bank Account. The
withdraw method throws NoSufficientAmountException if balance is not sufficient for
withdrawal. The deposit method should throw a NegativeAmountException if an
amount less than 0 is passed into it. Write a Bank application, which makes use of
the Account class. The program should handle the exceptions effectively.
2. Create an unchecked user-defined exception, which is to be generated

whenever the user inputs the string Hello.


3. Create a thread, which finds the number of semicolons contained in a file. Start two
instances of the thread from main to count the semicolons in two different files. The
main thread should stop only after the two child threads finish (use join). Display the
counts obtained.

4. Try the following example and make necessary modification so that makeDrink()
works for only one customer at a time. Only after serving first customer it should
consider another one. Also make necessary modifications to set different priorities for
the customer threads. Execute the program and see the order in which they are
served.
/*This class simulates a Hotel where the Customers are considered as threads. Each
customer is given the reference of a JuiceStall from where he can call makeDrink to
prepare the juice he like.*/
//The JuiceStall
class JuiceStall{
void makeDrink(String item){
System.out.println("[Started making\t"+item);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("\t"+item+"is ready]");
}
}
//The Customer
class Customer implements Runnable{
Thread service;
String item;
JuiceStall juice;
Customer(JuiceStall juice, String item){
this.juice=juice;
this.item=item;
service = new Thread(this);
service.start();
}
public void run(){
juice.makeDrink(item);
}
}
//The Hotel
class Hotel{
public static void main(String arg[]){
JuiceStall juice = new JuiceStall();
Customer c1 = new Customer(juice,"Lemon juice");
Customer c2 = new Customer(juice,"Orange juice");
Customer c3 = new Customer(juice,"Grape juice");
try{
c1.service.join();
c2.service.join();
c3.service.join();
}catch(InterruptedException e) {

}
}

LAB 5 (String Handling and Other classes in java.lang package)


1. Write the code to extract the class name and name of the last level package from the
following string
java.lang.reflect.Method
2. Extract the protocol, domain name and the resource name from the following URL
http://www.myweb.com/index.html
3. Write a java program that inputs a person name in the form First Middle Last and
then prints it in the form Last First M., where M is the persons middle initial.
For example, for the input
William Jefferson Clinton
output:
Clinton, William J.
4. Write and run a java program that capitalizes a two-word name.
For example, the input
north CARolina
would produce the output
North Carolina
5. Write a program to accept an integer as input and display its Binary, Octal and
Hexadecimal equivalents. (Use methods from wrapper class)
6. Write a program to start Notepad as a sub process. The program should wait for
Notepad to quit.
7. Write a Java program to start a C++ program (containing a simple while loop to print
a to z) as a sub process. The program should read and display the characters
printed by the C++ program.
8. Write a program to load a class using forName() method and find the following
a. The list of methods in the class
b. The list of interfaces that are implemented by the class.
c. The package that the class belongs to.

LAB 6 ( Collections Framework)


1. Create a Product class with data members productID, productName and price.
Include a parameterized constructor and setter and getter methods for each data
members. Also override toString() to return a string which describes the product.
Create an ArrayList object and add different products into it. Obtain an iterator from
the collection. Use the iterator to show each product in the list. While iterating, if a
product with a specified ID is found (say 105), remove it from the collection.
2. Modify the above program to use TreeSet. Implement Comparator interface to make
the products sorted in the order of their price.
3. Do program 1 using Vector. Obtain the first and last object in the collection. Use
Enumeration to list all products in the collection.

4. Write a program to list the system properties to the console. Find the name of current
user and java version. Also store the system properties list into a file.
5. Use HashMap to map names to account balances. Put five pairs into the collection.
Use Map.Entry to get the key and value of each pair in the collection. Also update the
account balance of a specified person.
LAB 7 ( I/O streams )
1. Write a program to delete all files with extension .txt from the U:\home directory.
2. Write an application to search for a file in a directory tree (use recursive function).
3. Write an application to append the contents of one file to another.
4. Write a program to accept n products and save the objects into a file. Read the
objects back and display.
5. Write a program to read and show the contents of three different files as a sequence.
6. Modify the above program to work with three different byte arrays.
7. Modify program 3 using character oriented stream classes.
8. Use PrintStream to write line by line output to a file (Hint: use println() method).
LAB 8 ( Applet and AWT and Swing )
1. Write an applet, which will show the contents of file located in its code base in a text
area.
2. Create a scrolling banner applet. When mouse is pressed on it, scrolling stops and
when mouse is released, start scrolling. The text to scroll is given as parameter to
the applet.
3. Create 3 horizontal scrollbars each for the colours Red, Green and Blue with value 0
to 255. Change the fill colour of an oval, when scroll bars are adjusted.
4. Create an image viewer applet with Next and Previous buttons. The applet should
show the images from a directory located at its code base.
5. Rewrite the above programs to incorporate Swing.
LAB 9 ( JDBC )
1. Create a database in MS Access, containing a single table. The schema of the table
is shown below:
StudentID
number
StudentName
text
Age
number
Mothertounge
text
Write a java program to list out ID and Name of all the students whose mother
tongue is Hindi and whose age is less than 15. Assume that the database is on the
local machine (use JDBC-ODBC bridge).
2. Write a java program using type-4 driver for Oracle, to insert records into the
following table in Oracle.

Employee
EmployeeID
EmployeeName
Date_of_birth
Department

number(5) primary key


varchar2(20)
Date
varchar2(20)

3. Rewrite the above program using OracleDataSource class.


4. Create an application (Swing), which displays the records one by one in a frame.
Use Text Fields to show each field value. The frame must contain Next, Previous
and Goto buttons to navigate the records.
5. Create a GUI application using Swing to manage the student records of an
institution.
LAB 10 (RMI)
1. Write a program to obtain the date of a server machine.
2. Write a program to send a message given by a client to a server. Store the message
in a file located on the server.
3. Write a client program, which sends a userid to a server. The server checks whether
the given id is valid or not and returns a boolean value.
4. Write an application to implement the following
Product objects are sent to the server. Server receives the product and writes it into
a database.
LAB 11 (Servlet)
1. Write a Servlet, which accepts a register number, entered from an HTML form and
displays the mark status as a table.
2. Write a Servlet program to display the contents of a text file residing on the server
machine, in the display window of your browser.
3. An image file is stored in the server machine as a jpeg file. Write a Servlet program
to display this browsers display window.
4. Methods in Cookie class allow you to create and add cookies into your HTTP
response. Write a Servlet program to create and add a cookie by name My Cookie
and value Servlet programming.
Create an HTML form to accept cookie value from a text filed.
The Servlet prints the cookies name and value in browsers display window.

LAB 12 (JSP)
1.

Write a JSP to output the values returned by System.getProperty for various


system properties such as java.version, java.home, os.name, user.name, user.home,
user.dir etc.
2.
Write a JSP to output the entire line, "Hello! The time is now ..." but use a
scriptlet for the complete string(print the time), including the HTML tags.

3.

Write a JSP to output all the values returned by System.getProperties with


"<BR>" embedded after each property name and value. Do not output the "<BR>"
using the "out" variable

4.

Write a JSP to do either a forward or an include, depending upon a boolean


variable (hint: The concepts of mixing HTML and scriptlets work with JSP tags also!)

5.

Write a JSP/HTML set that allows a user to enter the name of a system property,
and then displays the value returned by System.getProperty for that property name
(handle errors appripriately.) 2) Go back to the exercises where you manually
modified boolean variables. Instead of a boolean variable, make these come from a
HIDDEN form field that can be set to true or false.

6.

Read your application server's documentation and add login/password protection


to some of your JSPs

7.

Design an application using JSP and Beans to collect name and phone number,
and display all entered names and phone numbers in another page.

You might also like