Thursday, July 7, 2011

LEARN JAVA PROGRAMMING

What is programming?
Computer program is a set of instructions that guide a computer to execute a particular task. It is like a recipe for a cook in making a particular dish. The recipe contains a list of ingredients called the data or variables, and a list of steps that guide the computer what to do with the data. So programming is the technique of making a computer to perform something you want to do.
Programming or coding is a language that is used by operating systems to perform the task. We know computer understands binary languages with digits 1s and 0s. These binary languages are difficult to understand by human; so we generally use an intermediate language instead of binary language. Again the program uses high-level language that is interpreted into bytes that the computer understands. So a programmer writes a source code and uses a tool or interpreter that allows the computer to read, translate and execute the programs to perform a function.
What is Java, it?s history?
Java is a high-level object-oriented programming language developed by the Sun Microsystems.
What is Java, it’s history?
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s.

Download JDK
What is JDK (Java Development Kit)
JDK is a software development program provided by sun Microsystems. Java Development Kit or JDK comes in various version and can be downloaded free from the sun Microsystems. JVM compiler, debugger and other tools are used with JDK for developing java based application & java applets. So make sure that your JVM compiler & JDK versions are same.
JDK also known as Java 2 Platform, That comes in three editions J2ME, J2SE & J2EE. If you are beginner or learning Java then start by downloading J2SE.
Acronyms:
JDK Java Development Kit
JVM Java virtual machine
Download JDK
You can download JDK from www.javasoft.com/j2se
Latest version of JDK
1. JDK 5.0 Update 6
The full internal version number for this update release is 1.5.0_06-b05 (where "b" means "build"). The external version number is 5.0u6. Java Version 1.5.0_06 introduces various security enhancements in Java Plug-in and Java Web Start to better protect users and enterprises. For more information please visit: http://java.sun.com/j2se/1.5.0/ReleaseNotes.html

Getting Started - Write your First Java Program

Let us begin by writing our first Java program that prints a message "Hello, world!" to the display console, as shown:

Hello, world!

You could write Java programs using a programming text editor or an integrated development tool (such as Eclipse or NetBeans), Depending on your choice, read:

* writing your first Java program using JDK and a programming text editor (try this if you are not sure).
* writing your first Java program using Eclipse.
* writing your first Java program using NetBeans.

Hello, world

Dissecting Hello.java: Let us dissect the "Hello-world" program (reproduced below with line numbers added on the left panel to help in the explanation).

1
2
3
4
5
6
7
8



/*
* First Java program, which says "Hello, world!"
*/
public class Hello { // To save as "Hello.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // Print message
}
}

The statements in green are called comments. Comments are not executable, but provide useful explanation to you and your readers. There are two kinds of comments:

1. Multi-line Comment: begins with "/*" and ends with "*/", and may span more than one lines (as in Lines 1-3).
2. End-of-line Comment: begins with "//" and lasts until the end of the current line (as in Lines 4 and 6).

The basic unit of a Java program is a class. A class called "Hello" is defined with the keyword "class" in Lines 4-8, as follows:

public class Hello { ...... } // Use keyword "class" to define a class
// { ...... } is the "body" of the class
// The keyword "public" will be discussed later

In Java, the name of the source file must be the same as the name of the public class with a mandatory file extension of ".java". Hence, this file must be saved as "Hello.java".

Lines 5-7 defines the so-called main() method, which is the starting point, or entry point, of program execution, as follows:

public static void main(String[] args) { ...... } // main() method is the entry point of program execution
// { ...... } is the "body" of the method,
// which contains your programming statements.
// Other keywords will be discussed later.

In Line 6, the method System.out.println("Hello, world!") is used to print the message string "Hello, world!". A string is surrounded by a pair of double quotes and contain texts. The text will be printed as it is, without the double quotes.

A programming statement performs a piece of programmming action, which must be terminated by a semi-colon ";", as in Line 6.

A block is a group of programming statements enclosed by braces { }. There are two blocks in this program. One contains the body of the class Hello. The other contains the body of the main() method. There is no need to put a semi-colon after the closing brace.

Extra white-spaces, tabs, and lines are ignored, but they could help you and your readers to better understand your program. Use them liberally.

Java is case sensitive - a ROSE is NOT a Rose, and is NOT a rose. The filename is also case sensitive.
Java Program Template

You can use the following template to write your Java programs. Choose a meaningful Classname that reflects the purpose of your program, and write your programming statements inside the body of the main() method. Don't worry about the other terms and keywords now, which will be explained in due course.

1
2
3
4
5



public class Classname { // Choose a meaningful classname, save as "Classname.java"
public static void main(String[] args) {
// Your programming statements here!
}
}

Printing via System.out.println() and System.out.print()

System.out.println(aString) prints aString to the display console, and brings the cursor to the beginning of the next line; while System.out.print(aString) prints aString but keeps the cursor after the printed string. Try the following program and explain the output produced.

1
2
3
4
5
6
7
8
9
10
11



public class PrintTest { // Save as "PrintTest.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // Advance to next line after printing "Hello, world!"
System.out.println(); // Print a empty line
System.out.print("Hello, world!"); // Cursor stayed after the printed string
System.out.println("Hello,");
System.out.print(" "); // Print a space
System.out.print("world!");
System.out.println("Hello, world!");
}
}

Hello, world!

Hello, world!Hello,
world!Hello, world!

Let's Write a Program to Add a Few Numbers

Let's write a program to add five integers as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16



/*
* Sum five numbers and print the result
*/
public class FiveNumberSum { // Save as "FiveNumberSum.java"
public static void main(String[] args) {
int number1 = 11;
int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;
int sum;
sum = number1 + number2 + number3 + number4 + number5;
System.out.print("The sum is "); // Print a descriptive string
System.out.println(sum); // Print the value stored in sum
}
}

The sum is 165

Lines 6-10 declare five int (integer) variables called number1, number2, number3, number4, and number5; and assign then values of 11, 22, 33, 44, and 55 respectively, via the so-called assignment operator "=".

Line 11 declares a int (integer) variable called sum, without assigning an initial value.

Line 12 computes the sum of number1 to number5 and assign the result to the variable sum. The symbol '+' denotes arithmetic addition, just like Mathematics.

Line 13 prints a descriptive string. A String is surrounded by double quotes, and will be printed as it is (but without the double quotes).

Line 14 prints the value stored in the variable sum (in this case, the sum of the five numbers) - you should not surround a variable to be printed by double quotes.
What is a Program?

A program is a sequence of instructions (or programming statements), executing one after another - usually in a sequential manner, as illustrated in the following flow chart.
sequential flow

EXAMPLE: The following program prints the area and perimeter of a circle, given its radius. Take note that the programming statements are executed sequentially.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26



/*
* Print the area and perimeter of a circle, given its radius.
*/
public class CircleComputation { // Saved as "CircleComputation.java"
public static void main(String[] args) {
// Declare variables
double radius;
double area;
double perimeter;

// Assign a value to radius
radius = 1.2;

// Compute area and perimeter
area = radius * radius * 3.1416;
perimeter = 2.0 * radius * 3.1416;

// Print results
System.out.print("The radius is ");
System.out.println(radius);
System.out.print("The area is ");
System.out.println(area);
System.out.print("The perimeter is ");
System.out.println(perimeter);
}
}

The radius is 1.2
The area is 4.523904
The perimeter is 7.53984

Lines 7-9 declare three double variables, which can hold real numbers (or floating-point numbers). Line 12 assigns a value to the variable radius. Lines 15-16 compute the area and perimeter, based on the radius. Lines 19-24 print the results.

Take note that the programming statements inside the main() are executed one after another, sequentially.
What is a Variable?

Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.

More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value.

* A variable has a name (or identifier), e.g., radius, area, age, height. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., area = radius*radius*3.1416).
* A variable has a type. Examples of type are:
o int: for integers (whole numbers) such as 123 and -456;
o double: for floating-point or real numbers, such as 3.1416, -55.66, having a decimal point and fractional part;
o String: for texts such as "Hello", "Good Morning!". Text strings are enclosed within a pair of double quotes.
* A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor texts such as "Hello". The concept of type was introduced into the early programming languages to simplify intrepretation of data made up of 0s and 1s.

The following diagram illustrates three types of variables: int, double and String. An int variable stores an integer (whole number). A double variable stores a real number. A String variable stores texts.
variable

To use a variable, you need to first declare its name and type, in one of the following syntaxes:

var-type var-name; // Declare a variable of a type
var-type var-name-1, var-name-2,...; // Declare multiple variables of the same type
var-type var-name = initial-value; // Declare a variable of a type, and assign an initial value
var-type var-name-1 = initial-value-1, var-name-2 = initial-value-2,... ; // Declare variables with initial values

Take note that:

* Each declaration statement is terminated with a semi-colon ";".
* In multiple-variable declaration, the names are separated by commas ",".
* The symbol "=", known as the assignment operator, can be used to assign an initial value (of the declared type) to the variable.

For example,

int sum; // Declare a variable named "sum" of the type "int" for storing an integer.
// Terminate the statement with a semi-colon.
int number1, number2; // Declare two "int" variables named "number1" and "number2",
// separated by a comma.
double average; // Declare a variable named "average" of the type "double" for storing a real number.
int height = 20; // Declare an int variable, and assign an initial value.

Once a variable is declared, you can assign and re-assign a value to a variable, via the assignment operator "=". For example,

int number; // Declare a variable named "number" of the type "int" (integer)
number = 99; // Assign an integer value of 99 to the variable "number"
number = 88; // Re-assign a value of 88 to "number"
number = number + 1; // Evaluate "number + 1", and assign the result back to "number"
int sum = 0; // Declare an int variable named sum and assign an initial value of 0
sum = sum + number; // Evaluate "sum + number", and assign the result back to "sum", i.e. add number into sum
int num1 = 5, num2 = 6; // Declare and initialize two int variables in one statement, separated by a comma
double radius = 1.5; // Declare a variable name radius, and initialize to 1.5
int number; // ERROR: A variable named "number" has already been declared
sum = 55.66; // ERROR: The variable "sum" is an int. It cannot be assigned a floating-point number
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a text string

Take note that:

* Each variable can only be declared once.
* You can declare a variable anywhere inside the program, as long as it is declared before it is being used.
* Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello".
* The type of a variable cannot be changed inside the program.

I have shown your two data types in the above example: int for integer and double for floating-point number (or real number). Take note that in programming, int and double are two distinct types and special caution must be taken when mixing them in an operation, which shall be explained later.
Basic Arithmetic Operations

The basic arithmetic operations are:

* addition (+)
* subtraction (-)
* multiplication (*)
* division (/)
* remainder or modulo (%)
* increment (by 1) (++)
* decrement (by 1) (--)

Addition, subtraction, multiplication, division and remainder take two operands (binary operators); while increment and decrement take only one operand (unary operators).

The following program illustrates these arithmetic operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42



/**
* Test Arithmetic Operations
*/
public class ArithmeticTest { // Save as "ArithmeticTest.java"
public static void main(String[] args) {

int number1 = 98; // Declare an int variable number1 and initialize it to 98
int number2 = 5; // Declare an int variable number2 and initialize it to 5
int sum, difference, product, quotient, remainder; // Declare five int variables to hold results

// Perform arithmetic Operations
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;
System.out.print("The sum, difference, product, quotient and remainder of "); // Print description
System.out.print(number1); // Print the value of the variable
System.out.print(" and ");
System.out.print(number2);
System.out.print(" are ");
System.out.print(sum);
System.out.print(", ");
System.out.print(difference);
System.out.print(", ");
System.out.print(product);
System.out.print(", ");
System.out.print(quotient);
System.out.print(", and ");
System.out.println(remainder);

number1++; // Increment the value stored in the variable "number1" by 1
// Same as "number1 = number1 + 1"
number2--; // Decrement the value stored in the variable "number2" by 1
// Same as "number2 = number2 - 1"
System.out.println("number1 after increment is " + number1); // Print description and variable
System.out.println("number2 after decrement is " + number2);
quotient = number1 / number2;
System.out.println("The new quotient of " + number1 + " and " + number2
+ " is " + quotient);
}
}

The sum, difference, product, quotient and remainder of 98 and 5 are 103, 93, 490, 19, and 3
number1 after increment is 99
number2 after decrement is 4
The new quotient of 99 and 4 is 24

Lines 7-8 declare and initialize two int (integer) variables number1 and number2. Line 9 declares five int variables sum, difference, product, quotient, and remainder to hold the results of operations, in one statement (with items separated by commas), without assigning initial values.

Lines 12-16 carry out the arithmetic operations on variables number1 and number2. Take note that division of two integers produces a truncated integer, e.g., 98/5 → 19, 99/4 → 24, and 1/2 → 0.

Lines 17-30 print the results of the arithmetic operations, with appropriate string descriptions in between. Take note that text string are enclosed within double-quotes, and will get printed as it is, including the white spaces but without the double quotes. To print the value stored in a variable, no double quotes should be used. For example,

System.out.println("sum"); // Print text string "sum" - as it is
System.out.println(sum); // Print the value stored in variable sum, e.g., 98

Lines 32 and 34 illustrate the increment and decrement operations. Unlike "+", "-", "*", "/" and "%", which work on two operands (binary operators), "++" and "--" operate on only one operand (unary operators).

Lines 36-37 print the new values stored after the increment/decrement operations. Take note that instead of using many print() statements as in Lines 17-30, we could simply place all the items (text strings and variables) into one println(), with the items separated by "+". In this case, "+" does not perform addition. Instead, it concatenates or joins all the items together. Line 36 provides another example.

TRY:

1. Combining Lines 17-30 into one single println() statement, using "+" to concatenate all the items together.
2. Introduce one more int variable called number3, and assign it an integer value of 77. Compute and print the sum and product of all the three numbers.
3. In Mathematics, we could omit the multiplication sign in an arithmetic expression, e.g., x = 5a + 4b. In programming, you need to explicitly provide all the operators, i.e., x = 5*a + 4*b. Try printing the sum of 31 times of number1 and 17 times of number2 and 87 time of number3.

What If Your Need To Add Many Numbers?

Suppose that you want to add all the integers from 1 to 1000. If you follow the previous example, you would require a thousand-line program! Instead, you could use a loop in your program to perform a repetitive task, that is what the computer is good at.
Loop

Try the following program, which sums all the integers from a lowerbound (=1) to an upperbound (=1000) using a so-called for-loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17



/*
* Sum from a lowerbound to an upperbound using a for-loop
*/
public class RunningNumberSum { // Save as "RunningNumberSum.java"
public static void main(String[] args) {
int lowerbound = 1; // Store the lowerbound
int upperbound = 1000; // Store the upperbound
int sum = 0; // Declare an int variable "sum" to accumulate the numbers
// Set the initial sum to 0
// Use a for-loop to repeatitively sum from the lowerbound to the upperbound
for (int number = 1; number <= upperbound; number++) {
sum = sum + number; // Accumulate number into sum
}
// Print the result
System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
}
}

The sum from 1 to 1000 is 500500

Let us dissect this program:

Lines 6 and 7 declare two int variables to store the lowerbound and upperbound respectively.

Line 8 declares an int variable named sum and initializes it to 0. This variable will be used to accumulate numbers over the steps in the repetitive loop.

Lines 11-13 contain a so-called for-loop. A for-loop takes the following syntax:

// Syntax
for ( initialization ; test ; post-processing ) {
body ;
}




// Example
int sum = 0;
for (int number = 1; number <= 1000; number++) {
sum = sum + number;
}

for-loop

There are four parts in a for-loop. Three of them, initialization, test condition and post-processing, are enclosed in brackets ( ), and separated by two semi-colons ";". The body contains the repetitive task to be performed. As illustrated in the above flow chart, the initialization statement is first executed. The test is then evaluated. If the test returns true, the body is executed; followed by the post-processing statement. The test is checked again and the process repeats until the test is false. When the test is false, the for-loop completes and program execution continues to the next statement after the for-loop.

In our program, the initialization statement declares an int variable named number and initializes it to lowerbound (=1). The test checks if number is equal to or less than upperbound (=1000). If it is true, the current value of number is added into the sum, and the post-processing statement "number++" increases the value of number by 1. The test is then checked again and the process repeats until the test is false (i.e., number increases to upperbound+1), which causes the for-loop to terminate. Execution then continues to the next statement (in Line 15).

In this example, the loop repeats 1000 times (number having value of 1 to 1000). After the loop is completed, Line 15 prints the result with a proper description.

TRY:

1. Modify the above program to sum all the numbers from 9 to 888. (Ans: 394680.)
2. Modify the above program to sum all the odd numbers between 1 to 1000. (Hint: Change the post-processing statement to "number = number + 2". Ans: 250000)
3. Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7. (Hint: Modify the initialization and post-processing statements. Ans: 71071.)
4. Modify the above program to find the sum of the square of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 +... (Ans: 338350.)
5. Modify the above program (called RunningNumberProduct) to compute the product of all the numbers from 1 to 10. (Hint: Use a variable called product instead of sum and initialize product to 1. Ans: 3628800.)

Conditional

What if you want to sum all the odd numbers and also all the even numbers between 1 and 1000? There are many ways to do this. You could declare two variables: sumOdd and sumEven. You can then use a conditional statement to check whether the number is odd or even, and accumulate the number into the respective sums. The program is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
23



/*
* Sum the odd numbers and the even numbers from a lowerbound to an upperbound
*/
public class OddEvenSum { // Save as "OddEvenSum.java"
public static void main(String[] args) {
int lowerbound = 1;
int upperbound = 1000;
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
for (int number = lowerbound; number <= upperbound; number++) {
if (number % 2 == 0) { // Even
sumEven += number; // Same as sumEven = sumEven + number
} else { // Odd
sumOdd += number; // Same as sumOdd = sumOdd + number
}
}
// Print the result
System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " + sumOdd);
System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + " is " + sumEven);
System.out.println("The difference between the two sums is " + (sumOdd - sumEven));
}
}

The sum of odd numbers from 1 to 1000 is 250000
The sum of even numbers from 1 to 1000 is 250500
The difference between the two sums is -500

Lines 8 and 9 declare two int variables named sumOdd and sumEven and initialize them to 0, for accumulating the odd and even numbers respectively.

Lines 11-15 contain a conditional statement. The conditional statement can take one the following forms: if-then, if-then-else.

// if-then syntax
if ( condition ) {
true-body ;
}



// Example
if (mark >= 50) {
System.out.println("Congratulation!");
}

// if-then-else syntax
if ( condition ) {
true-body ;
} else {
false-body ;
}



// Example
if (mark >= 50) {
System.out.println("Congratulation!");
} else {
System.out.println("Try Harder!");
}

For a if-then statement, the true-body is executed if the test condition is true. Otherwise, nothing is done and the execution continues to the next statement.

For a if-then-else statement, the true-body is executed if the condition is true; otherwise, the false-body is executed. Execution is then continued to the next statement.

The following flow chart illustrates the if-then and if-then-else statements.
if-then if-then-else

In our program, we use the remainder (or modulo) operator (%) to compute the remainder of number divides by 2. We then compare the remainder with 0 to test for even number.

There are six comparison operators:

* equal to (==)
* not equal to (!=)
* greater than (>)
* less than (<)
* greater than or equal to (>=)
* less than or equal to (<=)

Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-equal sign (=) is the assignment operator.
Combining Simple Conditions

Suppose that you want to check whether a number x is between 1 and 100 (inclusive), i.e., 1 <= x <= 100. There are two simple conditions here, (x >= 1) AND (x <= 100). In programming, you cannot write 1 <= x <= 100, but need to write (x >= 1) && (x <= 100), where "&&" denotes the "AND" operator. Similarly, suppose that you want to check whether a number x is divisible by 2 OR by 3, you have to write (x % 2 == 0) || (x % 3 == 0) where "||" denotes the "OR" operator.

There are three so-called logical operators that operate on the boolean conditions:

* AND (&&)
* OR (||)
* NOT (!)

For examples:

// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100) // AND (&&)
// Incorrect to use 0 <= x <= 100

// Return true if x is outside 0 and 100 (inclusive)
(x < 0) || (x > 100) // OR (||)
!((x >= 0) && (x <= 100)) // NOT (!), AND (&&)

// Return true if "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.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

TRY:

1. Write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17, but not by 30.
2. Write a program to print all the leap years between AD1 and AD2010, and also print the number of leap years.

Type double and Floating-Point Numbers

Recall that a variable in Java has a name and a type, and can hold a value of only that particular type. We have so far used a type called int. A int variable holds an integer, such as 123 and -456; it cannot hold a real number, such as 12.34.

In programming, real numbers such as 3.1416, -55.66 are called floating-point numbers, and belong to a type called double. For example,

1
2
3
4
5
6
7
8
9
10
11



public class CircleOperation { // Saved as "CircleOperation.java"
public static void main(String[] args) {
double radius = 1.2; // Type double for floating-point numbers
double pi = 3.1416;
double area;
area = radius * radius * pi;
System.out.println("The radius is " + radius);
System.out.println("The area is " + area);
System.out.println("The perimeter is " + (2.0 * pi * radius));
}
}

The radius is 1.2
The area is 4.523904
The perimeter is 7.53984

Mixing int and double, and Type Casting

Although you can use a double to keep an integer value (e.g., double count = 5.0), you should use an int for integer, as int is far more efficient than double (e.g., in terms of running times, storage, among others).

At times, you may need both int and double in your program. For example, keeping the sum from 1 to 1000 as int, and their average as double. You need to be extremely careful when different types are mixed.

It is important to note that:

* Arithmetic operations ('+', '-', '*', '/') of two int's produce an int; while arithmetic operations of two double's produce a double. Hence, 1/2 → 0 and 1.0/2.0 → 0.5.
* Arithmetic operations of an int and a double produce a double. Hence, 1.0/2 → 0.5 and 1/2.0 → 0.5.

You can assign an integer value to a double variable. The integer value will be converted to a double value automatically, e.g., 3 → 3.0. For example,

int i = 3;
double d;
d = i; // 3 → 3.0, d = 3.0
d = 88; // 88 → 88.0, d = 88.0
double nought = 0; // 0 → 0.0; there is a subtle difference between int 0 and double 0.0

However, you CANNOT assign a double value directly to an int variable. This is because the fractional part could be lost, and the compiler signals an error in case that you were not aware. For example,

double d = 5.5;
int i;
i = d; // Compilation Error
i = 6.6; // Compilation Error

To assign an double value to an int variable, you need to explicitly invoke a type-casting operation to truncate the fractional part, as follows:

double d = 5.5;
int i;
i = (int) d; // Type-cast the value of double d, which returns an int value,
// assign the resultant int value to int i.
// The value stored in d is not affected.
i = (int) 3.1416; // i = 3

Take note that type-casting operator, in the form of (int) or (double), applies to one operand immediately after the operator (i.e., unary operator).

Type-casting is an operation, like increment or addition, which operates on a operand and return a value (in the specified type), e.g., (int)3.1416 takes a double value of 3.1416 and returns 3 (of type int); (double)5 takes an int value of 5 and returns 5.0 (of type double).

Try the following program and explain the outputs produced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25



/*
* Find the sum and average from a lowerbound to an upperbound
*/
public class TypeCastingTest { // Save as "TypeCastingTest.java"
public static void main(String[] args) {
int lowerbound = 1;
int upperbound = 1000;
int sum = 0; // sum is "int"
double average; // average is "double"
// Compute the sum (in "int")
for (int number = lowerbound; number <= upperbound; number++) {
sum = sum + number;
}
System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
// Compute the average (in "double")
average = sum/1000;
System.out.println("Average 1 is " + average);
average = (double)sum/1000;
System.out.println("Average 2 is " + average);
average = sum/1000.0;
System.out.println("Average 3 is " + average);
average = (double)(sum/1000);
System.out.println("Average 4 is " + average);
}
}

The sum is 500500
Average 1 is 500.0 <== incorrect
Average 2 is 500.5
Average 3 is 500.5
Average 4 is 500.0 <== incorrect

The first average is incorrect, as int/int produces an int (of 500), which is converted to double (of 500.0) to be stored in average (of double).

For the second average, the value of sum (of int) is first converted to double. Subsequently, double/int produces a double.

For the third average, int/double produces double.

For the fourth average, int/int produces an int (of 500), which is casted to double (of 500.0) and assigned to average (of double).

TRY:

1. Write a program called HarmonicSeriesSum to compute the sum of a harmonic series 1 + 1/2 + 1/3 + 1/4 + .... + 1/n, where n = 1000. Keep the sum in a double variable, and take note that 1/2 gives 0 but 1.0/2 gives 0.5.
Try computing the sum for n=1000, 5000, 10000, 50000, 100000.
Hints:

public class HarmonicSeriesSum { // Saved as "HarmonicSeriesSum.java"
public static void main (String[] args) {
int numTerms = 1000;
double sum = 0.0; // For accumulating sum in double
for (int denominator = 1; denominator <= numTerms ; denominator++) {
// Beware that int/int gives int
......
}
// Print the sum
......
}
}

The sum is 7.484470860550343

2. Modify the above program (called GeometricSeriesSum) to compute the sum of this series: 1 + 1/2 + 1/4 + 1/8 + .... (for 1000 terms).
Hints: Use post-processing statement of denominator = denominator*2.

Summary

I have presented the basics for you to get start in programming. To learn programming, you need to understand the syntaxes and features involved in the programming language that you chosen, and you have to practice, practice and practice, on as many problems as you could.
REFERENCES & RESOURCES

* "New to Java Program Center" @ http://www.oracle.com/technetwork/topics/newtojava/overview/index.html, Sun Microsystems (now Oracle).
* "The Java tutorials - Getting Started" @ http://download.oracle.com/javase/tutorial/ Sun Microsystems (now Oracle).
* Y. Daniel Liang, "Introduction to Java Programming", latest edition.
* Deitel & Deitel, "Java, How to Program", latest edition.
* Bruce Eckel, "Thinking in Java", latest edition.

Latest version tested: JDK 1.6
Last modified: September, 2010

Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME

What is Fibonacci Sequence?

A series of whole numbers in which each number is the sum of the two preceding numbers.
Beginning with 0 and 1, the sequence of Fibonacci numbers would be 0,1,1, 2, 3, 5, 8, 13, 21, 34, etc. using the formula n = n(-1) + n(-2), where the n(-1) means “the last number before n in the series” and n(-2) refers to “the second last one before n in the series.

Example: The Fibonacci sequence starts with the numbers 0 and 1. The next number is the sum of these and subsequent numbers are the sum of the preceding pair. so we get 0,1,1,2,3,5....
write a java program to display the first 20 fibonacci numbers using
for loop statement


soln
using FOR.LOOP.

public class JavaFibonacciSeriesExample {

public static void main(String[] args) {

int limit = 20;
long[] series = new long[limit];

series[0] = 0;

series[1] = 1;


for(int i=2; i < limit; i++){

series[i] = series[i-1] + series[i-2];

}


System.out.println("Fibonacci Series upto " + limit);

for(int i=0; i< limit; i++){

System.out.print(series[i] + " ");

}

}

}

Fibonacci Series upto 20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181


yet another insignificant programming notes... | HOME
Java Programming
Java Basics - Exercises
Exercises on Flow Controls
Exercises on Conditional (Decision)

Exercise (if-else): Write a program called CheckMark which prints "PASS" if the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise.

Hints:

public class CheckMark { // saved as "CheckMark.java"
public static void main(String[] args) {
int mark = 49; // set the value of mark here!
System.out.println("The mark is " + mark);

if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}


Exercise (if-else): Write a program called CheckNumber which prints "Odd Number" if the int variable “number” is odd, or “Even Number” otherwise.

Hints:

public class CheckNumber { // saved as "CheckNumber.java"
public static void main(String[] args) {
int number = 49; // set the value of number here!
System.out.println("The number is " + number);
if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}


Exercise (nested-if, switch-case): Write a program called PrintWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable "number" is 1, 2,... , 9 or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case" statement.

Hints:

public class PrintWord { // saved as "PrintWord.java"
public static void main(String[] args) {
int number = 5;

// nested-if
if (number == 1) {
System.out.println("ONE");
} else if (......) {
......
} else if (......) {
......
} else {
......
}

// switch-case
switch(number) {
case 1: System.out.println("ONE"); break;
case 2: ......
......
default: System.out.println("OTHER");
}
}
}

Exercises on Loop (Iteration)

Exercise (Loop): Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to 100. Also compute and display the average. The output shall look like:

The sum is 5050
The average is 50.5

Hints:

public class SumAndAverage { // saved as "SumAndAverage.java"
public static void main (String[] args) {
int sum = 0; // store the accumulated sum
double average; // average in double
int lowerbound = 100; // the lower bound to sum
int upperbound = 100; // the upper bound to sum

for (int number = lowerbound; number <= upperbound; number++) { // for loop
sum += number; // same as "sum = sum + number"
}
// Compute average in double. Beware that int/int produces int.
......
// Print sum and average.
......
}
}

Try:

1. Modify the program to use a "while-do" loop instead of "for" loop.

int number = 1;
int sum = 0;
while (number <= upperbound) {
sum += number;
number++;
}

2. Modify the program to use a "do-while" loop.

int number = 1;
int sum = 0;
do {
sum += number;
number++;
} while (number <= upperbound);

3. Modify the program to sum from 111 to 8989, and compute the average. Introduce an int variable called count to count the numbers in the specified range.

int count = 0;
for (...; ...; ...) {
......
count++;
}

4. Modify the program to sum only the odd numbers from 1 to 100, and compute the average.
5. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
6. 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.


Exercise (Loop): Write a program called Product1toN to compute the product of integers 1 to 10 (i.e., 123...10). Try computing the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results.

Hints: Declares an int variable called product (to accumulate the product) and initialize to 1.


Exercise (Loop): Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50000. The program shall compute the sum from left-to-right as well as from the right-to-left. Obtain the difference between these two sums and explain the difference. Which sum is more accurate?

Hints:

public class HarmonicSum { // saved as "HarmonicSum.java"
public static void main (String[] args) {
int maxDenominator = 50000;
double sumL2R = 0.0; // sum from left-to-right
double sumR2L = 0.0; // sum from right-to-left

// for-loop for summing from left-to-right
for (int denominator = 1; denominator <= maxDenominator; denominator++) {
......
// Beware that int/int gives int.
}
// for-loop for summing from right-to-left
......
// Find the difference and display
......
}
}


Exercise (Loop & Condition): Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π?

JDK maintains the value of π in a double constant called Math.PI. Compare the values obtained, in terms of the ratio between the value computed and the Math.PI, in percents.

Hint: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3.

double sum = 0;
int maxDenom = 10000000;
for (int denom = 1; ..... ; denom = denom + 2) {
if (denom % 4 == 1) {
sum += ......;
} else if (denom % 4 == 3) {
sum -= ......;
} else {
System.out.println("The computer has gone crazy?!");
}
}


Exercise (Loop & Condition): Write a program called CozaLozaWoza which prints the number 1 to 110, 11 numbers per line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on. The output shall look like:

1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
......

Hints:

public class CozaLozaWoza { // saved as "CozaLozaWoza.java"
public static void main(String[] args) {
int lowerbound = 1;
int upperbound = 110;
for (int number = lowerbound; number <= upperbound; number++) {
// 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
if (......) {
......
}
// Print a space
......
// Print a newline if number is divisible by 11
if (......) {
System.out.println();
}
}
}
}


Exercise (Loop): Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. The output shall look like:

The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
The average is 885.5

Hints:

public class Fibonacci {
public static void main (String args[]) {
int n = 3; // the index n for F(n), starting from n=3
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;
double average;

System.out.println("The first " + nMax + " Fibonacci numbers are:");
......

while (n <= nMax) {
// Compute F(n), print it and add to sum
......
// Adjust the index n and shift the numbers
......
}

// Compute and display the average (=sum/nMax)
......
}
}

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)=1, T(2)=1 and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci numbers.
Exercises on Nested-Loop

Exercise (nested-loop): Write a program called SquareBoard that displays the following 5x5 pattern using two nested for-loops.

# # # # #
# # # # #
# # # # #
# # # # #
# # # # #

Your program should use only two output statements, one each of the followings:

System.out.print("# "); // print "# ", without newline
System.out.println(); // print a newline

Hints:

public class SquareBoard { // saved as "SquareBoard.java"
public static void main (String[] args) {
int size = 5; // size of the board
for (int row = 1; ......; ......) {
for (int col = 1; ......; ......) {
......
}
......
}
}
}


Exercise (nested-loop): Write a program called CheckerBoard that displays the following 7x7 checkerboard pattern using two nested for-loops.

# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #

Your program should use only three output statements, one each of the followings:

System.out.print("# "); // print "# ", without newline
System.out.print(" "); // print a space, without newline
System.out.println(); // print a newline

Hints:

public class CheckerBoard { // saved as "CheckerBoard.java"
public static void main (String[] args) {
int size = 7; // size of the board

for (int row = 1; ......; ......) {
// Use modulus 2 to find alternate lines
if ((row % 2) == 0) { // row 2, 4, 6, 8
......
}
for (int col = 1; ......; ......) {
......
}
......
}
}
}


Exercise (nested-loop): Write a program called TimeTable to produce the multiplication table of 1 to 9 as shown using two nested for-loops:

* | 1 2 3 4 5 6 7 8 9
-------------------------------
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81

Modify the program to print the multiplication table of 1 to 12.
Exercises on Input

Exercise (Keyboard Input): Write a program called KeyboardInput to prompt user for an int, a double, and a String. The output shall look like (the inputs are shown in bold):

Enter an integer: 12
Enter a floating point number: 33.44
Enter your name: Peter
Hi! Peter, the sum of 12 and 33.44 is 45.44

Hints:

import java.util.Scanner; // needed to use Scanner for input
public class KeyboardInput {
public static void main(String[] args) {
int num1;
double num2;
String name;
double sum;

// Setup a Scanner called in to scan the keyboard (System.in)
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
num1 = in.nextInt(); // use nextInt() to read int
System.out.print("Enter a floating point number: ");
num2 = in.nextDouble(); // use nextDouble() to read double
System.out.print("Enter your name: ");
name = in.next(); // use next() to read String

// Display
......
}
}


Exercise (File Input): Write a program called FileInput to read an int, a double, and a String form a text file called "in.txt", and produce the following output:

The integer read is 12
The floating point number read is 33.44
The String read is "Peter"
Hi! Peter, the sum of 12 and 33.44 is 45.44

You need to create a text file called "in.txt" (in Eclipse, right-click on the "project" ⇒ "New" ⇒ "File") with the following contents:

12
33.44
Peter

import java.util.Scanner; // Needed to use Scanner for input
import java.io.File; // Needed to use File
import java.io.FileNotFoundException; // Needed for file operation

public class FileInput {
public static void main(String[] args)
throws FileNotFoundException { // Needed for file operation
int num1;
double num2;
String name;
double sum;

// Setup a Scanner to read from a text file
Scanner in = new Scanner(new File("in.txt"));
num1 = in.nextInt(); // use nextInt() to read int
num2 = in.nextDouble(); // use nextDouble() to read double
name = in.next(); // use next() to read String

// Display
......
}
}


Exercise (User Input): Write a program called CircleComputation, which prompts user for a radius and compute the area and perimeter of a circle. The output shall look like:

Enter the radius: 1.2
The area is 4.5239
The perimeter is 7.5398223686155035

Hints: π is kept in a constant called Math.PI.


Exercise (User Input & String Operations): Write a program called ReverseString, which prompts user for a String, and prints the reverse of the String. The output shall look like:

Enter a String: abcdef
The reverse of String "abcdef" is "fedcba".

Hints:

import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
String inStr; // input String
int inStrLen; // length of the input String

Scanner in = new Scanner(System.in);
System.out.print("Enter a String: ");
inStr = in.next(); // use next() to read String
inStrLen = inStr.length();

// Use inStr.charAt(index) to extract character at 'index' from inStr
......
}
}

For a String called inStr, you can use inStr.length() to retrieve the length of the String; and inStr.charAt(index) to retrieve the char at the index position, where index begins with 0.


Exercise (User Input & String Operations): On your phone keypad, the alphabets are mapped to digits as follows: ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9).

Write a program called PhoneKeyPad, which prompts user for a string (case insensitive), and converts to a sequence of digits. Use a nested-if in this exercise. Modify your program to use an array for table look-up later.

Hints: You can use in.next().toLowerCase() to read a string and convert it to lowercase to reduce your cases.


Exercise (Palindrome): A word that reads the same backward as forward is called a palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a program called TestPalindromicWord, that prompts user for a word and prints ""xxx" is|is not a palindrome".

Hints: Read in a word and convert to lowercase via in.next().toLowercase().

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). Modify your program (called TestPalindromicPhrase) to test palindromic phrase.

Hints: Read in the lowercase phrase via in.nextLine().toLowercase(). Maintain two indexes, forwardIndex and backwardIndex, used to scan the phrase forward and backward.


Exercise (Bin2Dec): Write a program called Bin2Dec to convert a binary string into its equivalent decimal number. Your output shall look like:

Enter a Binary string: 1011
The equivalent decimal number for binary "1011" is 11

Enter a Binary string: 1234
Error: Invalid Binary String "1234"

Hints: For a n-bit binary number bn-1bn-2...b1b0, bi∈{0,1}, the equivalent decimal number is bn-1×2n-1+bn-2×2n-2+ ...+b1×21+b0×20.

import java.util.Scanner;
public class Bin2Dec {
public static void main(String[] args) {
String binStr; // input binary string
int binStrLen; // length of the input string
int dec = 0; // equivalent decimal number
char binChar; // each individual char in the binary string

Scanner in = new Scanner(System.in);

// Read input binary string
......

// Convert binary string into Decimal
......
}
}

You can use JDK method Math.pow(x, y) to compute the x raises to the power of y. This method takes two doubles as argument and returns a double. You may have to cast the result back to int.

To convert a char (of digit '0' to '9') to int, simply subtract by '0', e.g., '5'-'0'→5.


Exercise (Hex2Dec): Write a program called HexToDec to convert a hexadecimal string into its equivalent decimal number. Your output shall look like:

Enter a Hexadecimal string: 1a
The equivalent decimal number for hexadecimal "1a" is 26

Enter a Hexadecimal string: 1y3
Error: Invalid Hexadecimal String "1y3"

Hints: For a n-digit hexadecimal number hn-1hn-2...h1h0, hi∈{0,…,9,A,…,F}, the equivalent decimal number is hn-1×16n-1+hn-2×16n-2+ ...+h1×161+h0×160.

You do not need a big nested-if statement of 16 cases (or 22 with upper and lower letters). Extract the individual character from the hexadecimal string, says c. If char c is between '0' to '9', you can get the integer offset via c-'0'. If c is between 'a' to 'f' or 'A' to 'F', the integer offset is c-'a'+10 or c-'A'+10.

String hexStr;
char hexChar;
......
hexChar = hexStr.charAt(i);
......
if (hexChar >= '0' && hexChar <= '9') {
... (hexChar-'0') ...
...
} else if (hexChar >= 'a' && hexChar <= 'f') { // lowercase
... (hexChar-'a'+10) ...
...
} else if (hexChar >= 'A' && hexChar <= 'F') { // uppercase
... (hexChar-'A'+10) ...
...
} else {
System.out.println("Error: Invalid hexadecimal string");
System.exit(1); // quit the program
}

Exercises on Array

Exercise (Array): Write a program called GradesAverage, which reads in n grades (of int between 0 and 100) and displays the average. You should keep the grades in an int[] (an array of int). Your output shall look like:

Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0


Exercise (Array): Write a program called Hex2Bin to convert a hexadecimal string into its equivalent binary string. The output shall look like:

Enter a Hexadecimal string: 1abc
The equivalent binary for hexadecimal "1abc" is 0001 1010 1011 1100

Hints: Use an array of 16 binary Strings corresponding to hexadecimal number '0' to 'F', as follows:

String[] hexBits = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"}

Exercises on Command-line Arguments

Exercise (Command-line arguments): Write a Java program called Arithmetic that takes three command-line arguments: two integers followed by an arithmetic operator (+, -, * or /). The program shall perform the corresponding operation on the two integers and print the result. For example:

> java Arithmetic 3 2 +
3+2=5

> java Arithmetic 3 2 -
3-2=1

> java Arithmetic 3 2 /
3/2=1

Hints:

The method main(String[] args) has a parameter: "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:

> java Arithmetic 12345 4567 +

The three command-line arguments "12345", "4567" and "+" will be captured in a String array and passed into the main() method as parameter args. That is,

args is {"12345", "4567", "+"}; // args is a String array
args.length is 3; // length of the array
args[0] is "12345"; // 1st element of the String array
args[1] is "4567"; // 2nd element of the String array
args[2] is "+"; // 3rd element of the String array
args[0].length() is 5; // length of 1st String element
args[1].length() is 4; // length of the 2nd String element
args[2].length() is 1; // length of the 3rd String element

public class Arithmetic {
public static void main (String[] args) {
int operand1, operand2;
char theOperator;

// Check if there are 3 command-line arguments in the
// String array args[] by using length variable of array.
if (args.length != 3) {
System.err.println("Usage: java Arithmetic int1 int2 op");
return;
}

// Convert the 3 Strings args[0], args[1], args[2] to int and char.
// Use the Integer.parseInt(aStr) to convert a String to an int.
operand1 = Integer.parseInt(args[0]);
operand2 = ......

// Get the operator, assumed to be the first character of
// the 3rd string. Use method charAt() of String.
theOperator = args[2].charAt(0);
System.out.print(args[0] + args[2] + args[1] + "=");

switch(theOperator) {
case ('-'):
System.out.println(operand1 – operand2); break;
case ('+'): ......
case ('*'): ......
case ('/'): ......
default:
System.err.println("\nError: invalid operator!");
}
}
}

Notes:

* To provide command-line arguments, use the "cmd" shell 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?


Exercise (Command-line arguments): Write a Java program called SumDigits to sum up the individual digits of a positive integer, given in the command line. The output shall look like:

> java SumDigits 12345
The sum of digits = 1 + 2 + 3 + 4 + 5 = 15

Exercises on Method

Exercise (Method): Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive) and displays the average, minimum, maximum, and standard deviation. Your program shall check for valid input. You should keep the grades in an int[] and use a method for each of the computations. Your output shall look like:

Enter the number of students: 4
Enter the grade for student 1: 50
Enter the grade for student 2: 51
Enter the grade for student 3: 56
Enter the grade for student 4: 53
The average is 52.5
The minimum is 50
The maximum is 56
The standard deviation is 2.29128784747792

Hints: The formula for calculating standard deviation is:

public class GradesStatistics {
public static int[] grades; // Declare an int[], to be allocated later

// main() method
public static void main(String[] args) {
readGrades();
System.out.println("The average is " + average());
System.out.println("The minimum is " + min());
System.out.println("The maximum is " + max());
System.out.println("The standard deviation is " + stdDev());
}

// Prompt user for the number of students and allocate the "grades" array.
// Then, prompt user for grade, check for valid grade, and store in "grades".
public static void readGrades() { ....... }

// Return the average value of int[] grades
public static double average() { ...... }

// Return the maximum value of int[] grades
public static int max() { ...... }

// Return the minimum value of int[] grades
public static int min() { ....... }

// Return the standard deviation of the int[] grades
public static double stdDev() { ....... }
}


Exercise (Method): Write a program called GradesHistogram, which reads in n grades (of int between 0 and 100, inclusive) from a text file called "grades.in" and displays the histogram. The file has the following format:

numStduents:int
grade1:int grade2:int .... gradeN:int

For example:

15
49 50 51 59 0 5 9 10 15 19 50 55 89 99 100

The output shall consist of a horizontal histogram and a vertical histogram as follows:

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

Hints:

public class GradesHistogram {
public static int[] grades;
// Declare an int array of grades, to be allocated later
public static int[] bins = new int[10];
// Declare and allocate an int array for histogram bins.
// 10 bins for 0-9, 10-19,...., 90-100

public static void main(String[] args) {
readGrades("grades.in");
computeHistogram();
printHistogramHorizontal();
printHistogramVertical();
}

// Read the grades from "filename", store in "grades" array.
// Assume that the inputs are valid.
public static void readGrades(String filename) { ...... }

// Based on "grades" array, populate the "bins" array.
public static void computeHistogram() { ....... }

// Print histogram based on the "bins" array.
public static void printHistogramHorizontal() { ...... }

// Print histogram based on the "bins" array.
public static void printHistogramVertical() { ...... }
}


Exercise (Method): Write a method called reverseArray() with the following signature:

public static void reverseArray(int[] intArray)

The method accepts an int array, and reverses its orders. For example, if the input array is {12, 56, 34, 79, 26}, the reversal is {26, 79, 34, 56, 12}. You MUST NOT use another array in your method (but you need a temporary variable to do the swap). Also write a test class called ReverseArrayTest to test this method. 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").
More Basic Java Exercises

Exercise (JDK Source Code): Extract the source code of the class Math from the JDK source code ("$JAVA_HOME" ⇒ "src.zip" ⇒ "Math.java" under folder "java.lang"). Study how constants such as E and PI are defined. Also study how methods such as abs(), max(), min(), toDegree(), etc, are written.


Exercise (Matrix Operation): Similar to Math class, write a Matrix library that supports matrix operations (such as addition, subtraction, multiplication) via 2D arrays. The operations shall support both doubles and ints. Also write a test class to exercise all the operations programmed.

Hints:

public class Matrix {
public static void printMatrix(int[][] m) { ...... }
public static void printMatrix(double[][] m) { ...... }
public static boolean haveSameDimension(int[][] m1, int[][] m2) { ...... }
public static boolean haveSameDimension(double[][] m1, double[][] m2) { ...... }
public static int[][] add(int[][] m1, int[][] m2) { ...... }
public static double[][] add(double[][] m1, double[][] m2) { ...... }
......
}


Exercise (Special Characters and Escape Sequences): Write a program called PrintAnimalPattern, which uses println() to produce this pattern:

'__'
(©©)
/========\/
/ || %% ||
* ||----||
¥¥ ¥¥
"" ""

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 sign inside a String. Single quote (') does not require escape sign.

Print the same pattern using printf(). Hints: Need to use %% to print a % in printf() because % is the suffix for format specifier.


Exercise (Print Pattern using nested-loop): Write a method to print each of the followings patterns using nested loops in a class called PrintPattern. The signatures of the methods are:

public static void printPatternX(int size) // 'X' from 'A' to ..., size is a positive integer.

# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
(a) (b) (c) (d)

Hints: On the diagonal, row = col. On the opposite diagonal, row + col = size + 1.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(e) (f) (g) (h) (i)

# # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # #
(j) (k) # # # # # # # # #
# # # # # # #
# # # # #
# # #
#
(l)

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
(m) (n) (o) (p)

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
(q) (r)

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
(s) (t)

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
(u)


Exercise (Print Pattern using nested-loop): Write a method to print each of the following patterns using nested-loops in a class called PrintTriangle. The signatures of the methods are:

public static void printXxx(int numRows) // Xxx is the pattern's name

Write the main() which prompts the user for the numRows and prints all the patterns.

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


Exercise (Series): Write a method to compute sin(x) and cos(x) using the following series expansion, in a class called TrigonometricSeries. The headers of the methods are:

public static double sin(double x, int numTerms) // x in radians
public static double cos(double x, int numTerms)

Compare the values computed using the series with the JDK methods Math.sin(), Math.cos() at x=0, π/6, π/4, π/3, π/2 using various numbers of terms.

Hints: Avoid generating large numerator and denominator (which may cause arithmetic overflow, e.g., 13! is out of int range). Compute the terms as:


Exercise (Series): Write a method to compute the sum of the series in a class called Series. The signature of the method is:

public static double sumOfSeries(double x, int numTerms)


Exercise (Fibonacci Number & 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-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 room for the next Fibonacci number).

Write a similar program for Tribonacci numbers.


Exercise (Factorial & Overflow): Write a program called Factorial1to10, to compute the factorial of n, for 1≤n≤10. Your output shall look like:

The factorial of 1 is 1
The factorial of 2 is 2
...
The factorial of 10 is 3628800

Modify your program (called FactorialInt), to list all the factorials, that can be expressed as an int (i.e., 32-bit signed integer). Your output shall look like:

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: Overflow occurs for Factorial(n+1) if (Integer.MAX_VALUE / Factorial(n)) < (n+1).

Modify your program again (called FactorialLong) to list all the factorials 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.


Exercise (Number Systems Conversion): Write a method call toRadix() which converts a positive integer from one radix into another. The method has the following header:

public static String toRadix(String in, int inRadix, int outRadix) // The input and output are treated as String.

Write a program called NumberConvert, which prompts the user for an input number, 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.


Example: Java code to print prime numbers from 1 to 100
Answer:
Improve
import java.io.*;
class prmNo
{
public static void main(String[] args)
{
Console con = System.console();
System.out.println("Enter length of list :");
int n = con.readLine();
boolean flag;
System.out.print("1 ");
for (int i=2;i<=n;i++)
{
for (int j=2;j{
if (i%j==0)
flag=true;
}
if(!flag)
System.out.print(i+ " ");
flag=false;
}
}
}


Exercise (Guess a Number): Write a Java 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
"
You got it in 4 trials!

Hints: Use Math.random() to produce a random number in double between 0.0 and (less than) 1.0. To produce an int between 0 and 99, use:

int secretNumber = (int)(Math.random()*100);


Exercise (Guess a Word): 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:

java WordGuess testing
Key in one character or your guess word: t
Trail 1: t__t___
Key in one character or your guess word: g
Trail 2: t__t__g
Key in one character or your guess word: e
Trail 3: te_t__g
Key in one character or your guess word: testing
Trail 4: Congratulation!
You got in 4 trials

Hints:

* Set up a boolean array 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 retrieving the word to be guessed from a text file (or a dictionary) randomly.


Exercise (Day of the Week): Write a program called DayOfWeek, which takes a date (in year, month and day), and returns the day of the week.

There is an interesting algorithm for finding the day of week given year, month and day (e.g., 26-9-2010), as follows:

1. Take the last two digit of the year, and add a quarter (divide by 4 and discard the remainder). In our example, 10 + 10/4 = 12
2. Add a value according to the month as follow: Jan: 1, Feb: 4, Mar: 4, Apr: 0, May: 2, Jun: 5, Jul: 0, Aug: 3, Sep: 6, Oct: 1, Nov: 4, Dec: 6. For our example, 12 + 6 (Sep) = 18.
3. Add the day. For our example, 18 + 26 = 44
4. Add a century offset according to century value as follows: 18xx:2, 19xx: 0, 20xx: 6, 21xx: 4. For our example, 44 + 6 (20xx) = 50. For years outside this range, add or subtract 400 to bring the year into this range. This is based on the fact that the calendar repeats every 400 years.
5. For leap year (a leap year is a year that is divisible by 4 and not divisible by 100, or divisible by 400), if month is Jan or Feb, subtract 1. For our example, 2010 is not a leap year.
6. Take modulus 7, and retrieve the day of the week from the array {Sat, Sun, Mon, Tues, Wed, Thurs, Fir}. For our example, 50 % 7 = 1, which is a Sunday.

You can compare the day obtain with the Java's Calendar output as follows:

// Construct a Calendar with the given year, month and day
Calendar cal = new GregorianCalendar(year, month - 1, day); // month is 0-based
// Get the day of the week number: 1 (Sunday) to 7 (Saturday)
int dayNumber = cal.get(Calendar.DAY_OF_WEEK);
String[] calendarDays = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
// Print result
System.out.println("It is " + calendarDays[dayNumber - 1]);

This above algorithm work for Gregorian dates only. 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.

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.
Exercises on Number Theory

Exercise (Perfect and Deficient Numbers): A positive integer is called a perfect number if the sum of all its factors (excluding the number itself, i.e., proper divisor) is equal to its value. For example, the number 6 is perfect because its proper divisors are 1, 2, and 3, and 6=1+2+3; but the number 10 is not perfect because its proper divisors are 1, 2, and 5, and 10≠1+2+5.

A positive integer is called a deficient number if the sum of all its proper divisors is less than its value. For example, 10 is a deficient number because 1+2+5<10; while 12 is not because 1+2+3+4+6>12.

Write a Java method called isPerfect(int posInt) that takes a positive integer, and return true if the number is perfect. Similarly, write a Java method called isDeficient(int posInt) to check for deficient numbers.

Using the methods, write a program called PerfectNumberList that prompts user for an upper bound (a positive integer), and lists all the perfect numbers less than or equal to this upper bound. It shall also list all the numbers that are neither deficient nor perfect. The output shall look like:

Enter the upper bound: 1000
These numbers are perfect:
6 28 496
[3 perfect numbers found (0.30%)]

These numbers are neither deficient nor perfect:
12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 ......
[246 numbers found (24.60%)]


Exercise (Prime): A positive integer is a prime if it is divisible by 1 and itself only. Write a Java method called isPrime(int posInt) that takes a positive integer and returns true if the number is a prime. Write a Java program called PrimeList that prompts the user for an upper bound (a positive integer), and lists all the primes less than or equal to it. Also display the percentage of prime (up to 2 decimal places). The output shall look like:

Please enter the upper bound: 10000
1
2
3
......
......
9967
9973
[1230 primes found (12.30%)]

Hints: To check if a number n is a prime, the simplest way is try dividing n by 2 to √n.


Exercise: Write a method isProductOfPrimeFactors(int posInt) that takes a positive integer, and return true if the product of all its prime factors (excluding 1 and the number itself) is equal to its value. For example, the method returns true for 30 (30=2×3×5) and false for 20 (20≠2×5). You may need to use the isPrime() method in the previous exercise.

Write a program called PerfectPrimeFactorList that prompts user for an upper bound. The program shall display all the numbers (less than or equal to the upper bound) that meets the above criteria. The output shall look like:

Enter the upper bound: 100
These numbers are equal to the product of prime factors:
1 6 10 14 15 21 22 26 30 33 34 35 38 39 42 46 51 55 57 58 62 65 66 69 70 74 77 78 82 85 86 87 91 93 94 95
[36 numbers found (36.00%)]


Exercise (GCD): One of the earlier known algorithms is the Euclid algorithm to find the GCD of two integers (developed by the Greek Mathematician Euclid around 300BC). By definition, GCD(a, b) is the greatest factor that divides both a and b. Assume that a and b are positive integers, and a≥b, the Euclid algorithm is based on these two properties:

GCD(a, 0) = a
GCD(a, b) = GCD(b, a mod b), where (a mod b) denotes the remainder of a divides by b.

For example,

GCD(15, 5) = GCD(5, 0) = 5
GCD(99,88) = GCD(88,11) = GCD(11,0) = 11
GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9

The pseudocode for the Euclid algorithm is as follows:

GCD(a, b) // assume that a ≥ b
while (b != 0) {
// Change the value of a and b: a ← b, b ← a mod b, and repeat until b is 0
temp ← b
b ← a mod b
a ← temp
}
// after the loop completes, i.e., b is 0, we have GCD(a, 0)
GCD is a

Write a method called gcd() with the following signature:

public static int gcd(int a, int b)

Your methods shall handle arbitrary values of a and b, and check for validity.

2 comments:

  1. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete
  2. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete