0% found this document useful (0 votes)
47 views15 pages

Step 2 - Java - MustDo - Exercises

learn java

Uploaded by

Priyanka Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
47 views15 pages

Step 2 - Java - MustDo - Exercises

learn java

Uploaded by

Priyanka Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Java Hands on | Must Do exercises for fresh brains

Java Fundamentals

Problems – 1

1. Write a program, which reads two, numbers and displays their sum.
2. Write a program, which reads two numbers and displays their product.
3. Write a program, which reads two numbers and displays the quotient obtained after dividing
the first number by the second.
4. Write a program, which reads the length and width of a rectangle and displays its area and
perimeter.
5. Write a program, which reads a two-digit integer number and calculates sum of its digits.
6. Write a program, which reads a three-digit integer number and calculates sum of its digits.
7. Write a program, which reads a 4-digit integer number and generates a new number in which
order of the digits is reversed.
8. Write a program to calculate the area and circumference of a given circle.

Problems – 2

1. Write a program which reads a number and displays suitable message indicating whether the
given number is odd or even;
2. Write a program to find the larger of the two given numbers.
3. Write a program to find the smaller of the two given numbers.
4. Write a program to find the largest of the three given numbers.
5. Write a program to find the smallest of the three given numbers.
6. Write a program to find the second largest of the three given numbers.
7. Write a program to calculate the DA for a given basic salary using following rules.
(i) BASIC <= 3500 THEN DA = 159% of BASIC SALARY.
(ii) BASIC > 3500 AND BASIC <= 6000 THEN DA = 159% of the 3500 or 119% of the
BASIC whichever is higher.
(iii) OTHERWISE DA = 119% OF 6000 or 103% of the BASIC whichever is higher.
8. Write a program to read a number and display an appropriate message displaying whether the
given number is positive, negative or zero.
9. Write a program to find the roots of a quadratic equation
ax 2 + bx + c = 0

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE -i-
Java Hands on | Must Do exercises for fresh brains

10. Write a program, which reads the three sides of a given triangle and calculates its area.
Note: Program should display appropriate message if the three given sides do not from a
triangle.
11. Write a program, which reads the three sides of a given triangle and checks whether it is an
isosceles triangle.
12. Write a program, which reads three sides of a given triangle and checks whether it is an
equilateral triangle.
13. Write a program, which reads three sides of a given triangle and checks whether it is a right–
angled triangle.

Problems – 3

1. Write a program, which reads two numbers and displays the result of exponentiation of the
first number by the second.
2. Write a program, which reads an integer number and calculates sum of its digits.
3. Write a program, which reads an integer number and generates a new number in which order
of the digits is reversed.
4. Write a program, which finds the factorial of a given number.
5. Write a program, which read a number and displays a suitable message indicating whether
the given number is an Armstrong number or not.
Note: A number is said to be Armstrong number if the sum of the cubes of its digits is equal
to the number itself (e.g. 371 = 33 + 73 + 13).
6. Write a program, which generates the N terms of the Fibonacci series.
7. Write a program, which checks whether a given number is prime or not and displays an
appropriate message.
8. Write a program to generate and find the sum of the following series up to N terms:
(A) 1 + 4 + 9 + 16 + ……………
(B) 4 + 12 + 36 + 108 +…………
(C) 1/2 - 2/3 + 3/4 - 4/5 + ………
(D) 4/1 – 4/3 + 4/7 – 4/13 +……….
(E) 1 + X + X2 + X3 +…
(F) 3 + 5 + 9 + 15 +…
(G) 1 – X2/2! + X4/4! – X6/6! +…
(H) X – X3/3! + X5/5! – X7/7! +…

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - ii -


Java Hands on | Must Do exercises for fresh brains

9. Write a program, which reads two integer numbers and displays their L.C.M.
10. Write a program, which reads two integer numbers and displays their H.C.F.
11. Write a program to generate the first N terms of a G.P. for which first term and common ratio
is known.
12. Write a program to generate the first N terms of an A.P. for which first term and the common
difference is known.
13. Write a program, which finds all the Armstrong numbers up to a given number.

Problems – 4

1. Write a program to read and write an array.


2. Write a program to find the sum and average of N given numbers.
3. Write a program to find the largest & smallest of the N given numbers.
4. Write a program, which looks for an element in a given array using linear search method.
5. Write a program, which looks for an element in a given sorted array using binary search
method.
6. Write a program, which finds the smallest and largest elements in an array and the
corresponding position.
7. Write a program to reverse the order of the elements of an array.
8. Write a program, which deletes an element whose position is specified from an array.
9. Write a program, which inserts a given element at a specific location in an array.
10. Write a program to sort the N given numbers using the selection sort method.
11. Write a program to sort the N given numbers using bubble sort method.

Problems – 5

1. Write a program to read and write a matrix.


2. Write a program, which reads two matrices and calculates their sum.
3. Write a program to find the transpose of a given matrix.
4. Write a program to fins the transpose of a given square matrix without using another matrix.
5. Write a program to find the smallest and largest element in a given matrix.
6. Write a program to calculate the sum of matrix row wise and column wise.
7. Write a program to multiply the two matrices.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - iii -
Java Hands on | Must Do exercises for fresh brains
Class Fundamentals
1. Write a class Math to implement the following simple arithmetic operations:
(a) Addition (b) Subtraction (c) Division, and (d) Multiplication
Note: All the methods must be static. Also make sure that it should not be possible to instantiate the
class.
2. Implement a class Complex, which should provide methods to perform the following operations on
complex numbers:
(a) Addition (b) Subtraction
Note: Implement using static as well as non-static (instance) methods. Decide whether
implementing all the methods as static would be a better alternative in this case.
3. Implement class Stack. The class should implement the following operations:
(i) void push(int x);
(ii) int pop();
(iii) int peek()
(iv) boolean isStackEmpty()
(v) boolean isStackFull()
(vi) void display()

Write a menu-driven program, which makes use of the Stack class to create the stack of the desired
size. The program should prompt the user to select the desired option and then take appropriate
action based on the user choice. The user should also be provided the exit option.
Note: Repeat the above problem with dynamic implementation of stack.
4. Implement class Queue. The class should implement the following operations:
(i) void add(int x);
(ii) int delete();
(vii) boolean isQueueEmpty()
(viii) boolean isQueueFull()
(ix) void display()

Write a menu-driven program, which makes use of the Queue class to create the queue of the desired
size. The program should prompt the user to select the desired option and then take appropriate
action based on the user choice. The user should also be provided the exit option.
Note: Repeat the above problem with dynamic implementation of queue.
5. Write a program to reverse a given array of numbers using a stack. The size of the stack should be
same as the number of elements in the array.
6. Write class “ThreeDimObject” and define overloaded methods named volume() to calculate the
volumes of various 3D-Objects (cube, cuboids, sphere and cylinder).
7. Write a class Account to represent bank account of a customer with the following data members:
Name of the depositor, account number, type of account (S for saving, C for current) & balance
amount and member methods/constructors to do the following: to initialize data members, to deposit
money, to withdraw money after checking the balance (minimum balance is Rs.1000) and to display
the data members. Write a program to create an array of Account objects to hold account details of
10 customers which would be read from the keyboard. Perform deposit and withdraw operations on
some of the accounts and then display the modified details.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - iv -


Java Hands on | Must Do exercises for fresh brains
Inheritance
1. Assume that a bank maintains two kinds of accounts for customers, one called as savings account
and the other as current account. The savings account provides compound interest and deposit,
withdraw facilities. The current account provides no interest. Current account holders should also
maintain a minimum balance and if the balance falls below this level, a service charge is imposed.
Create a class Account that stores customer name, account number and type of account. From this
drive the classes CurrAcct and SavAcct to make them more specific. Include necessary methods in
order to achieve the following tasks:
(a) Accept deposit from a customer and update the balance.
(b) Display the balance
(c) Compute the deposit interest
(d) Permit withdrawal and update the balance.
(e) Check for minimum balance, impose penalty, if necessary, and update the balance.

2. Write class Employee which should have constructors and methods as given below:
public Employee(String name, double salary, int year, int month, int day)
public String getName()
public double getSalary()
public Date getHireDate()
public void raiseSalary(double byPercent)

Define class Manager by extending class Employee. The manager also gets bonus in addition to
salary, so the class must have an extra method say setBonus(double bonus) to set the bonus. The
getSalary() method must be overridden in the manager class so as to compute salary as sum of base
salary and bonus. This method must make use of the super class method with the same name to get
the base salary and then add bonus to it.
Write a Java program to instantiate objects of classes Employee and Manager and store them in an
array of type Employee. The program must finally display the details of each employee.
3. Create the classes in the employee inheritance hierarchy as shown below:

Employee

SalariedEmployee CommissionEmployee HourlyEmployee

BasePlusCommissionEmployee

An employee should have a first name, last-name and social-security number. In addition, a
SalariedEmployee should have a weekly salary; an HourlyEmployee should have a wage and a
number of hours worked; a CommissionEmployee should have a commission rate and gross sales; and
a BasePlusCommissionEmployee should also have base salary. Each class must have appropriate
constructors, set methods and get methods. Also write a program that instantiates objects of each of
these classes and outputs all information associated with each object (including inherited information).

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE -v-
Java Hands on | Must Do exercises for fresh brains
4. Write a class Queue, which supports the following operations:
(i) void add(int x)
(ii) int delete()

After writing Queue class, write another class ExtQueue by sub-classing it and add the following
features:
(i) void display(); //to display the queue without modifying it
(ii) boolean isQueueEmpty()
(iii) boolean isQueueFull()

5. Write an inheritance hierarchy for class Quadrilateral, Trapezoidal, Parallelogram, Rectangle


and Square. Use Quadrilateral as the super-class of the hierarchy. Specify the instance variable and
methods for each class. The private data of Quadrilateral should be the x-y co-ordinate pairs for the
four end-points of the quadrilateral. Write a program that instantiates objects of your classes and
outputs each object’s area (except Quadrilateral).
6. Write a class Math to implement the following simple arithmetic operations:
(a) Addition (b) Subtraction (c) Division, and (d) Multiplication
Define another class TrigMath by extending the class Math and adding methods for trigonometrical
operations.
7. Implement a class Complex, which should provide methods to perform the following operations on
complex numbers:
(a) Addition (b) Subtraction
Define another class ComplexExt by extending the class Complex and adding methods for the following
operations: (i) Multiplication, and (ii) Division
8. Implement a class List to hold numbers. The class should support the following operations:
(a) void add(int x)
(b) boolean delete(int x)
(c) int delete(long index)
(d) void deleteAll()
(e) boolean search(int x)
(f) void insert(int x, int index)
(g) List sort()
(h) void append(int x)
(i) void display()
(j) int get(int index)
Note: Implement the static as well as linked-list implementation of the List class.
Extend the List class to implement class SortedList. You should override the methods of the List
class wherever possible so as to improve the performance. For example, the search method should be
over-ridden to make use of the fact that data is sorted. The SortedList class must have constructor to
accept List.
9. Implement class Date, which has three data members: (i) Year (ii) Month and (iii) Day. The class
must have appropriate constructors. The class must also have various methods for date manipulation.
Extend the above class to add three more data members: (i) hour (ii) minute, and (iii) second. This is
to store the time along with the date so as to represent exact point of time. Add extra methods to
manipulate both date and time.
Hint: You can make use of built-in classes to manipulate the date.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - vi -


Java Hands on | Must Do exercises for fresh brains
Packages
1. Modify the inheritance related problems so as both base class and child class are defined in separate
source files and have a package statement such that both classes belong to the same package.
2. Repeat as above but now the base class and child class should belong to different packages.

Interface
1. Define an interface QueueInt, with the following method declarations:
• void add(int x)
• int delete()
Write a class CircularQueue, which implements the above interface.

2. Extend the interface QueueInt defined in the previous question to define a new interface
ExtQueueInt by adding the following methods:
• void display(); //to display the queue without modifying it
• boolean isQueueEmpty()
• boolean isQueueFull()

3. Define a class, which implements the ExtQueueInt interface. You should make use of class
CircularQueue, which provides the partial implementation of the ExtQueueInt interface.

4. Define an interface Collection to hold numbers as follows:


interface Collection
{ boolean add(int x)
boolean delete(int x)
int delete(long index)
void deleteAll()
boolean search(int x)
boolean insert(int x, int index)
void append(int x)
void display()
int get(int index)
}
Implement interface Collection and derive classes List, SortedList, Set, SortedSet and ArrayList. The
class List must provide a linked-list implementation of the Collection interface. The class SortedList
must also provide the linked-list implementation but the elements must remain sorted after each
operation. The class Set must not allow duplicate elements. The SortedSet class should not allow
duplicate elements like Set class but the elements must be stored in sorted order so as to provide fast
search facility. The class ArrayList must internally use an array to hold numbers so that elements can
be accessed randomly. The internal array must shrink and grow automatically as the number of elements
increase and decrease.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - vii -
Java Hands on | Must Do exercises for fresh brains
Exception Handling
1. Write a method that accepts an array list of integers, an integer, and a subscript as parameters. It
should try to put the integer into the array list at the specified subscript, catching the exception
IndexOutOfBoundsException, should it be thrown. The method should return true if no exception is
thrown and false otherwise.
2. Write a method, Divide, that repeatedly prompts the user at the command line for two integers and
computes their quotient as long as the division generates as ArithmeticExcxeption. If no exception
occurs, the quotient should be returned.
3. Write a program that repeatedly prompts the user to enter a number at the command line. It stops
when a non-numeric value is read and returns the smallest number that was entered.
4. Write a main method that examines its command-line arguments, computes the sum of all of them
that are numbers and displays that sum on the command line.
5. Define a class StackEmptyException that is a checked exception.
6. Define a class StackFullException that defines an unchecked exception.
7. Modify the class Stack discussed earlier so as to handle the stackfull and stackempty conditions by
throwing StackEmptyException and StackFullException exceptions respectively. Write a program
that makes use of the Stack class and handles the above exceptions.
8. Write a program that computes and displays the factorial of a number specified on the command
line. It handles all possible user input errors with try/catch.

String and StringBuffer


1. Write and run a java program that inputs a person’s name in the form First Middle Last and then
prints it in the form Last First Middle.
2. Write a program that capitalizes a two-word name. For example, the input rakesh kedia would
produce the output Rakesh Kedia.
3. Write a method that accepts a string as a parameter and returns a copy of that same string, but in title
case – the first letter of every word is upper case and the other letters in lower case.
4. Write a method that accepts a string buffer parameter and modifies the string so that is in title case.
5. Write a method that tests whether a string is in title case. First break the string into an array of
strings delimited by white space using the split method, then test each substring with the matches
method using a regular expression that defines a word in title case.
6. Write a method that accepts a string parameter and returns a copy of that string with all the white
spaces removed.
7. Write a method that accepts a string buffer as a parameter and replaces all white space characters
with dashes.
8. Write a method that accepts a string, splits the string into substrings, and returns the array of
substrings. The delimiters should be any combination of spaces or commas. Use the
StringTokenizer class to accomplish the subdivision.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - viii -
Java Hands on | Must Do exercises for fresh brains
9. Read a line of text from the keyboard. Adjust the white space between words so that the whole line
is aligned left and right in a line width of 60 characters and print it out.
10. Write a program to convert a given number into words. For example, number 490 should result in
the output: four hundred ninety.
11. Write and execute a java program which makes use of a stack to reverse a string.
12. Write a program that reads names of persons from the keyboard, sorts them in ascending order and
then displays on the monitor.
13. Write an application that reads several lines of text from the keyboard and prints a table indicating
the number of occurrences of each letter of the alphabet in the text.
14. Write an application that reads several lines of text from the keyboard and prints a table indicating
the number of one-letter words, two-letter words, three-letter words, etc. appearing in the text.
15. Write an application that reads several lines of text from the keyboard and prints a table indicating
the number of occurrences of each different word in the text.

Object and Wrapper Class


1. Make the LinkedList class Cloneable such that the clone() method returns the new linked list using
deep cloning i.e. the modification in cloned list must not affect the original list and vice-versa.
2. Write your own wrapper class Integer, which can hold data of primitive type int. The class Integer
should also have method to convert the wrapper class object back to primitive. You should also
override the equals() so that it returns true if the contents of two different Integer objects are same.
Also override the hashCode() methods so that it returns same hashcode for the objects which are
treated equal by the equals() method.
3. Implement the LinkedList class to hold any type of numeric data. Write a program which reads
some numbers and stores them in the linked list. Finally compute and display sum of all the numbers
stored in the linked list.
4. Write a Java Program that converts the string “7845” to its binary, octal and hexadecimal
equivalents.
5. Write a program that converts the characters in the given character array to uppercase letters.
6. Implement the class Employee to store information about employee. Override the toString() method
so that employee’s information can be displayed just by displaying employee’s object i.e. by passing
an employee’s object in println() method of standard output stream.
7. Implement class HashTable to store key-value pairs. The key must be unique but the value may be
duplicate. For example, it can be used to store dictionary entries, where word is a key and its
meaning is value. The type of both key and value should be Object so that any data type can be
stored in hash table. The hash table should provide the following operations:
(a) Object put(Object key, Object value)
(b) Object get(Object key)
(c) Object[] keys()
(d) Object[] values()
(e) void display()
(f) Object delete(Object key)

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - ix -


Java Hands on | Must Do exercises for fresh brains
Threads
1. Write a program that displays the name of the thread that executes main.
2. Write a Java program to demonstrate that as a high-priority thread executes, it will delay the
execution of all lower priority threads.
3. If your system supports time-slicing, write a java program that demonstrates time-slicing among
several equal-priority threads. Also show that a lower priority thread’s execution is deferred by the
time-slicing of higher priority threads.
4. Write a java program that demonstrates a high priority thread using sleep to give lower priority
threads a chance to run.
5. Write a java program that reads numbers from keyboard in two arrays say a and b. The program
should create one thread for sorting each array. The main thread should block till both the treads
complete sorting and then merge the two sorted arrays and finally should display merged array on
the output stream.
Hint: Make use of join() method to block the main thread till both the sort threads complete.
6. Solve the previous problem by using isAlive() method instead of join() method.
7. Write a class whose objects hold a current value and have a method that will add to the value. Write
a program that creates such an object, creates multiple threads, and invokes the adding method
repeatedly from each thread. Write the class so that no addition can be lost.
8. Modify the previous problem to use static data and methods.
9. Write a java program which creates instance of Stack class and creates two threads to concurrently
access the same stack. Demonstrate that the concurrent operations may lead to inconsistency.
Modify the Stack class to ensure that the concurrent operations do not lead to inconsistency.
10. A bank account is operated by a father and his son. The account is opened with an initial deposit of
Rs. 1000. The father and son can access the account concurrently. Create two threads for performing
transactions on the bank account one for father and one for son. Demonstrate that the concurrent
operations may lead to inconsistency. Then make appropriate modifications to ensure that the
concurrent operations do not lead to inconsistency.
11. Write a java program which creates two threads Producer and Consumer to access a common
circular queue of size n. The producer thread puts numbers in the queue starting from one. The
producer thread continues to put numbers in the queue as soon as it gets chance. It gives up control
when its time slice is over or queue becomes full and ensures that consumer thread can now start
processing. The consumer thread reads numbers from the queue and displays on the output stream
whenever it gets chance. The consumer thread continues till its time slice is over or queue becomes
empty and ensures that producer thread can start processing as soon as consumer thread gives up
control.
12. Modify the above program so that it works correctly even when there are two or more producers and
two or more consumers.
13. Write a class ThreadSafeIntList which can hold a growable list of primitive int values, suitable for
use with multiple threads. The class should be thread safe i.e. if an object of this class is accessed by
multiple threads its state should not become inconsistent.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE -x-
Java Hands on | Must Do exercises for fresh brains
Input/Output
1. Write a Java Program that finds the largest file in the given directory.
2. Write a Java Program that lists the file name, its size and the last modified date for all the files in the
specified directory just like the dir command of DOS.
3. Write a program that accepts names of input & output text files as command-line arguments, and
copies the input file to the output file, converting all letters to the uppercase. The input file should be
read using BufferedReader stream and contents to output file should be written using PrintWriter
stream.
4. Write a program to input the Name, Sex, Height and Weight of n persons from the keyboard and
store them in a file “height.dat”.
5. Write a java program to read the file “height.dat” created in the above program and display on the
monitor.
6. Modify the above program so as to display the output sorted in ascending order of names.
7. A set of double values are stored in two different files file1.dat and file2.dat. Write a java
program to read these files and find the average of the values.
8. A list containing the following details is given:
Name : String
Marks1 : int
Marks2 : int
Marks3 : int
Write a class to describe the above fields. Create objects for 5 sets of values and store the data in a
file “result.dat” using ObjectOutputStream class.
9. Read the file “result.dat” created in the above program and display the data.
10. Write a program to count the number of characters, words and lines in a given file. The file name is
to be given through the command line argument.
11. Write a program to read a text file, “input.dat”, and replace the following HTML entities with their
textual values as shown in the following table:
&lt; <
&gt; >
&copy; (c)
&quot; “
&amp; &
&apos; ‘
12. Write and execute an interactive java program to do following operations on a binary file.
• Store the student’s records.
• Display all records
• Search for a student’s record with a given roll no.
13. A random access file contains int type data. Write a java program to read the 1st, 5th and 9th values.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - xi -


Java Hands on | Must Do exercises for fresh brains
14. Write a program that reads a specified file and searches for a specified word, printing all the lines on
which that word is found, preceded by the line’s number.
Hint: Use LineNumberReader stream class.
15. Using FileNameFilter or FileFilter, write a program that takes a directory and suffix as parameters
and prints all files that have that suffix.
16. Write a program named Head that prints out the first 10 lines of each file specified on the command
line.
17. Write a program named Tail that prints out the last 10 lines of each file specified on the command
line.
18. Write a program that adds up and reports the size of all the files in a specified directory. It should
recursively scan any subdirectories, summing and reporting the size of the files that they contain.
19. Write a program to compress a given file and store the compressed output in another file. You can
make use of GZipOutputStream.
20. Write a program to uncompress a given compressed file and store the uncompressed output in
another file. You can make use of GZipInputStream.
21. Write a program to compress a given directory and store it in a file. You can make use of
ZipOutputStream and ZipEntry classes.
22. Write a program to decompress a directory stored in a file and create the original directory hierarchy.
You can make use of ZipInputStream class.
23. Write a Java program that takes a list of filenames on the command line and prints out the number of
lines in each file. The program should create one thread for each file and use these threads to count
the lines in all the files at the same time. Use java.io.LineNumberReader to help you count lines.
You’ll probably want to define a LineCounter class that extends Thread or implements Runnable.
Now write a variant of your program that uses your LineCounter class to read the files sequentially,
rather than at the same time. Compare the performance of the multi-threaded and single-threaded
programs, using System.currentTimeMillis() to determine elapsed time. Compare the performance of
the two programs for two, five, and ten files.
24. Write a class Account to represent bank account of a customer with the following data members:
Name of the depositor, account number, type of account (S for saving, C for current) & balance
amount and member methods/constructors to do the following: to initialize data members, to deposit
money, to withdraw money after checking the balance (minimum balance is Rs.1000) and to display
the data members. Write a program to read details of some customer’s accounts from the keyboard
and store then in a file named “Account.dat”. Perform deposit and withdraw operations on some of
the accounts and update the corresponding entries in the file “Account.dat”. Finally display the
updated details.
25. Write a program to create a sequential file that could store details about five products. Details
include product code, cost, and number of items available and are provided through the keyboard.
26. Rewrite the above program using a random access file. Add some more products and update some
existing products.
27. Write a program that will print details of the alternate products stored in the random access file
created in the above program.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - xii -
Java Hands on | Must Do exercises for fresh brains
Collection and Map Classes

1. Write a program that reads in a series of first names and stores them in a LinkedList. Do not store
duplicate names. Allow the user to search for a first name.
2. Write a program to count the number of occurrences of each word in a given string.
3. Modify the above program to count the number of occurrences of each letter rather than of each
word.
4. Write a program that determines and prints the number of duplicate words in a sentence. Treat
uppercase and lowercase letters the same.
5. Write a program that uses a StringTokenizer to tokenize a line of text input by the user and places
each token in a sorted tree. Print the elements of the sorted tree.
6. Write a program which reads names and marks of students from the keyboard and stores them in a
hash table. The program then displays the name and marks on the monitor. The user then gets
choices for adding more entries, updating existing entries, deleting wrong entries and for exiting
after displaying final list and storing final list in a file.
7. Modify the above program so that students records are always sorted in the descending order of
marks.
8. A properties file contains pairs of person name and phone numbers. It is assumed that person name
is unique and acts as a key. Write a java program to read the contents of the file in a Properties
object. The program then provides a menu of choices to the user to perform following operations:
(a) Adding a new entry
(b) Deleting an existing entry
(c) Updating an existing entry
(d) Searching
(e) Updating the properties file so as to reflect the current status, and
(f) Exiting
9. Write a program which reads student’s records from keyboard. Each record consists of roll no, name
and marks in 3 subjects. Store the records in an object of class TreeMap. The roll no. should be used
as a key and value should be an object containing student’s details. The students’ records should be
added such that they remain sorted on total marks. Finally display the students’ records.
10. Write a program to read key-value pairs of words and their meanings from a properties file and store
in a properties table. The program then should prompts the user to enter a word and should either
display the word’s meaning or a message indicating that word is not present in the dictionary.
11. Write a program to count number of unique words in a given string by making use of TreeSet class.
12. Store few names in a Vector and then display them using all different possible ways of iterating
collection elements.
13. Store few key-value pairs in a hash table and then display them using all different possible ways of
iterating map/dictionary elements.
14. Store few names in an object of class TreeSet. The names should be sorted in alphabetical order
ignoring the case.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - xiii -
Java Hands on | Must Do exercises for fresh brains
AWT (Abstract Windows Toolkit)
1. Write an applet that displays your name and keeps on scrolling it like marquee tag.
2. Write an applet that has two text fields for entering floating point numbers. The applet also has an
uneditable text field to display the result. It has four buttons labeled Add, Multiply, Subtract and
Divide. Clicking on a button performs the corresponding arithmetic operation on the two floating
point numbers and the result is displayed in the result text field.
3. Write an applet that calculates the squares and cubes of the numbers from 0 to 10 and draws the
resulting values in table format as shown below.
Number Square Cube
0 0 0
1 1 1
2 4 8
3 9 27
. . .
. . .
10 100 1000
4. Write applets to draw the following shapes:
(a) Cone
(b) Cylinder
(c) Cube
(d) Square inside a circle
(e) Circle inside a square
5. Write a method that accepts a text field as a parameter and determines whether the string contained
in that text field is an integer.
6. Write a program that displays a window containing two text fields and a button, arranged vertically
with the button in the middle. The top text field should be editable, the bottom should not. When the
button is pressed, the square root of the value in the top text field should be displayed in the bottom
one. Use the method developed in the above exercise to verify that the top text field contains an
integer.
7. Write a program that displays a ten-by-ten grid of editable text fields. To the right of each row and
below each column is an uneditable text field. Below the text fields is a button labeled “Compute”.
When the button is pressed, the sum of each row is displayed in the uneditable text field to the right
of that row. Similarly the sum of each column is displayed in the uneditable text field below each
column. Empty text fields are treated as though they contain zero. An error message is displayed if
any text field contains nonnumeric text.
8. Create the simple calculator GUI which just contains buttons labeled 0 to 9, four button for
arithmetic operation (+, -, /, *), one button labeled “.” (dot) and one button labeled “=” . The GUI
should also provide a text field, to display the numbers typed by the user and for displaying results.
You do not have to provide any functionality.
9. Make the calculator GUI created in the above exercise, functional, by adding event handling.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - xiv -
Java Hands on | Must Do exercises for fresh brains
10. Design a login screen which has two text fields for accepting username and password and a submit
button. First row should contain label “Username:” followed by a text field for accepting username.
The second row should contain label “Password:” followed by a text field for accepting password.
The third row should contain submit button, which should be centered. The frame displaying login
screen should not be resizable.
11. Create GUI for a scientific calculator. You can have a look at the calculator available as windows
accessories. The next step is to make it functional.
12. Develop a simple Catch Me application. Display a button or any appropriate component labeled
“Catch Me”. Try to move the mouse so that mouse pointer moves inside the component labeled
“Catch Me”. You should never be able to catch the component. The component should move to a
different random location as soon as mouse pointer reaches at its boundary.
13. Develop a simple text editor like notepad.
14. Write a program that implements a tic-tac-toe game. The interface should consist of a three-by-three
grid of buttons, initially without labels. When an unlabeled button is pressed it is labeled alternately
with an X label or an O label. Pressing already labeled buttons has no effect. The program terminates
when any row, column, or diagonal contains all X’s or O’s. In this case, the winner is announced. It
also terminates when all buttons are labeled. A tie is announced in that case.
15. Write a program to generate the magic square of size n. A magic square is a two dimensional array
with the n rows and n columns that satisfy the following properties:
• The numbers 1 to n2 each appear once in some cell of the magic square.
• The numbers in every row add to n(n2 + 1)/2.
• The numbers in every column add to n(n2 + 1)/2.
• The numbers in both diagonals add to n(n2 + 1)/2.
The number of rows and columns, n, must be at least three. After generating magic square check
whether it meets the above requirements.
The magic square of size 3 is as follows:

8 1 6
3 5 7
4 9 2

16. Develop a simple painting application like Paint Brush. You should be able to draw different shapes
as well as well as do freehand sketching by moving and dragging mouse. The action taken on
moving/dragging mouse depends on the current mode which can be any one of the following:
(a) Line Drawing Mode
(b) Pencil for freehand sketching
(c) Rectangle for drawing rectangle and square
(d) Oval for drawing ellipse and circle
Besides drawing mode the application should provide a choice box for selecting the current drawing
color.

Prepared By - Sumit Agrawal | Technical Architect | HCL MCC Retail COE - xv -

You might also like