03-An Introduction To Java Programming For First-Time Programmers - Java Programming Tutorial
03-An Introduction To Java Programming For First-Time Programmers - Java Programming Tutorial
1 of 12
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
Introduction to Java
Programming
(for Novices & First-Time
Programmers)
Step 1: Write the Source Code: Enter the following source codes using a programming text editor (such as TextPad or NotePad++ for
Windows; jEdit or gedit for Mac OS X; gedit for Ubuntu); or an Interactive Development Environment (IDE) (such as Eclipse or NetBeans).
Do not enter the line numbers (on the left panel), which were added to aid in the explanation. Save the source file as " Hello.java". A Java source
file should be saved with a file extension of ".java". The filename shall be the same as the classname - in this case "Hello".
1
2
3
4
5
6
7
8
/*
* First Java program, which says "Hello, world!"
*/
public class Hello {
// Save as "Hello.java"
public static void main(String[] args) {
System.out.println("Hello, world!");
// print message
}
}
Step 2: Compile the Source Code: Compile the source code "Hello.java" into portable bytecode "Hello.class" using JDK Compiler
"javac". Start a CMD Shell (Windows) or Terminal (UNIX/Linux/Mac OS X) and issue this command:
prompt> javac Hello.java
There is no need to explicitly compile the source code under IDEs (such as Eclipse or NetBeans), as they perform incremental compilation implicitly.
Step 3: Run the Program: Run the program using Java Runtime "java", by issuing this command:
prompt> java Hello
Hello, world!
Take note that the Run command is "java Hello" without the ".class" extension.
On IDEs (such as Eclipse or NetBeans), right-click on the source file Run As... Java Application.
07/08/2015 1:57 PM
2 of 12
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
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".
System.out.println("Hello, world!");
In Line 6, the statement System.out.println("Hello, world!") is used to print the message string "Hello, world!" to the display console. 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.
Block : A block is a group of programming statements enclosed by braces { }. This group of statements is treated as one single unit. 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.
Comments : A multi-line comment begins with /* and ends with */. An end-of-line comment begins with // and lasts till the end of the line.
Comments are NOT executable statements and are ignored by the compiler. But they provide useful explanation and documentation. Use
comments liberally.
Whitespaces : Blank, tab, and newline are collectively called whitespace. Extra whitespaces are ignored, i.e., only one whitespace is needed to
separate the tokens. But they could help you and your readers better understand your program. Use extra whitespaces liberally.
Case Sensitivity : Java is case sensitive - a ROSE is NOT a Rose, and is NOT a rose. The filename is also case-sensitive.
Hello, world!
Hello, world!Hello,
world!Hello, world!
Exercises
1. Print each of the following patterns. Use one System.out.println(...) statement for each line of outputs.
* * * * *
* * * * *
* * * * *
07/08/2015 1:57 PM
3 of 12
* * * * *
* * * * *
* * * * *
* * * * *
(a)
*
*
*
* * * *
(b)
*
*
*
*
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
*
*
*
* *
*
(c)
/*
* Sum five numbers and print the result
*/
public class FiveNumberSum {
// Save as "FiveNumberSum.java"
public static void main(String[] args) {
int number1 = 11; // Declare 5 int variables to hold 5 integers
int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;
int sum;
// Declare an int variable called sum to hold the 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
}
}
int
int
int
int
int
number1
number2
number3
number4
number5
=
=
=
=
=
11;
22;
33;
44;
55;
declare five int (integer) variables called number1, number2, number3, number4, and number5; and assign values of 11, 22, 33, 44 and 55 to the
variables, respectively, via the so-called assignment operator '='. You could also declare many variables in one statement, separating with commas,
e.g.,
int number1 = 11, number2 = 22, number3 = 33, number4 = 44, number5 = 55;
int sum;
declares an int (integer) variable called sum, without assigning an initial value.
Exercise
1. Modify the above program to print the product of 5 integers. Use a variable called product to hold the product, and * for multiplication.
6. What is a Program?
A program is a sequence of instructions (called programming statements), executing one after
another - usually in a sequential manner, as illustrated in the following flow chart.
Example
The following program prints the area and circumference of a circle, given its radius. Take note
that the programming statements are executed sequentially - one after another in the order that
they are written.
07/08/2015 1:57 PM
4 of 12
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
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
/*
* Print the area and circumference of a circle, given its radius.
*/
public class CircleComputation { // Saved as "CircleComputation.java"
public static void main(String[] args) {
// Declare variables
double radius, area, circumference;
final double PI = 3.14159265;
// Assign a value to radius
radius = 1.2;
// Compute area and circumference
area = radius * radius * PI;
circumference = 2.0 * radius * PI;
// Print results
System.out.print("The radius is "); // Print description
System.out.println(radius);
// Print the value stored in the variable
System.out.print("The area is ");
System.out.println(area);
System.out.print("The circumference is ");
System.out.println(circumference);
}
}
radius = 1.2;
assigns a value to the variable radius.
Take note that the programming statements inside the main() are executed one after another, in a sequential manner.
Exercises
1. Follow the above example, write a program (called RectangleComputation) to print the area and perimeter of a rectangle, given its length
and width in doubles.
2. Follow the above example, write a program (called CylinderComputation) to print the surface area and volume of a cylinder, given its
radius and height in doubles.
7. 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 of that type.
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
07/08/2015 1:57 PM
5 of 12
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., radius*radius*3.1416).
A variable has a type. Examples of type are:
int: for integers (whole numbers) such as 123 and -456;
double: for floating-point or real numbers, such as 3.1416, -55.66, 7.8e9, -1.2e3.4 having an optional decimal point and fractional
part, in fixed or scientific notations;
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
interpretation of data.
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.
To use a variable, you need to first declare its name and type, in one of the following syntaxes:
varType
varType
varType
varType
varName;
// Declare a variable of a type
varName1, varName2,...; // Declare multiple variables of the same type
varName = initialValue; // Declare a variable of a type, and assign an initial value
varName1 = initialValue1, varName2 = initialValue2,... ; // Declare variables with initial values
//
//
int number1, number2; //
double average;
//
int height = 20;
//
Declare a variable named "sum" of the type "int" for storing an integer.
Terminate the statement with a semi-colon.
Declare 2 "int" variables named "number1" and "number2", separated by a comma.
Declare a variable named "average" of the type "double" for storing a real number.
Declare an "int" variable, and assign an initial value.
Once a variable is declared, you can assign and re-assign a value to the variable, via the so-called assignment operator '='. For example,
int number;
//
number = 99;
//
number = 88;
//
number = number + 1; //
int sum = 0;
//
sum = sum + number;
//
int num1 = 5, num2 = 6;
double radius = 1.5; //
int number;
//
sum = 55.66;
//
sum = "Hello";
//
07/08/2015 1:57 PM
6 of 12
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
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.
x=x+1?
Assignment (=) in programming is different from equality in Mathematics. e.g., "x=x+1" is invalid in Mathematics. However, in programming, it
means compute the value of x plus 1, and assign the result back to variable x.
"x+y=1" is valid in Mathematics, but is invalid in programming. In programming, the RHS of "=" has to be evaluated to a value; while the LHS shall
be a variable. That is, evaluate the RHS first, then assign to LHS.
Some languages uses := as the assignment operator to avoid confusion with equality.
Operator
Meaning
Example
Addition
x + y
Subtraction
x - y
Multiplication
x * y
Division
x / y
Modulus (Remainder)
x % y
++
Increment by 1 (Unary)
++x or x++
--
Decrement by 1 (Unary)
--x or x--
Addition, subtraction, multiplication, division and remainder are binary operators that take two operands (e.g., x + y); while negation (e.g., -x),
increment and decrement (e.g., x++, --x) are unary operators that take only one operand.
Example
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
/**
* 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;
// Print results
System.out.print("The sum, difference, product, quotient and remainder of ");
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;
--number2;
//
//
//
//
// Print description
07/08/2015 1:57 PM
7 of 12
38
39
40
41
42
43
44
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
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
++number1;
--number2;
illustrate the increment and decrement operations. Unlike '+', '-', '*', '/' and '%', which work on two operands (binary operators), '++' and
'--' operate on only one operand (unary operators). ++x is equivalent to x = x + 1, i.e., increment x by 1. You may place the increment operator
before or after the operand, i.e., ++x (pre-increment) or x++ (post-increment). In this example, the effects of pre-increment and post-increment are
the same. I shall point out the differences in later section.
Exercises
1. Combining Lines 19-32 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.
Example
Try the following program, which sums all the integers from a lowerbound (=1) to an upperbound (=1000) using a so-called while-loop.
1
2
3
/*
* Sum from a lowerbound to an upperbound using a while-loop
*/
07/08/2015 1:57 PM
8 of 12
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
int sum = 0;
declares an int variable to hold the sum. This variable will be used to accumulate numbers over the steps in the repetitive loop, and thus
initialized to 0.
As illustrated in the flow chart, the initialization statement is first executed. The test is
then checked. If the test is true, the body is executed. The test is checked again and the
process repeats until the test is false. When the test is false, the loop completes and
program execution continues to the next statement after the loop.
In our program, the initialization statement declares an int variable named number and
initializes it to lowerbound. The test checks if number is equal to or less than the
upperbound. If it is true, the current value of number is added into the sum, and the
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 loop to terminate. Execution then continues to the next statement (in
Line 23).
In this example, the loop repeats upperbound-lowerbound+1 times. After the loop is completed, Line 17 prints the result with a proper
description.
System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
prints the results.
Exercises
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.)
07/08/2015 1:57 PM
9 of 12
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
/*
* 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, upperbound = 1000; // lowerbound and upperbound
int sumOdd = 0;
// For accumulating odd numbers, init to 0
int sumEven = 0;
// For accumulating even numbers, init to 0
int number = lowerbound;
while (number <= upperbound) {
if (number % 2 == 0) { // Even
sumEven += number;
// Same as sumEven = sumEven + number
} else {
// Odd
sumOdd += number;
// Same as sumOdd = sumOdd + number
}
++number; // Next 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));
}
}
int sumOdd = 0;
int sumEven = 0;
declare two int variables named sumOdd and sumEven and initialize them to 0, for accumulating the odd and even numbers, respectively.
if (number % 2 == 0) {
sumEven = sumEven + number;
} else {
sumOdd = sumOdd + number;
}
This is a conditional statement. The conditional statement can take one these forms: if-then or if-then-else.
// if-then
if ( test ) {
true-body;
}
// if-then-else
if ( test ) {
true-body;
} else {
false-body;
}
true.
Comparison Operators
There are six comparison (or relational) operators:
07/08/2015 1:57 PM
10 of 12
Operator
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
Meaning
Example
==
Equal to
x == y
!=
Not equal to
x != y
>
Greater than
x > y
>=
x >= y
<
Less than
x < y
<=
x <= y
Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-equal sign (=) is the assignment operator.
Operator
Meaning
Example
&&
Logical AND
||
Logical OR
Logical NOT
!(x == 8)
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)
Exercises
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. (Hints: use a variable called
count, which is initialized to zero. Increment the count whenever a leap year is found.)
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* Convert temperature between Celsius and Fahrenheit
*/
public class ConvertTemperature { // Save as "ConvertTemperature.java"
public static void main(String[] args) {
double celsius, fahrenheit;
celsius = 37.5;
fahrenheit = celsius * 9.0 / 5.0 + 32.0;
System.out.println(celsius + " degree C is " + fahrenheit + " degree F.");
fahrenheit = 100.0;
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
System.out.println(fahrenheit + " degree F is " + celsius + " degree C.");
}
07/08/2015 1:57 PM
11 of 12
17
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
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;
// error: possible loss of precision
i = 6.6;
// error: possible loss of precision
For example,
double d = 5.5;
int i;
i = (int) d;
i = (int) 3.1416;
//
//
//
//
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).
Example
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
/*
* 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, upperbound = 1000;
int sum = 0;
// sum is "int"
double average;
// average is "double"
// Compute the sum (in "int")
int number = lowerbound;
while (number <= upperbound) {
sum = sum + number;
++number;
}
System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
07/08/2015 1:57 PM
12 of 12
17
18
19
20
21
22
23
24
25
26
27
28
29
30
http://www.ntu.edu.sg/home/ehchua/programming/java/J1a_Introducti...
The sum
Average
Average
Average
Average
Average
from
1 is
2 is
3 is
4 is
5 is
1 to 1000 is 500500
500.0 <== incorrect
500.5
500.0 <== incorrect
500.5
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 fifth average, int/int produces an int (of 500), which is casted to double (of 500.0) and assigned to average (of double).
Exercises
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
int denominator = 1;
while (denominator <= numTerms) {
// Beware that int/int gives int
......
++denominator; // next
}
// Print the sum
......
}
}
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.)
13. 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.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
07/08/2015 1:57 PM