0% found this document useful (0 votes)
85 views10 pages

Java Programming Exercises and Tutorials

The document provides 12 exercises involving writing Java programs to perform various tasks like inputting and displaying values, calculating values using loops and methods, working with arrays and matrices, and implementing classes and interfaces. The exercises include writing programs that input and output integers, display messages in a loop, calculate circle properties, count characters and words, convert decimals to binary, and perform operations on complex numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views10 pages

Java Programming Exercises and Tutorials

The document provides 12 exercises involving writing Java programs to perform various tasks like inputting and displaying values, calculating values using loops and methods, working with arrays and matrices, and implementing classes and interfaces. The exercises include writing programs that input and output integers, display messages in a loop, calculate circle properties, count characters and words, convert decimals to binary, and perform operations on complex numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Exercises
  • Solutions

Exercises

1. Write a program to keep inputting integer values until –1 is entered.


2. Write a program using a while loop to display a message 10 times. Each message
should be on a separate line using the following format with numbering starting from
1: A message
2: A message
3: A message
……
3. Write a program that inputs the radius of a circle and displays its circumference and
area. (use [Link] for π)
4. Write a program to read in a line of text as a String and output the number of
characters and words it contains. Spaces and tabs should not be counted as characters.
5. Write a program that reads a decimal integer and prints out its binary equivalent.
6. Write a program that counts the number of times a specified character appears in a line
of text.
7. Write a program that uses a recursive method to calculate the product of a sequence of
numbers specified by the user. For example, if the user specifies 4 to 8, the method
calculates 4*5*6*7*8.
8. Write a method to test if an integer of type long is a prime number. The method should
return a boolean.
9. Write a program to read in 10 integers and store them in an array. Then display the
contents of the array.
10. Write a program to read in a sequence of integers until ‘stop’ is entered. Store the
integers in an array. Then display the average of the numbers entered.
11. A matrix can be represented using a 2D array. Write methods to perform matrix
addition, subtraction and multiplication. Each method should take two 2D arrays as a
parameter and return a new 2D array containing the result. Use the methods in a test
program to verify that they work correctly.
12. Write a program to act as a simple address book, storing names and addresses in a data
file.
13. Create an implementation of the interface Queue that throws exceptions appropriately.
Declare any exception classes needed and write a test class

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
1
Exercise 1: (Complex numbers)
The purpose of this exercise is to define a class “CN” so that it can be used to
manipulate complex numbers.

Part A
Follow the specification below to define the class CN:
1. Attributes
CN contains two attributes “re” and “im” representing respectively the real and
imaginary parts of the complex number.

2. Constructors
CN contains a no-argument constructor (it sets re and im to zero), and a 2-argument
constructor having as parameters initial values of real and imaginary parts of the
complex number.

3. Methods
• getRe: returns the real part of the complex number.
• getImg: returns the imaginary part of the complex number.
• setRel and setImg: respectively modify the value of real and imaginary parts.
• add, multiply and subtract: to add, multiply or subtract two complex numbers.
• getModule: return the module of an instance of CN
• equals: Tests if two complex numbers are equal.(2 complex numbers are equal if
their real and imaginary parts are the same)
• clone: returns a copy of an instance of CN (the new copy will not share the same
reference with the original one).

Part B
Propose now a class TestCN with the main method to illustrate how to use the class CN
defined above.

Exercise 2:
Consider three classes A, B, and C. Assume that:
• B extends A, B and C implement the interface I,

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
2
• B overrides the method meth() of A,
• and B and C define a method fonc() of the interface I
For instructions (on the block S1) below, specify which version of method “meth” or “fonc”
is called.
S1
A a; B b; C c; I i;
a = new A();
a = b;
b = new B();
[Link](); (3)
c = new C();

i = b; [Link](); (4)
[Link](); (1)
i = c; [Link](); (5)
[Link](); (2)

Exercise 3: (Control flow)


1. Write a java program that reads a positive integer n, calculate and displays its
factorial.
2. Suppose now that the value of n is passed as argument to the main function. Write a
java program that prints out n!.

Exercise 4: (Method random() of [Link] ) ***


Write a program that simulates rolling a pair of dice. You can simulate rolling one die
by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents
the number on the die after it is rolled (Use the method random of [Link]. For

example, int n = (int)([Link]()*6)+1 returns a random interger between 1


and 6).
You can assign this value to a variable to represent one of the dice that are being
rolled. Do this twice and add the results together to get the total roll. Your program should
report the number showing on each die as well as the total roll.

For example:
The first die comes up 3
The second die comes up 5

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
3
Your total roll is 8

Exercise 5:
Write a program that asks the user’s name, and then greets the user by name. Before
outputting the user’s name, convert it to upper case letters. For example, if the user’s
name is Fred, then the program should respond “Hello, FRED, nice to meet you!”.

Exercise 6: (StringTonizer) **
Write a program that reads one line of input text and breaks it up into words. The words
should be output one per line. Assume that words are separated by the blank character “ ”. For
example, if the user inputs the line “Hello Word! I am a student”, the program prints:
Hello
Word!
I
am
a
student

Exercise 7:
Suppose that a file contains information about sales figures for a company in various cities.
Each line of the file contains a city name, followed by a colon (:) followed by the data for that
city. The data is a number of type double. However, for some cities, no data was available. In
these lines, the data is replaced by a comment explaining why the data is missing. For
example, several lines from the file might look like:
San Francisco: 19887.32
Chicago: no report received
New York: 298734.12
Write a program that will compute and print the total sales from all the cities together. The
program should also report the number of cities for which data was not available.
The name of the file is “[Link]”.

What output is produced by the following program segment? (Recall that [Link](i)is
the i-th character in the string, name.)

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
4
String name;
int i;
boolean startWord;
name = "Richard M. Nixon";
startWord = true;
for (i = 0; i < [Link](); i++) {
if (startWord)
[Link]([Link](i));
if ([Link](i) == ’ ’)
startWord = true;
else
startWord = false;
}

Exercise 8:
To “capitalize” a string means to change the first letter of each word in the string to upper
case (if it is not already upper case). For example, a capitalized version of “Now is the time to
act!” is “Now Is The Time To Act!”. Write a subroutine named printCapitalized that will
print a capitalized version of a string to standard output. The string to be printed should be a
parameter to the subroutine. Test your subroutine with a main() routine that gets a line of
input from the user and applies the subroutine to it. Note that a letter is the first letter of a
word if it is not immediately preceded in the string by another letter. Recall that there is a
standard boolean-valued function [Link](char) that can be used to test whether its
parameter is a letter. There is another standard char-valued function,
[Link](char), that returns a capitalized version of the single character passed
to it as a parameter. That is, if the parameter is a letter, it returns the upper-case version. If the
parameter is not a letter, it just returns a copy of the parameter.

Exercise 9

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
5
1. Define a class named Point, with two attributes x and y representing its coordinates. The
constructor of class Point takes as parameters, initial values of x and y (Point(int x_init, int
y_init). Its methods are described below:
- move(int dx, int dy) : this method adds dx to x and dy to y
- display() : Displays the point coordinates (x and y)
2. Suppose that your program must also manipulate colored points represented by a class
named PointCol Describes as follow:
- Class PointCol extends Point and has only one attribute color (representing the color
of its instances).
- Its constructor signature is PointCol(int x_init, int y_init, byte color).
- PointCol overrides the methods display() of its super class, to show its coordinates
and color .
Propose a definition of class PointCol.

3. Consider class TestPoint defined by:


Class TestPoint{
public static void main(String arg[]){
Point p = new Point(3, 2);
[Link](); (a)

PointCol pc = new PointCol(5, 5, (byte)3);


p = pc;
[Link](); (b)
}
}

What output is produced by instructions (a) and (b)?

Exercise 10:
The hexadecimal digits are the ordinary, base-10 digits ’0’through ’9’ plus the letters ’A’
through ’F’. In the hexadecimal system, these digits represent the values 0 through 15,
respectively. Write a function named hexValue that uses a switch statement to find the
hexadecimal value of a given character. The character is a parameter to the function, and its
hexadecimal value is the return value of the function. You should count lower case letters ’a’

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
6
through ’f’ as having the same value as the corresponding upper case letters. If the parameter
is not one of the legal hexadecimal digits, return -1 as the value of the function.

Exercise 11: ***


Write a program that displays a window containing a button labeled “Say Hello”. When the
user clicks on that button, the program displays the message “Hello World”.

Exercise 12:
Implement a program with this interface:

Clicking the buttons increments or decrements the displayed counter value.

Exercise 13:
Write a Swing program to display this window:

When the button is clicked, the text typed into the JTextField at the top of the window is
copied into the label in the middle of the window.

Exercise 14:
Implement a calculator program (using GUI)

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
7
Solutions

Exercise 1:
Part A
public class CN { //method substract
private double re; public CN subtract(CN c){
private double img; return new CN(re - [Link], img - [Link]);
}
//No-argument constructor //method multiply
public CN(){ public CN multiply(CN c){
re = 0; return new CN(re*[Link] + img*[Link],
img = 0; re*[Link] + img*[Link]);
} }
//2-arguments constructor
public CN(double re, double img){ //method getModule
[Link] = re; public double getModule(){
[Link] = img; return [Link](re*re + img*img);
} }

//Getter and Setter public boolean equals(CN c){


public double getRe(){ if((re == [Link]) && (img == [Link]))
return re; return true;
} else
public double getImg(){ return false;
return img; }
}
public void setRe(double re){ public CN clone(){
[Link] = re; return new CN(re, img);
} }
public void setImg(double img){ }
[Link] = img;
}
//method add
public CN add(CN c){
return new CN(re + [Link], img + [Link]);
}

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
8
Part B
public class TestCN {
public static void main(String arg[]){
CN c1 = new CN(0.5, 0.5);
CN c2 = new CN(1.5, 0.5 );
CN add = [Link](c2);
CN sub = [Link](c1);
[Link]("c1 + c2 = "+[Link]()+"+"+[Link]()+"i");
[Link]("c1 + c2 = "+[Link]()+"+"+[Link]()+"i");
}
}

Exercise 2
(1) This instruction calls the method “meth” of class A.
(2) This instruction calls the method “meth” of class B.
(3) It calls the method “meth” of class B.

(4) The method “fonc” of class B is called


(5) The method “fonc” of class C is called

Exercise 9
1. Class Point
class Point
{ private int x, y ;
public Point (int x, int y)
{
this.x = x ; this.y = y ;
}
public void move(int dx, int dy)
{
x += dx ; y += dy ;
}
public void display()
{
[Link] ("my position is " + x + " " + y) ;
}
}

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
9
2. Class PointCol
class Pointcol extends Point
{
private byte color ;
public Pointcol (int x, int y, byte color)
{
super (x, y) ; // must be the first instruction since the no-argument contrustor isn’t defined in
// the super class
[Link] = color ;
}
public void display()
{
super. display() ;
[Link] ("and my color is: " + color) ;
}
}

3. Instruction (a) will display:


my position is 3 2

(b) will display:


my position is 5 5
and my color is 3

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING
10

Common questions

Powered by AI

The class CN facilitates the manipulation and representation of complex numbers with its attributes ‘re’ and ‘im’, representing the real and imaginary parts respectively. The class provides constructors for initializing these attributes, and methods like ‘add’, ‘subtract’, and ‘multiply’ for arithmetic operations, allowing for encapsulated operations on complex numbers. Additional methods such as ‘getModule’ and ‘equals’ enable computation of the modulus and equality checks, enhancing utility and integration in mathematical computations .

Java constructors enhance program flexibility by providing multiple ways to instantiate objects with different initial states, as seen in the classes CN, Point, and PointCol. The constructors allow specific initialization of the object's state, enabling the creation of objects with default or customized values. For example, CN’s two-argument constructor allows initializing a complex number with specific real and imaginary parts, while PointCol's constructor allows setting coordinates and color. This flexibility supports diverse use cases and helps avoid errors from uninitialized fields .

The method "printCapitalized" leverages Java's standard functions, such as Character.isLetter() and Character.toUpperCase(), to identify word boundaries and convert the first letter of each word in a string to uppercase. This process transforms user input text into a standardized, capitalized format, improving the readability and aesthetic of text data and ensuring consistency across processed text. This is particularly useful for user interfaces requiring formal or uniform text presentation .

Implementing the "Queue" interface with exception handling increases the robustness of a Java program by ensuring that specific, predictable responses are executed when errors occur, such as attempts to dequeue from an empty queue or enqueue into a full one. Custom exceptions provide clear error messages and help isolate issues, making debugging and maintenance easier and protecting against unintended behavior .

Polymorphism is demonstrated in the example by the way classes B and C implement the interface I and class B extends class A while overriding methods. When the method 'meth' is called on an object referred to by a superclass reference that actually refers to an object of a subclass, the overridden method of the subclass is executed. Similarly, when the method ‘fonc’ from interface I is called, the version defined by B or C is executed depending on the actual object type. This allows methods to behave differently based on the object's runtime type, demonstrating polymorphism .

The methods add, subtract, and multiply in the class CN encapsulate the arithmetic logic required to perform operations on complex numbers, enforcing correctness and reducing errors. These methods provide reusable components, improving code modularity and offering a consistent interface for complex number operations. By isolating arithmetic operations within specific methods, the class allows for easy maintenance and unit testing, enhancing code reliability and efficiency when performing complex mathematical operations .

Method overriding in Java is central to achieving polymorphism, allowing subclasses to provide specific implementations of methods defined in a superclass or interfaces. In the scenario involving methods 'meth' and 'fonc', overriding enables class B to define its own version of 'meth', distinct from that in class A. Similarly, 'fonc' is implemented differently in classes B and C, even though both implement the same interface I. Such overriding ensures that the method executed corresponds to the actual object's class, not just its reference type, allowing dynamic method dispatch and increased flexibility in code design .

Exception handling is crucial in implementing interfaces like Queue because it provides a mechanism to gracefully handle exceptional circumstances that may arise, such as invalid operations like dequeuing from an empty queue. By defining specific exceptions and handling them appropriately, the implementation can ensure a robust, predictable response to errors, thus maintaining program stability and preventing crashes or undefined behavior. This is particularly crucial in concurrent or real-time systems where queue operations are frequent .

Using recursive methods for computing the product of a sequence of numbers offers conceptual simplicity, especially when implementing mathematical expressions that are naturally recursive. Recursion can reduce the need for explicit loops and additional control variables, thus enhancing readability and maintainability of the code. However, it may introduce overhead through stack memory usage and recursion depth limits, posing risks for very large sequences .

Using 2D array representation for matrix operations provides a structured approach to handle and iterate over matrices. This approach simplifies the implementation of addition, subtraction, and multiplication operations, as it aligns with mathematical matrix manipulation techniques. 2D arrays facilitate efficient storage and quick access to matrix elements during computation, enhance code clarity, and improve the scalability of handling matrices of any defined size .

IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
1 
Exercises 
1. Write a program to keep inputting integer values until –1 is enter
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
2 
Exercise 1: (Complex numbers) 
The purpose of this exercise is to define a class
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
3 
• B overrides the method meth() of A,  
• and B and C define a method fonc() of
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
4 
Your total roll is 8 
 
Exercise 5: 
Write a program that asks the user’s name,
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
5 
String name; 
int i; 
boolean startWord; 
name = "Richard M. Nixon"; 
startWord
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
6 
1. Define a class named Point, with two attributes x and y representing its coor
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
7 
through ’f’ as having the same value as the corresponding upper case letters. If
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
8 
Solutions 
 
Exercise 1: 
Part A 
public class CN { 
    private double re;
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
9 
Part B 
public class TestCN { 
    public static void main(String arg[]){
IUGET/2022-2023/HND/200/JAVA_PROGRAMMING 
10 
2. Class PointCol 
class Pointcol extends Point 
{  
private byte color ; 
 pub

You might also like