Step 2 - Java - MustDo - Exercises
Step 2 - Java - MustDo - Exercises
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! +…
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
Problems – 5
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.
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
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()
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.
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.
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.
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:
< <
> >
© (c)
" “
& &
' ‘
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 - 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.