Java New Syllabus
Java New Syllabus
I Semester: AE / ME / CE / ECE / EEE / CSE / CSE (AI & ML) / CSE (DS) / CSE (CS) / IT
Course Code Category Hours / Week Credits Maximum Marks
L T P C CIA SEE Total
ACSD01 Foundation
3 0 0 3 40 60 100
Contact Classes: 48 Tutorial Classes: Nil Practical Classes: Nil Total Classes: 48
Prerequisites: There are no prerequisites to take this course.
I. COURSE OVERVIEW:
This course introduces the core principles of Object Oriented Programming (OOP), including encapsulation,
inheritance, polymorphism, and abstraction and design modular, maintainable software solutions while harnessing
the power of OOP's structured approach. By the end of the course, the skills needed to create adaptable, scalable,
and efficient codebases using object-oriented techniques to solve real time problems.
V. TEXTBOOKS:
1. Matt Weisfeld, The Object-Oriented Thought Process, Addison Wesley Object Technology Series,
4th Edition, 2013.
I Semester: AE / ME / CE / ECE / EEE / CSE / CSE (AI & ML) / CSE (DS) / CSE (CS) / IT
Course Code Category Hours / Week Credits Maximum Marks
L T P C CIA SEE Total
ACSD02 Foundation
0 1 2 2 40 60 100
Contact Classes: 15 Tutorial Classes: NIL Practical Classes: 30 Total Classes: 45
Prerequisite: There are no prerequisites to take this course.
I. COURSE OVERVIEW:
This course provides students with hands-on experience in developing Java programs. It covers the fundamental
concepts of object-oriented programming in Java that includes classes, objects, methods, inheritance, and
polymorphism. Students will also learn how to use the Java development environment. This course enables the
students to pursue career in software development.
Note: Students are encouraged to bring their own laptops for laboratory
practice sessions.
Hints
Use >= for greater than or equal to comparison.
/* Trying if-else statement.
*/
public class CheckPassFail { // Save as "CheckPassFail.java"
public static void main(String[] args) { // Program entry point
int mark = 49; // Set the value of "mark" here!
System.out.println("The mark is " + mark);
// if-else statement
if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
System.out.println( ...... );
}
}
Try
Take note of the source-code indentation!!! Whenever you open a block with '{', indent all the
statements inside the block by 3 (or 4 spaces). When the block ends, un-indent the closing '}' to align
with the opening statement.
Hints
n is an even number if (n % 2) is 0; otherwise, it is an odd number. Use == for comparison, e.g., (n %
2) == 0.
/**
* Trying if-else statement and modulus (%) operator.
*/
public class CheckOddEven { // Save as "CheckOddEven.java"
public static void main(String[] args) { // Program entry point
int number = 49; // Set the value of "number" here!
System.out.println("The number is " + number);
if ( ...... ) {
System.out.println( ...... ); // even number
} else {
System.out.println( ...... ); // odd number
}
System.out.println( ...... );
}
}
Try
Again, take note of the source-code indentation! Make it a good habit to ident your code properly, for
ease of reading your program.
Hints
/**
* Trying nested-if and switch-case statements.
*/
public class PrintNumberInWord { // Save as "PrintNumberInWord.java"
public static void main(String[] args) {
int number = 5; // Set the value of "number" here!
// Using nested-if
if (number == 1) { // Use == for comparison
System.out.println( ...... );
} else if ( ...... ) {
......
} else if ( ...... ) {
......
......
......
} else {
......
}
// Using switch-case-default
switch(number) {
case 1:
System.out.println( ...... ); break; // Don't forget the "break" after
each case!
case 2:
System.out.println( ...... ); break;
......
......
default: System.out.println( ...... );
}
}
}
Try
number = 0, 1, 2, 3, ..., 9, 10 and verify your results.
Try
Hints
/**
* Compute the sum and average of running integers from a lowerbound to an upperbound
using loop.
*/
public class SumAverageRunningInt { // Save as "SumAverageRunningInt.java"
public static void main (String[] args) {
// Define variables
int sum = 0; // The accumulated sum, init to 0
double average; // average in double
final int LOWERBOUND = 1;
final int UPPERBOUND = 100;
int sum = 0;
int number = LOWERBOUND; // declare and init loop index variable
while (number <= UPPERBOUND) { // test
sum += number;
++number; // update
}
2. Modify the program using do-while loop
int sum = 0;
int number = LOWERBOUND; // declare and init loop index variable
do {
sum += number;
++number; // update
} while (number <= UPPERBOUND); // test
3. What is the difference between "for" and "while-do" loops? What is the difference between "while-
do" and "do-while" loops?
4. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable
called count to count the numbers in the specified range (to be used in computing the average).
5. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 +
2*2 + 3*3 + ... + 100*100.
6. Modify the program to produce two sums: sum of odd numbers and sum of even numbers
from 1 to 100. Also computer their absolute difference.
Try
1. Compute the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product
obtained and decide if the results are correct.
Hints
/**
* Compute the sum of harmonics series from left-to-right and right-to-left.
*/
public class HarmonicSum { // Save as "HarmonicSum.java"
public static void main (String[] args) {
// Define variables
final int MAX_DENOMINATOR = 50000; // Use a more meaningful name instead of
n
double sumL2R = 0.0; // Sum from left-to-right
double sumR2L = 0.0; // Sum from right-to-left
double absDiff; // Absolute difference between the two sums
Hints
Add to sum if the denominator % 4 is 1, and subtract from sum if it is 3.
Try
1. Instead of using maximum denominator as the terminating condition, rewrite your program to use
the maximum number of terms (MAX_TERM) as the terminating condition.
Hints
public class CozaLozaWoza { // Save as "CozaLozaWoza.java"
public static void main(String[] args) {
final int LOWERBOUND = 1, UPPERBOUND = 110;
for (int number = LOWERBOUND; number <= UPPERBOUND; ++number) {
// number = LOWERBOUND+1, LOWERBOUND+2, ..., UPPERBOUND
// Print "Coza" if number is divisible by 3
if ( ...... ) {
System.out.print("Coza");
}
// Print "Loza" if number is divisible by 5
if ( ...... ) {
System.out.print(.....);
}
// Print "Woza" if number is divisible by 7
......
// Print the number if it is not divisible by 3, 5 and 7 (i.e., it has not
been processed above)
if ( ...... ) {
......
}
// After processing the number, print a newline if number is divisible by
11;
// else print a space
if ( ...... ) {
System.out.println(); // print newline
} else {
System.out.print( ...... ); // print a space
}
}
}
}
Notes
1. You cannot use nested-if (if ... else if ... else if ... else) for this problem. It is because the tests are
not mutually exclusive. For example, 15 is divisible by both 3 and 5. Nested-if is only applicable
if the tests are mutually exclusive.
2. The tests above look messy. A better solution is to use a boolean flag to keep track of whether
the number has been processed, as follows:
Hints
/**
* Print first 20 Fibonacci numbers and their average
*/
public class Fibonacci {
public static void main (String[] args) {
int n = 3; // The index n for F(n), starting from n=3, as n=1 and
n=2 are pre-defined
int fn; // F(n) to be computed
int fnMinus1 = 1; // F(n-1), init to F(2)
int fnMinus2 = 1; // F(n-2), init to F(1)
int nMax = 20; // maximum n, inclusive
int sum = fnMinus1 + fnMinus2; // Need sum to compute average
double average;
Try
1. Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a
number is formed by adding the three previous numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3), T(1)
=T(2)=1, and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci
numbers.
Hints
The coding pattern for extracting individual digits from an integer n is:
1. Use (n % 10) to extract the last (least-significant) digit.
2. Use n = n / 10 to drop the last (least-significant) digit.
3. Repeat if (n > 0), i.e., more digits to extract.
Take note that n is destroyed in the process. You may need to clone a copy.
int n = ...;
while (n > 0) {
int digit = n % 10; // Extract the least-significant digit
// Print this digit
......
n = n / 10; // Drop the least-significant digit and repeat the loop
}
Write a program called Add2Integers that prompts user to enter two integers. The program shall read
the two integers as int; compute their sum; and print the result. For example,
Enter first integer: 8
Enter second integer: 9
The sum is: 17
Hints
import java.util.Scanner; // For keyboard input
/**
* 1. Prompt user for 2 integers
* 2. Read inputs as "int"
* 3. Compute their sum in "int"
* 4. Print the result
*/
public class Add2Integers { // Save as "Add2Integers.java"
public static void main (String[] args) {
// Declare variables
int number1, number2, sum;
// Compute sum
sum = ......
// Display result
System.out.println("The sum is: " + sum); // Print with newline
}
}
Hints
// Declare variables
int number1, number2, number3; // The 3 input integers
int sum, product, min, max; // To compute these
// Compute min
// The "coding pattern" for computing min is:
// 1. Set min to the first item
// 2. Compare current min with the second item and update min if second item
is smaller
// 3. Repeat for the next item
min = number1; // Assume min is the 1st item
if (number2 < min) { // Check if the 2nd item is smaller than current min
min = number2; // Update min if so
}
if (number3 < min) { // Continue for the next item
min = number3;
}
// Print results
......
Try
1. Write a program called SumProductMinMax5 that prompts user for five integers. The program shall
read the inputs as int; compute the sum, product, minimum and maximum of the five integers; and
print the results. Use five int variables: number1, number2, ..., number5 to store the inputs.
Hints
// Declare variables
double radius, diameter, circumference, area; // inputs and results - all in
double
......
// Compute in "double"
......
Take note that you cannot name the variable surface area with a space or surface-area with a dash.
Java's naming convention is surfaceArea. Other languages recommend surface_area with an
underscore.
4.4 Swap2Integers
Write a program called Swap2Integers that prompts user for two integers. The program shall read the
inputs as int, save in two variables called number1 and number2; swap the contents of the two
variables; and print the results. For examples,
Hints
To swap the contents of two variables x and y, you need to introduce a temporary storage, say temp,
and do: temp x; x y; y temp.
For example, suppose that the taxable income is $85000, the income tax payable is $20000*0% +
$20000*10% + $20000*20% + $25000*30%.
Write a program called IncomeTaxCalculator that reads the taxable income (in int). The
program shall calculate the income tax payable (in double); and print the result rounded to 2 decimal
places. For examples,
Hints
// Declare constants first (variables may use these constants)
// The keyword "final" marked these as constant (i.e., cannot be changed).
// Use uppercase words joined with underscore to name constants
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;
// Declare variables
int taxableIncome;
double taxPayable;
......
The -1 is known as the sentinel value. (Wiki: In programming, a sentinel value, also referred to as a flag
value, trip value, rogue value, signal value, or dummy data, is a special value which uses its presence as
a condition of termination.)
Hints
The coding pattern for handling input with sentinel value is as follows:
// Declare constants first
final int SENTINEL = -1; // Terminating value for input
......
// Declare variables
int taxableIncome;
double taxPayable;
......
Take note that we repeat the input statements inside and outside the loop. Repeating statements is
NOT a good programming practice. This is because it is easy to repeat (Cntl-C/Cntl-V), but hard to
maintain and synchronize the repeated statements. In this case, we have no better choices!
Hints
// Read the first input to "seed" the while loop
System.out.print("Enter the monthly salary (or -1 to end): $");
salary = in.nextInt();
......
......
Hints
// Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1; // Terminating value for input
// Declare variables
double price, actualPrice, salesTax; // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; // to
accumulate
......
Hints
Use the following coding pattern which uses a while-loop with repeated modulus/divide operations to
extract and drop the last digit of a positive integer.
// Declare variables
int inNumber; // to be input
int inDigit; // each digit
......
// Extract and drop the "last" digit repeatably using a while-loop with
modulus/divide operations
while (inNumber > 0) {
inDigit = inNumber % 10; // extract the "last" digit
// Print this digit (which is extracted in reverse order)
......
inNumber /= 10; // drop "last" digit and repeat
}
......
Hints
See "ReverseInt".
Hints
// Declare constant
final int NUM_STUDENTS = 3;
// Declare variables
int numberIn;
boolean isValid; // boolean flag to control the input validation loop
int sum = 0;
double average;
......
sum += ......;
}
......
5. Exercises on Nested-Loops
5.1 SquarePattern (nested-loop)
Write a program called SquarePattern that prompts user for the size (a non-negative integer
in int); and prints the following square pattern using two nested for-loops.
Hints
The code pattern for printing 2D patterns using nested loops is:
Notes
1. You should name the loop indexes row and col, NOT i and j, or x and y, or a and b, which are
meaningless.
2. The row and col could start at 1 (and upto size), or start at 0 (and upto size-1). As computer
counts from 0, it is probably more efficient to start from 0. However, since humans counts from 1,
it is easier to read if you start from 1.
Try
Hints
Hints
1. Use printf() to format the output, e.g., each cell is %4d.
2. See "Java Basics" article.
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
(a) (b) (c) (d)
Hints
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1,
where row and col begin from 1.
2. You need to print the leading blanks, in order to push the # to the right. The trailing blanks are
optional, which does not affect the pattern.
3. For pattern (a), if (row >= col) print #. Trailing blanks are optional.
4. For pattern (b), if (row + col <= size + 1) print #. Trailing blanks are optional.
5. For pattern (c), if (row >= col) print #; else print blank. Need to print
the leading blanks.
6. For pattern (d), if (row + col >= size + 1) print #; else print blank. Need to print
the leading blanks.
7. The coding pattern is:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) (c) (d) (e)
Hints
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1,
where row and col begin from 1.
2. For pattern (a), if (row == 1 || row == size || col == 1 || col == size) print #;
else print blank. Need to print the intermediate blanks.
3. For pattern (b), if (row == 1 || row == size || row == col) print #; else print
blank.
# # # # # ## # # # # # # # # # # # # # # # # #
# # # # # # ## # # # # # # # # # # # # # # # # #
# # # # # # # ## # # # # # # # # # # # # # # # #
# # # # # # # # ## # # # # # # # # # # # # # # #
# # # # # # # # # ## # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) # # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # #
(c) (d)
Hints
For pattern (a):
1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1
1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1
1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1
1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1
1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1
1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1
1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1
1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(a) (b) (c) (d)
6. Magic(Special) Numbers
Hints
1+2+4+5+10+11+20+22+44+55+110 = 284
Enter number=145
145 is not an Armstrong Number
Hints
(1*1*1)+(5*5*5)+(3*3*3) = 153
Enter a number : 45
45 is a Capricorn/Kaprekar number
Enter a number : 297
297 is a Capricorn/Kaprekar number
Enter a number : 44
44 is not a Capricorn/Kaprekar number
Hints
Number = 45
(45)2 = 2025
From the above we can see one combination is equal to number so that 45 is Capricorn or Kaprekar
number.
Try
Write a Java program to generate and show all Kaprekar numbers less than 1000.
Enter a number : 31
31 is a Happy number
Enter a number : 32
32 is not a Happy number
Enter a number : 5
5 is a Automorphic Number
Enter a number : 25
25 is a Automorphic Number
Enter a number : 2
2 is not a Automorphic Number
Hints
Enter a number : 32
32 is not a Disarium Number
Hints
11 + 32 + 53 = 1 + 9 + 125 = 135
Enter a number : 32
32 is not a Magic Number
Enter number = 541
153 is a Magic Number
Hints
2+2+6=10 sum of digits is 10 then again 1+0=1 now we get a single digit number is 1.if we single digit
number will now 1 them it would not a magic number.
Enter a number: 9
9 is a Neon Number
Enter a number: 8
8 is not a Neon Number
Enter a number : 6
6 is a Perfect Number
Enter a number : 3
3 is not a Perfect Number
Enter a number : 23
23 is not a Special Number
Enter a number : 12
12 is not a Spy Number
Enter a number : 6
6 is an Ugly Number
Enter a number : 14
14 is not an Ugly Number
Hints
For a String called inStr, you can use inStr.length() to get the length of the String;
and inStr.charAt(idx) to retrieve the char at the idx position, where idx begins at 0, up
to instr.length() - 1.
// Define variables
String inStr; // input String
int inStrLen; // length of the input String
......
Hints
1. To check if a char c is a digit, you can use boolean expression (c >= '0' && c <= '9'); or
use built-in boolean function Character.isDigit(c).
2. You could use in.next().toLowerCase() to convert the input String to lowercase to reduce
the number of cases.
3. To print a % using printf(), you need to use %%. This is because % is a prefix for format specifier
in printf(), e.g., %d and %f.
Write a program called PhoneKeyPad, which prompts user for a String (case insensitive), and converts
to a sequence of keypad digits. Use (a) a nested-if, (b) a switch-case-default.
Hints
1. You can use in.next().toLowerCase() to read a String and convert it to lowercase to reduce
your cases.
2. In switch-case, you can handle multiple cases by omitting the break statement, e.g.,
switch (inChar) {
case 'a': case 'b': case 'c': // No break for 'a' and 'b', fall thru 'c'
System.out.print(2); break;
case 'd': case 'e': case 'f':
......
default:
......
}
7.4 Caesar's Code (String & char)
Caesar's Code is one of the simplest encryption techniques. Each letter in the plaintext is replaced by a
letter some fixed number of position (n) down the alphabet cyclically. In this exercise, we shall pick n=3.
That is, 'A' is replaced by 'D', 'B' by 'E', 'C' by 'F', ..., 'X' by 'A', ..., 'Z' by 'C'.
Write a program called CaesarCode to cipher the Caesar's code. The program shall prompt user for a
plaintext string consisting of mix-case letters only; compute the ciphertext; and print the ciphertext in
uppercase. For example,
Hints
1. Use in.next().toUpperCase() to read an input string and convert it into uppercase to reduce
the number of cases.
2. You can use a big nested-if with 26 cases ('A'-'Z'). But it is much better to
consider 'A' to 'W' as one case; 'X', 'Y' and 'Z' as 3 separate cases.
3. Take note that char 'A' is represented as Unicode number 65 and char 'D' as 68.
However, 'A' + 3 gives 68. This is because char + int is implicitly casted to int + int which
returns an int value. To obtain a char value, you need to perform explicit type casting
using (char)('A' + 3). Try printing ('A' + 3) with and without type casting.
Hints
1. Use in.next().toUpperCase() to read an input string and convert it into uppercase to reduce
the number of cases.
2. You can use a big nested-if with 26 cases ('A'-'Z'), or use the following relationship:
Write a program called TestPalindromicWord, that prompts user for a word and prints ""xxx" is|is
not a palindrome".
A phrase that reads the same backward as forward is also called a palindrome, e.g., "Madam, I'm Adam",
"A man, a plan, a canal - Panama!" (ignoring punctuation and capitalization).
2. You can check if a char c is a letter either using built-in boolean function Character.isLetter(c);
or boolean expression (c >= 'a' && c <= 'z'). Skip the index if it does not contain a letter.
7.8 CheckBinStr (String & char)
The binary number system uses 2 symbols, 0 and 1. Write a program called CheckBinStr to verify a
binary string. The program shall prompt user for a binary string; and decide if the input string is a valid
binary string. For example,
Hints
Use the following coding pattern which involves a boolean flag to check the input string.
// Declare variables
String inStr; // The input string
int inStrLen; // The length of the input string
char inChar; // Each char of the input string
boolean isValid; // "is" or "is not" a valid binary string?
......
isValid = true; // Assume that the input is valid, unless our check fails
for (......) {
inChar = ......;
if (!(inChar == '0' || inChar == '1')) {
isValid = false;
break; // break the loop upon first error, no need to continue for
more errors
// If this is not encountered, isValid remains true after the
loop.
}
}
if (isValid) {
System.out.println(......);
} else {
System.out.println(......);
}
// or using one liner
//System.out.println(isValid ? ... : ...);
Hints
if (!((inChar >= '0' && inChar <= '9')
|| (inChar >= 'A' && inChar <= 'F')
|| (inChar >= 'a' && inChar <= 'f'))) { // Use positive logic and then
reverse
......
}
Hints
Hints
8. Exercises on Arrays
8.1 PrintArray (Array)
Write a program called PrintArray which prompts user for the number of items in an array (a non-
negative integer), and saves it in an int variable called NUM_ITEMS. It then prompts user for the values
of all the items and saves them in an int array called items. The program shall then print the contents
of the array in the form of [x1, x2, ..., xn]. For example,
Hints
// Declare variables
tinal int NUM_ITEMS;
int[] items; // Declare array name, to be allocated after NUM_ITEMS is known
......
// Prompt for for the number of items and read the input as "int"
......
NUM_ITEMS = ......
// Prompt and read the items into the "int" array, if array length > 0
if (items.length > 0) {
......
for (int i = 0; i < items.length; ++i) { // Read all items
......
}
}
// Print array contents, need to handle first item and subsequent items
differently
......
for (int i = 0; i < items.length; ++i) {
if (i == 0) {
// Print the first item without a leading commas
......
} else {
// Print the subsequent items with a leading commas
......
}
// or, using a one liner
//System.out.print((i == 0) ? ...... : ......);
}
Hints
// Declare variables
final int NUM_ITEMS;
int[] items; // Declare array name, to be allocated after NUM_ITEMS is known
......
......
// Print array in "index: number of stars" using a nested-loop
// Take note that rows are the array indexes and columns are the value in
that index
for (int idx = 0; idx < items.length; ++idx) { // row
System.out.print(idx + ": ");
// Print value as the number of stars
for (int starNo = 1; starNo <= items[idx]; ++starNo) { // column
System.out.print("*");
}
......
}
......
Hints
1. Use an array of 16 Strings containing binary strings corresponding to hexadecimal number 0-9A-
F (or a-f), as follows
final String[] HEX_BITS = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
9. Exercises on Methods
9.1 exponent() (method)
Write a method called exponent(int base, int exp) that returns an int value of base raises to the
power of exp. The signature of the method is:
Assume that exp is a non-negative integer and base is an integer. Do not use any Math library
functions.
Also write the main() method that prompts user for the base and exp; and prints the result. For
example,
return product;
}
}
Also write the main() method that prompts user for a number, and prints "ODD" or "EVEN". You should
test for negative input. For examples,
Enter a number: 9
9 is an odd number
Enter a number: 8
8 is an even number
Enter a number: -5
-5 is an odd number
Hints
See Notes.
Write a program called MagicSum, which prompts user for integers (or -1 to end), and produce the sum
of numbers containing the digit 8. Your program should use the above methods. A sample output of
the program is as follows:
Hints
The coding pattern to repeat until input is -1 (called sentinel value) is:
final int SENTINEL = -1; // Terminating input
int number;
You can either repeatably use modulus/divide (n%10 and n=n/10) to extract and drop each digit in int;
or convert the int to String and use the String's charAt() to inspect each char.
Also write a test driver to test this method (you should test on empty array, one-element array, and n-
element array).
How to handle double[] or float[]? You need to write a overloaded version for double[] and a
overloaded version for float[], with the following signatures:
Hints
For the first element, print its value; for subsequent elements, print commas followed by the value.
Also write a test driver to test this method (you should test on empty array, one-element array, and n-
element array).
Notes: This is similar to the built-in function Arrays.toString(). You could study its source code.
Hints
You need to use a temporary location to swap two storage locations.
// Swap item1 and item2
int item1, item2, temp;
temp = item1;
item1 = item2;
item2 = item1;
// You CANNOT simply do: item1 = item2; item2 = item2;
9.11 reverse() (Array & Method)
Write a method called reverse(), which takes an array of int and reverse its contents. For example,
the reverse of [1,2,3,4] is [4,3,2,1]. The method's signature is as follows:
Take note that the array passed into the method can be modified by the method (this is called "pass by
reference"). On the other hand, primitives passed into a method cannot be modified. This is because a
clone is created and passed into the method instead of the original copy (this is called "pass by value").
Hints:
// Prompt user for the number of students and allocate the global "grades" array.
// Then, prompt user for grade, check for valid grade, and store in "grades".
public static void readGrades() { ....... }
// Print the given int array in the form of [x1, x2, x3,..., xn].
public static void print(int[] array) { ....... }
0 - 9: ***
10 - 19: ***
20 - 29:
30 - 39:
40 - 49: *
50 - 59: *****
60 - 69:
70 - 79:
80 - 89: *
90 -100: **
*
*
* * *
* * * *
* * * * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1
Hints
The method main(String[] args) takes an argument: "an array of String", which is often (but not
necessary) named args. This parameter captures the command-line arguments supplied by the user
when the program is invoked. For example, if a user invokes:
The three command-line arguments "12345", "4567" and "+" will be captured in
a String array {"12345", "4567", "+"} and passed into the main() method as the argument args.
That is,
switch(theOperator) {
case ('-'): System.out.println(operand1 - operand2); break;
case ('+'): ......
case ('*'): ......
case ('/'): ......
default:
System.err.println("Error: invalid operator!");
}
}
}
Notes:
To provide command-line arguments, use the "cmd" or "terminal" to run your program in the form
"java ClassName arg1 arg2 ....".
To provide command-line arguments in Eclipse, right click the source code "Run As" "Run
Configurations..." Select "Main" and choose the proper main class Select "Arguments" Enter
the command-line arguments, e.g., "3 2 +" in "Program Arguments".
To provide command-line arguments in NetBeans, right click the "Project" name "Set
Configuration" "Customize..." Select categories "Run" Enter the command-line arguments,
e.g., "3 2 +" in the "Arguments" box (but make sure you select the proper Main class).
Question: Try "java Arithmetic 2 4 *" (in CMD shell and Eclipse/NetBeans) and explain the result
obtained. How to resolve this problem?
In Windows' CMD shell, * is known as a wildcard character, that expands to give the list of file in the
directory (called Shell Expansion). For example, "dir *.java" lists all the file with extension of ".java".
You could double-quote the * to prevent shell expansion. Eclipse has a bug in handling this, even * is
double-quoted. NetBeans??
Exercises on Recursion
In programming, a recursive function (or method) calls itself. The classical example is factorial(n),
which can be defined recursively as f(n)=n*f(n-1). Nonetheless, it is important to take note that a
recursive function should have a terminating condition (or base case), in the case of factorial, f(0)=1.
Hence, the full definition is:
factorial(n) = 1, for n = 0
factorial(n) = n * factorial(n-1), for all n > 1
Hints
Writing recursive function is straight forward. You simply translate the recursive definition into code
with return.
// Return the factorial of the given integer, recursively
public static int factorial(int n) {
if (n == 0) {
return 1; // base case
} else {
return n * factorial(n-1); // call itself
}
// or one liner
// return (n == 0) ? 1 : n*factorial(n-1);
}
Notes
Compare the recursive version with the iterative version written earlier.
Hints
// Translate the recursive definition into code with return statements
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
10.4 Length of a Running Number Sequence (Recursive)
A special number sequence is defined as follows:
S(1) = 1
S(2) = 12
S(3) = 123
S(4) = 1234
......
S(9) = 123456789 // length is 9
S(10) = 12345678910 // length is 11
S(11) = 1234567891011 // length is 13
S(12) = 123456789101112 // length is 15
......
gcd(a,b) = a, if b = 0
gcd(a,b) = gcd(b, remainder(a,b)), if b > 0
Hints
public class Matrix {
// Method signatures
public static void print(int[][] m);
public static void print(double[][] m);
public static boolean haveSameDimension(int[][] m1, int[][] m2); // Used in
add(), subtract()
public static boolean haveSameDimension(double[][] m1, double[][] m2);
public static int[][] add(int[][] m1, int[][] m2);
public static double[][] add(double[][] m1, double[][] m2);
public static int[][] subtract(int[][] m1, int[][] m2);
public static double[][] subtract(double[][] m1, double[][] m2);
public static int[][] multiply(int[][] m1, int[][] m2);
public static double[][] multiply(double[][] m1, double[][] m2);
......
}
Hints
Use escape sequence \uhhhh where hhhh are four hex digits to display Unicode characters such as ¥
and ©. ¥ is 165 (00A5H) and © is 169 (00A9H) in both ISO-8859-1 (Latin-1) and Unicode character sets.
Double-quote (") and black-slash (\) require escape sequence inside a String. Single quote (') does
not require escape sign.
Try
Print the same pattern using printf(). (Hints: Need to use %% to print a % in printf() because % is
the suffix for format specifier.)
# # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # #
(a) (b) # # # # # # # # #
# # # # # # #
# # # # #
# # #
#
(c)
1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1
1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1
1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1
1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1
1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1
1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1
1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1
1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(d) (e) (f) (g)
1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 2 1 1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1
1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1 1 2 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1
(h) (i)
1 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1
1 2 3 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 5 4 3 2 1 1 2 3 4 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 3 2 1
1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 1
(j) (k)
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 0 1 0 9 8 7 6
7 8 9 0 1 2 3 2 1 0 9 8 7
8 9 0 1 2 3 4 5 4 3 2 1 0 9 8
(l)
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
(a) PowerOf2Triangle
1 1
1 1 1 1
1 2 1 1 2 1
1 3 3 1 1 3 3 1
1 4 6 4 1 1 4 6 4 1
1 5 10 10 5 1 1 5 10 10 5 1
1 6 15 20 15 6 1 1 6 15 20 15 6 1
(b) PascalTriangle1 (c) PascalTriangle2
Compare the values computed using the series with the JDK
methods Math.sin(), Math.cos() at x=0, , , , using various numbers of terms.
Hints
Do not use int to compute the factorial; as factorial of 13 is outside the int range. Avoid generating
large numerator and denominator. Use double to compute the terms as:
11.7 Exponential Series
Write a method to compute e and exp(x) using the following series expansion, in a class
called ExponentialSeries. The signatures of the methods are:
The factorial of 1 is 1
The factorial of 2 is 2
...
The factorial of 12 is 479001600
The factorial of 13 is out of range
Hints
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently
wraps the number around. Hence, you cannot use F(n) * (n+1) > Integer.MAX_VALUE to check for
overflow. Instead, overflow occurs for F(n+1) if (Integer.MAX_VALUE / Factorial(n)) < (n+1),
i.e., no more room for the next number.
Try
Modify your program called FactorialLong to list all the factorial that can be expressed as a long (64-
bit signed integer). The maximum value for long is kept in a constant called Long.MAX_VALUE.
11.10 FibonacciInt (Handling Overflow)
Write a program called FibonacciInt to list all the Fibonacci numbers, which can be expressed as
an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]). The output shall look
like:
F(0) = 1
F(1) = 1
F(2) = 2
...
F(45) = 1836311903
F(46) is out of the range of int
Hints
The maximum and minimum values of a 32-bit int are kept in
constants Integer.MAX_VALUE and Integer.MIN_VALUE, respectively. Try these statements:
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently
wraps the number around. Hence, you cannot use F(n) = F(n-1) + F(n-2) >
Integer.MAX_VALUE to check for overflow. Instead, overflow occurs for F(n) if Integer.MAX_VALUE
F(n-1) < F(n-2) (i.e., no more room for the next Fibonacci number).
Try
Write a similar program called TribonacciInt for Tribonacci numbers.
public static String toRadix(String in, int inRadix, int outRadix) // The input
and output are treated as String.
Write a program called NumberConversion, which prompts the user for an input string, an input
radix, and an output radix, and display the converted number. The output shall look like:
Enter a number and radix: A1B2
Enter the input radix: 16
Enter the output radix: 2
"A1B2" in radix 16 is "1010000110110010" in radix 2.
11.12 NumberGuess
Write a program called NumberGuess to play the number guessing game. The program shall generate
a random number between 0 and 99. The player inputs his/her guess, and the program shall response
with "Try higher", "Try lower" or "You got it in n trials" accordingly. For example:
java NumberGuess
Key in your guess:
50
Try higher
70
Try lower
65
Try lower
61
You got it in 4 trials!
Hints
Use Math.random() to produce a random number in double between 0.0 (inclusive)
and 1.0 (exclusive). To produce an int between 0 and 99, use:
final int SECRET_NUMBER = (int)(Math.random()*100); // truncate to int
11.13 WordGuess
Write a program called WordGuess to guess a word by trying to guess the individual characters. The
word to be guessed shall be provided using the command-line argument. Your program shall look like:
Hints
Set up a boolean array (of the length of the word to be guessed) to indicate the positions of the word
that have been guessed correctly.
Check the length of the input String to determine whether the player enters a single character or a
guessed word. If the player enters a single character, check it against the word to be guessed, and
update the boolean array that keeping the result so far.
Try
Try retrieving the word to be guessed from a text file (or a dictionary) randomly.
11.14 DateUtil
Complete the following methods in a class called DateUtil:
boolean isLeapYear(int year): returns true if the given year is a leap year. A year is a leap year if it is divisible by 4 but
not by 100, or it is divisible by 400.
boolean isValidDate(int year, int month, int day) : returns true if the
given year, month and day constitute a given date. Assume that year is between 1 and 9999, month is between 1 (Jan) to 12 (Dec) and day shall
be between 1 and 28|29|30|31 depending on the month and whether it is a leap year.
int getDayOfWeek(int year, int month, int day) : returns the day of the week, where 0 for SUN, 1 for MON, ...,
6 for SAT, for the given date. Assume that the date is valid.
String toString(int year, int month, int day) : prints the given date in the format "xxxday d mmm
yyyy", e.g., "Tuesday 14 Feb 2012". Assume that the given date is valid.
Hints
To find the day of the week (Reference: Wiki "Determination of the day of the week"):
1. Based on the first two digit of the year, get the number from the following "century" table.
2. Take note that the entries 4, 2, 0, 6 repeat.
3. Add to the last two digit of the year.
4. Add to "the last two digit of the year divide by 4, truncate the fractional part".
5. Add to the number obtained from the following month table:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Non-Leap Year 0 3 3 6 1 4 6 2 5 0 3 5
// Test Driver
public static void main(String[] args) {
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012)); // true
The calendar we used today is known as Gregorian calendar, which came into effect in October 15, 1582
in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed
from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only
difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every
four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible
by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible
by 400. Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January
1st.
This above algorithm work for Gregorian dates only. It is difficult to modify the above algorithm to
handle pre-Gregorian dates. A better algorithm is to find the number of days from a known date.
A class called Employee, which models an employee with an ID, name and salary, is designed as shown
in the following class diagram. The method raiseSalary(percent) increases the salary by the given
percentage. Write the Employee class.
Hints:
The expected out is:
Employee[id=8,name=Peter Tan,salary=2500]
Employee[id=8,name=Peter Tan,salary=999]
id is: 8
firstname is: Peter
lastname is: Tan
salary is: 999
name is: Peter Tan
annual salary is: 11988
1098
Employee[id=8,name=Peter Tan,salary=1098]
A class called InvoiceItem, which models an item of an invoice, with ID, description, quantity and unit
price, is designed as shown in the following class diagram. Write the InvoiceItem class.
Hints:
A class called Account, which models a bank account of a customer, is designed as shown in the
following class diagram. The methods credit(amount) and debit(amount) add or subtract the
given amount to the balance. The method transferTo(anotherAccount, amount) transfers the
given amount from this Account to the given anotherAccount. Write the Account class.
Hints:
A class called Date, which models a calendar date, is designed as shown in the following class diagram.
Write the Date class.
Hints:
You can reuse the Circle class that you have created in the previous exercise. Make sure that you keep
"Circle.class" in the same directory.
Method Overriding and "Super": The subclass Cylinder inherits getArea() method from its
superclass Circle. Try overriding the getArea() method in the subclass Cylinder to compute the
-area) of the cylinder instead of base area. That is,
if getArea() is called by a Circle instance, it returns the area. If getArea() is called by
a Cylinder instance, it returns the surface area of the cylinder.
If you override the getArea() in the subclass Cylinder, the getVolume() no longer works. This is
because the getVolume() uses the overridden getArea() method found in the same class. (Java
runtime will search the superclass only if it cannot locate the method in this class). Fix the getVolume().
Hints: After overridding the getArea() in subclass Cylinder, you can choose to invoke
the getArea() of the superclass Circle by calling super.getArea().
Try:
Provide a toString() method to the Cylinder class, which overrides the toString() inherited from
the superclass Circle, e.g.,
@Override
public String toString() { // in Cylinder class
return "Cylinder: subclass of " + super.toString() // use Circle's toString()
+ " height=" + height;
}
Write the classes as shown in the following class diagram. Mark all the overridden methods with
annotation @Override.
13.3 Point2D and Point3D
Write the classes as shown in the following class diagram. Mark all the overridden methods with
annotation @Override.
Hints:
1. You cannot assign floating-point literal say 1.1 (which is a double) to a float variable, you need
to add a suffix f, e.g. 0.0f, 1.1f.
2. The instance variables x and y are private in Point2D and cannot be accessed directly in the
subclass Point3D. You need to access via the public getters and setters. For example,
Write the classes as shown in the following class diagram. Mark all the overridden methods with
annotation @Override.
Hints
1. You cannot assign floating-point literal say 1.1 (which is a double) to a float variable, you need
to add a suffix f, e.g. 0.0f, 1.1f.
2. The instance variables x and y are private in Point and cannot be accessed directly in the
subclass MovablePoint. You need to access via the public getters and setters. For example, you
cannot write x += xSpeed, you need to write setX(getX() + xSpeed).
13.5 Superclass Shape and its subclasses Circle, Rectangle and Square
Write a test class to test these statements involving polymorphism and explain the outputs. Some
statements may trigger compilation errors. Explain the errors, if any.
Try:
14.2 GeometricObject Interface and its Implementation Classes Circle and Rectangle
Write an interface called GeometricObject, which contains 2 abstract methods: getArea() and
getPerimeter(), as shown in the class diagram. Also write an implementation class called Circle.
Mark all the overridden methods with annotation @Override.
14.3 Ex: Movable Interface and its Implementation MovablePoint Class
Write an interface called Movaable, which contains 4 abstract methods moveUp(), moveDown(),
moveLeft() and moveRight(), as shown in the class diagram. Also write an implementation class
called MovablePoint. Mark all the overridden methods with annotation @Override.
1 4 .4 M o v a b l e In t er face an d
C l as se s M o v a b l e Po i n t an d M o v a b leC i r c l e
Write the implementation classes called MovablePoint and MovableCircle. Mark all the overridden
methods with annotation @Override.
14.5 Interfaces Resizable and GeometricObject
Write the interface called GeometricObject, which declares two abstract methods: getParameter()
and getArea(), as specified in the class diagram.
Hints:
public interface GeometricObject {
public double getPerimeter();
......
}
Write the implementation class Circle, with a protected variable radius, which implements the
interface GeometricObject.
Hints:
public class Circle implements GeometricObject {
// Private variable
......
// Constructor
......
......
}
Write a test program called TestCircle to test the methods defined in Circle.
The class ResizableCircle is defined as a subclass of the class Circle, which also implements an
interface called Resizable, as shown in class diagram. The interface Resizable declares
an abstract method resize(), which modifies the dimension (such as radius) by the given
percentage. Write the interface Resizable and the class ResizableCircle.
Hints:
// Constructor
public ResizableCircle(double radius) {
super(...);
}
Write a test program called TestResizableCircle to test the methods defined in ResizableCircle.
Write the codes for all the classes shown in the class diagram. Mark all the overridden methods with
annotation @Override.
@Override
public void greeting(Dog another) {
System.out.println("Woooooowwwww!");
}
}
Try:
Explain the outputs (or error) for the following test program.
// Using Polymorphism
Animal animal1 = new Cat();
animal1.greeting();
Animal animal2 = new Dog();
animal2.greeting();
Animal animal3 = new BigDog();
animal3.greeting();
Animal animal4 = new Animal();
// Downcast
Dog dog2 = (Dog)animal2;
BigDog bigDog2 = (BigDog)animal3;
Dog dog3 = (Dog)animal3;
Cat cat2 = (Cat)animal2;
dog2.greeting(dog3);
dog3.greeting(dog2);
dog2.greeting(bigDog2);
bigDog2.greeting(dog2);
bigDog2.greeting(bigDog1);
}
}
15. Final Notes
The only way to learn programming is program, program and program on challenging problems. The
problems in this tutorial are certainly NOT challenging. There are tens of thousands of challenging
problems available used in training for various programming contests (such as International Collegiate
Programming Contest (ICPC), International Olympiad in Informatics (IOI)). Check out these sites:
The ACM - ICPC International collegiate programming contest (https://icpc.global/ )
The Topcoder Open (TCO) annual programming and design contest
(https://www.topcoder.com/ )
https://uva.onlinejudge.org/ ).
http://poj.org/ ).
USA Computing Olympiad (USACO) Training Program @ http://train.usaco.org/usacogate.
https://codingcompetitions.withgoogle.com/codejam,
https://codingcompetitions.withgoogle.com/hashcode )
The ICFP programming contest (https://www.icfpconference.org/ )
BME International 24-hours programming contest (https://www.challenge24.org/ )
The International Obfuscated C Code Contest (https://www0.us.ioccc.org/main.html )
Internet Problem Solving Contest (https://ipsc.ksp.sk/ )
Microsoft Imagine Cup (https://imaginecup.microsoft.com/en-us )
Hewlett Packard Enterprise (HPE) Codewars (https://hpecodewars.org/ )
OpenChallenge (https://www.openchallenge.org/ )
Coding Contests Scores
Students must solve problems and attain scores in the following coding contests:
Name of the contest Minimum number of problems to Required score
solve
CodeChef 20 200
Leetcode 20 200
GeeksforGeeks 20 200
SPOJ 5 50
InterviewBit 10 1000
Hackerrank 25 250
Codeforces 10 100
BuildIT 50 500
Total score need to obtain 2500
Student must have any one of the following certifications:
HackerRank Java Basic Skills Certification
Oracle Certified Associate Java Programmer OCAJP
CodeChef - Learn Java Certification
NPTEL Programming in Java
NPTEL Data Structures and Algorithms in Java
V. TEXT BOOKS:
1. Farrell, Joyce.Java Programming, Cengage Learning B S Publishers, 8 th Edition, 2020
2. Schildt, Herbert. Java: The Complete Reference 11th Edition, McGraw-Hill Education, 2018.