Introduction To Java Programming
Introduction To Java Programming
el
BCS 210 – Object Oriented Programming
ha
Introduction, Selection, Mathematical Functions, Strings, Loops and Methods
1 Introduction
p
1.1 Basics
Ra
Writing a program involves designing a strategy for solving the problem and then using a programming
language to implement that strategy.
Writing a program involves designing algorithms and translating algorithms into programming instruc-
tions, or code. An algorithm describes how a problem is solved by listing the actions that need to be taken
and the order of their execution. Algorithms can help the programmer plan a program before writing it
in a programming language. Algorithms can be described in natural languages or in pseudocode (natural
u
language mixed with some programming code).
The algorithm for calculating the area of a circle can be described as follows:
ul
Remember, its always good practice to outline your program (or its underlying problem) in the form of an
algorithm before you begin coding.
When you codethat is, when you write a programyou translate an algorithm into a program. You al-
ready know that every Java program begins with a class definition in which the keyword class is followed
by the class name. Assume that you have chosen ComputeArea as the class name. The outline of the
Dr
Remember, every Java program must have a main method where program execution begins. The program
is then expanded as follows:
1 public class ComputeArea{
2 public static void main(String[] args){
3 //Step 1: Read radius
4
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 1
5 //Step 2: Calculate area
6
7 //Step 3: Display radius and area
8
9 }
10 }
The program needs to read the radius entered by the user from the keyboard. This raises two important
issues:
el
• Storing the radius in the program.
ha
Lets address the second issue first. In order to store the radius, the program needs to declare a symbol
called a variable. A variable represents a value stored in the computers memory.
Rather than using x and y as variable names, choose descriptive names: in this case, radius for radius,
and area for area. To let the compiler know what radius and area are, specify their data types. That is
p
the kind of data stored in a variable, whether integer, real number, or something else. This is known as
declaring variables. Java provides simple data types for representing integers, real numbers, characters, and
Ra
Boolean types. These types are known as primitive data types or fundamental types.
Real numbers (i.e., numbers with a decimal point) are represented using a method known as floating-
point in computers. So, the real numbers are also called floating-point numbers. In Java, you can use the
keyword double to declare a floating-point variable. Declare radius and area as double. The program can
be expanded as follows:
1 public class ComputeArea{
u
2 public static void main(String[] args){
3 double radius;
4 double area;
ul
5
6 //Step 1: Read radius
7
8 //Step 2: Calculate area
ng
9
10 //Step 3: Display radius and area
11
12 }
13 }
.A
The program declares radius and area as variables. The reserved word double indicates that radius and
area are floating-point values stored in the computer.
The first step is to prompt the user to designate the circles radius. You will soon learn how to prompt the
user for information. For now, to learn how variables work, you can assign a fixed value to radius in the
program as you write the code; later, youll modify the program to prompt the user for this value.
Dr
The second step is to compute area by assigning the result of the expression radius * radius * 3.14159
to area.
In the final step, the program will display the value of area on the console by using the System.out.println
method.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 2
3 double radius;
4 double area;
5
6 //Assign radius a fixed value
7 radius = 7;
8
9 //Step 2: Calculate area
10 area = radius ∗ radius ∗ 3.14159;
11
12 //Step 3: Display radius and area
el
13 System.out.println(”Radius = ” + radius + ” Area = ” + area);
14
15 }
16 }
ha
Listing 1: Area of circle
NOTE: The plus sign (+) has two meanings: one for addition and the other for concatenating (combining)
strings. The plus sign (+) in lines 13 is called a string concatenation operator. It combines two strings into
one. If a string is combined with a number, the number is converted into a string and concatenated with
p
the other string. Therefore, the plus signs (+) in lines 13 concatenate strings into a longer string, which is
then displayed in the output.
1
2
System.out.println(”Introduction to Java Programming,
by R. Angulu”);
Ra
A string cannot cross lines in the source code. Thus, the following statement would result in a compile
error:
To fix the error, break the string into separate sub-strings, and use the concatenation operator (+) to
combine them:
u
1 System.out.println(”Introduction to Java Programming, ” +
2 ”by R. Angulu”);
ul
In Listing 1, the radius is fixed in the source code. To use a different radius, you have to modify the
source code and recompile it. Obviously, this is not convenient, so instead you can use the Scanner class
for console input.
.A
Java uses System.out to refer to the standard output device and System.in to the standard input device.
By default, the output device is the display monitor and the input device is the keyboard. To perform
console output, you simply use the println method to display a primitive value or a string to the console.
Console input is not directly supported in Java, but you can use the Scanner class to create an object to
read input from System.in, as follows:
Dr
The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner
input declares that input is a variable whose type is Scanner. The whole line Scanner input = new
Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An object
may invoke its methods. To invoke a method on an object is to ask the object to perform a task. You can
invoke the nextDouble() method to read a double value as follows:
1 double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to radius. Complete area of
circle program with user input is shown in Listing 2.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 3
1 import java. util .Scanner; // Scanner is a class in java . util package
2 public class ComputeArea{
3 public static void main(String[] args){
4 double radius;
5 double area;
6
7 //Create a Scanner object
8 Scanner input = new Scanner(System.in); //Common error: Scanner input = new Scanner(”System.in”);
9
10 //Promt user to enter radius
l
11 System.out.print(”Enter Radius: ”);
12
ae
13 //Read the value entered and assign it to the variable radius
14 double radius = input.nextDouble();
15
16 //Step 2: Calculate area
17 area = radius ∗ radius ∗ 3.14159;
ph
18
19 //Step 3: Display radius and area
20 System.out.println(”Radius = ” + radius + ” Area = ” + area);
21 }
22 }
Enter key, the program reads the number and assigns it to radius.
1.3 Identifiers
Ra
The statement in line 14 reads input from the keyboard. After the user enters a number and presses the
Identifiers are the names that identify the elements such as classes, methods, and variables in a program.
u
All identifiers must obey the following rules:
• An identifier is a sequence of characters that consists of letters, digits, underscores ( ), and dollar signs
l
($).
gu
• An identifier must start with a letter, an underscore ( ), or a dollar sign ($). It cannot start with a
digit.
• An identifier cannot be a reserved word. (See Appendix A for a list of reserved words.)
An
use variable names such as i, j, k, x, and y in the code snippets for brevity. These names also provide a
Dr
NOTE: Variables, variable declaration and assignment remains as discussed in C and C++
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 4
The value of a variable may change during the execution of a program, but a named constant, or simply
constant, represents permanent data that never changes. In our ComputeArea program, π is a constant.
If you use it frequently, you dont want to keep typing 3.14159; instead, you can declare a constant for π.
Here is the syntax for declaring a constant:
1 final dataType CONSTANTNAME = value;
A constant must be declared and initialized in the same statement. The word final is a Java keyword for
declaring a constant. For example, you can declare π as a constant as
final double PI = 3.14159;
l
1
ae
and use it in the expression for calculating area as
1 double area = radius ∗ radius ∗ PI;
There are three benefits of using constants: (1) you dont have to repeatedly type the same value if it is used
multiple times; (2) if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to
ph
change it only in a single location in the source code; and (3) a descriptive name for a constant makes the
program easy to read.
Ra
Sticking with the Java naming conventions makes your programs easy to read and avoids errors. Conventions
are NOT rules, its like a tradition or common practice of Java programmers.
Make sure that you choose descriptive names with straightforward meanings for the variables, constants,
classes, and methods in your program. As mentioned earlier, names are case sensitive. Listed below are the
conventions for naming variables, methods, and classes.
u
• Use lowercase for variables and methods. If a name consists of several words, concatenate them
into one, making the first word lowercase and capitalizing the first letter of each subsequent wordfor
l
example, the variables radius and area and the method print.
gu
• Capitalize the first letter of each word in a class namefor example, the class names ComputeArea
and System.
• Capitalize every letter in a constant, and use underscores between wordsfor example, the constants
PI and MAX VALUE.
An
Do not choose class names that are already used in the Java library. For example, since the System class
is defined in Java, you should not name your class System.
Every data type has a range of values. The compiler allocates memory space for each variable or constant
according to its data type. Java provides eight primitive data types for numeric values, characters, and
Boolean values. This section introduces numeric data types and operators.
Figure 1 lists the six numeric data types, their ranges, and their storage sizes.
IEEE 754 is a standard approved by the Institute of Electrical and Electronics Engineers for representing
floating-point numbers on computers. The standard has been widely adopted. Java uses the 32-bit IEEE
754 for the float type and the 64-bit IEEE 754 for the double type.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 5
l
ae
ph
Figure 1: Numeric Data Types
Java uses four types for integers: byte, short, int, and long. Choose the type that is most appropri-
Ra
ate for your variable. For example, if you know an integer stored in a variable is within a range of a byte,
declare the variable as a byte. For simplicity and consistency, we will use int for integers most of the time.
Java uses two types for floating-point numbers: float and double. The double type is twice as big as
float, so the double is known as double precision and float as single precision. Normally, you should use
the double type, because it is more accurate than the float type.
u
1.6.2 Reading Numbers from the Keyboard
You know how to use the nextDouble() method in the Scanner class to read a double value from the
l
keyboard. You can also use the methods listed in Figure 2 to read a number of the byte, short, int, long,
gu
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 6
l
ae
Figure 3: Numeric Operators
ph
a float-point division, one of the operands must be a floating-point number. For example, 5.0 / 2 yields 2.5.
The % operator, known as remainder or modulo operator, yields the remainder after division. The operand
on the left is the dividend and the operand on the right is the divisor. Therefore, 7 % 3 yields 1, 3 % 7
yields 3, 12 % 4 yields 0, 26 % 8 yields 2, and 20 % 13 yields 7.
Ra
The % operator is often used for positive integers, but it can also be used with negative integers and
floating-point values. The remainder is negative only if the dividend is negative. For example, -7 % 3 yields
-1, -12 % 4 yields 0, -26 % -8 yields -2, and 20 % -13 yields 7.
Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd
u
number % 2 is always 1. Thus, you can use this property to determine whether a number is even or odd.
If today is Saturday, it will be Saturday again in 7 days. Suppose you and your friends are going to
l
meet in 10 days. What day is in 10 days? You can find that the day is Tuesday using the following
gu
expression:
An
The Math.pow(a, b) method can be used to compute ab . The pow method is defined in the Math class
in the Java API. You invoke the method using the syntax Math.pow(a, b) (e.g., Math.pow(2, 3)), which
Dr
returns the result of ab (23 ). Here, a and b are parameters for the pow method and the numbers 2 and 3
are actual values used to invoke the method. For example,
1 System.out.println(Math.pow(2, 3)); // Displays 8.0
2 System.out.println(Math.pow(4, 0.5)); // Displays 2.0
3 System.out.println(Math.pow(2.5, 2)); // Displays 6.25
4 System.out.println(Math.pow(2.5, −2)); // Displays 0.16
More details on methods will be discussed later. For now, all you need to know is how to invoke the pow
method to perform the exponent operation.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 7
2 Selection
The program can decide which statements to execute based on a condition.
If you enter a negative value for radius in Listing 2, the program displays an invalid result. If the ra-
dius is negative, you dont want the program to compute the area. How can you deal with this situation?
Like all high-level programming languages, Java provides selection statements: statements that let you
choose actions with alternative courses. You can use the following selection statement to replace lines 17-20
el
in Listing 2.
1 if (radius < 0){
2 System.out.println(”Wrong Radius. Radius must be positive”);
ha
3 }
4 else {
5 area = radius ∗ radius ∗ 3.14159;
6 System.out.println(”Radius = ” + radius + ” Area = ” + area);
7 }
p
Selection statements use conditions that are Boolean expressions. A Boolean expression is an expression
that evaluates to a Boolean value: true or false. We now introduce Boolean types and relational operators.
How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than
0? Java provides six relational operators (also known as comparison operators), shown in Figure 4, which
u
can be used to compare two values (assume radius is 5 in the figure). The equality testing operator is two
ul
ng
.A
equal signs (==), not a single equal sign (=). The latter symbol is for assignment.
Dr
2.2 if Statements
An if statement is a construct that enables a program to specify alternative paths of execution.
Java has several types of selection statements: one-way if statements, two-way if-else statements, nested
if statements, multi-way if-else statements, switch statements, and conditional expressions.
A one-way if statement executes an action if and only if the condition is true. The syntax for a one-way if
statement is:
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 8
1 if ( boolean−expresion){
2 //statements to be executed if condition is true
3 }
The flowchart in Figure 5a illustrates how Java executes the syntax of an if statement.
A flowchart is a diagram that describes an algorithm or process, showing the steps as boxes of various
kinds, and their order by connecting these with arrows.
Process operations are represented in these boxes, and arrows connecting them represent the flow of
control. A diamond box denotes a Boolean condition and a rectangle box represents statements.
l
ae
ph
Ra
Figure 5: One-way if flow of execution
If the boolean-expression evaluates to true, the statements in the block are executed. As an example, see
u
the following code:
1 if (radius >= 0) {
l
2 area = radius ∗ radius ∗ PI;
gu
The flowchart of the preceding statement is shown in Figure 5b. If the value of radius is greater than or
equal to 0, then the area is computed and the result is displayed; otherwise, the two statements in the block
An
A one-way if statement performs an action if the specified condition is true. If the condition is false,
nothing is done. But what if you want to take alternative actions when the condition is false? You can use
.
a two-way if-else statement. The actions that a two-way if-else statement specifies differ based on whether
Dr
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 9
l
ae
Figure 6: Two-way if flow of execution: An if-else statement executes statements for the true case if the
ph
Booleanexpression evaluates to true; otherwise, statements for the false case are executed
}
area = radius ∗ radius ∗ PI;
System.out.println(”The area for the circle of radius ” +
radius + ” is ” + area);
else {
System.out.println(”Negative input”);
Ra
8 }
u
If radius >= 0 is true, area is computed and displayed; if it is false, the message ”Negative input” is
displayed.
l
gu
As usual, the braces can be omitted if there is only one statement within them. The braces enclosing the
System.out.println(”Negative input”) statement can therefore be omitted in the preceding example.
The statement in an if or if-else statement can be any legal Java statement, including another if or
if-else statement. The inner if statement is said to be nested inside the outer if statement. The inner if
statement can contain another if statement; in fact, there is no limit to the depth of the nesting.
You can use Math.random() to obtain a random double value between 0.0 and 1.0, excluding 1.0.
Suppose you want to develop a program for a first-grader to practice subtraction. The program randomly
generates two single-digit integers, number1 and number2, with number1 ¿= number2, and it displays to
the student a question such as What is 9 - 2? After the student enters the answer, the program displays a
message indicating whether it is correct.
Invoking random() method returns a random double value d such that 0.0 ≤ d < 1.0. Thus, (int)(Math.random()
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 10
* 10) returns a random single-digit integer (i.e., a number between 0 and 9).
See the code in Listing 3 for a a complete program that generates two random numbers between 0 and
10 and subtracts the smaller number from the larger number. The program asks the user for difference and
displays a message to the user.
1 import java. util .Scanner;
2 public class RandomNumbers {
3 public static void main(String[] args) {
4 int number1 = (int)(Math.random() ∗ 10);
l
5 int number2 = (int)(Math.random() ∗ 10);
ae
6
7 //swap if number1 is less than number2 to avoid negative results
8 if (number1 < number2)
9 {
10 int temp = number1;
ph
11 number1 = number2;
12 number2 = temp;
13 }
14 //Ask a user to enter an answer
15 System.out.print(”What is ” + number1 + ” − ” + number2 + ”? ”);
16 Scanner input = new Scanner(System.in);
Ra
17 int resp = input.nextInt();
18
19 //Perform the difference
20 int diff = number1 − number2;
21
22 //compare user input with the actual difference
23 if (resp == diff){
24 System.out.println(”Your answer is Correct! \n” +
25 number1 + ” − ” + number2 + ” = ” + diff);
u
26 }
27 else
28 System.out.println(”Your answer is Wrong! \n” +
l
29 number1 + ” − ” + number2 + ” = ” + diff);
gu
30 }
31 }
3 Mathematical Functions
The focus of this section is to introduce mathematical functions, characters, string objects, and use them
to develop programs.
Java provides many useful methods in the Math class for performing common mathematical functions.
A method is a group of statements that performs a specific task. You have already used the pow(a, b)
method to compute ab , Exponent Operations and the random() method for generating a random number.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 11
This section introduces other useful methods in the Math class. They can be categorized as trigonometric
methods, exponent methods, and service methods. Service methods include the rounding, min, max, abso-
lute, and random methods. In addition to methods, the Math class provides two useful double constants,
PI and E (the base of natural logarithms). You can use these constants as Math.PI and Math.E in any
program.
l
ae
ph
Ra
Figure 7: Trigonometric Methods in the Math Class
u
The parameter for sin, cos, and tan is an angle in radians. The return value for asin, acos, and atan is a
degree in radians in the range between −π/2 and π/2. One degree is equal to π/180 in radians, 90 degrees
l
is equal to π/2 in radians, and 30 degrees is equal to π/6 in radians. For example
gu
There are five methods related to exponents in the Math class as shown in Figure 8.
Dr
For example,
1 Math.exp(1) returns 2.71828
2 Math.log(Math.E) returns 1.0
3 Math.log10(10) returns 1.0
4 Math.pow(2, 3) returns 8.0
5 Math.pow(3, 2) returns 9.0
6 Math.pow(4.5, 2.5) returns 22.91765
7 Math.sqrt(4) returns 2.0
8 Math.sqrt(10.5) returns 4.24
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 12
el
Figure 8: Exponents Methods in the Math Class
ha
3.0.3 The Rounding Methods
The Math class contains four rounding methods as shown in Figure 9.
p
Ra
Figure 9: Rounding Methods in the Math Class
u
1 Math.ceil(2.1) returns 4.0
Math.ceil(2.0) returns 2.0
ul
2
3 Math.ceil(−2.0) returns −2.0
4 Math.ceil(−2.1) returns −2.0
5 Math.floor(2.1) returns 2.0
6 Math.floor(2.0) returns 2.0
ng
7 Math.floor(−2.0) returns 2 .0
8 Math.floor(−2.1) returns −4.0
9 Math.rint(2.1) returns 2.0
10 Math.rint(−2.0) returns 2 .0
11 Math.rint(−2.1) returns −2.0
Math.rint(2.5) returns 2.0
.A
12
13 Math.rint(4.5) returns 4.0
14 Math.rint(−2.5) returns −2.0
15 Math.round(2.6f) returns 3 // Returns int
16 Math.round(2.0) returns 2 // Returns long
17 Math.round(−2.0f) returns −2 // Returns int
18 Math.round(−2.6) returns −3 // Returns long
19 Math.round(−2.4) returns −2 // Returns long
Dr
The abs method returns the absolute value of the number (int, long, float, or double). For example,
1 Math.max(2, 3) returns 3
2 Math.max(2.5, 3) returns 4.0
3 Math.min(2.5, 4.6) returns 2.5
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 13
4 Math.abs(−2) returns 2
5 Math.abs(−2.1) returns 2.1
l
ae
ph
In general,
The char type represents only one character. To represent a string of characters, use the data type called
l
String. For example, the following code declares message to be a string with the value ”Welcome to
gu
Java”.
1 String message = ”Welcome to Java”;
String is a predefined class in the Java library, just like the classes System and Scanner. The String type
is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type
An
for a variable. The variable declared by a reference type is known as a reference variable that references an
object. Here, message is a reference variable that references a string object with contents Welcome to
Java.
Reference data types will be discussed in detail when we cover Objects and Classes. For the time be-
ing, you need to know only how to declare a String variable, how to assign a string to the variable, and
how to use the methods in the String class.
.
Figure 10 lists the String methods for obtaining string length, for accessing characters in the string, for
Dr
concatenating strings, for converting a string to upper or lowercases, and for trimming a string.
Strings are objects in Java. The methods in Figure 10 can only be invoked from a specific string instance.
For this reason, these methods are called instance methods. A non-instance method is called a static
method.
A static method can be invoked without using an object. All the methods defined in the Math class
are static methods. They are not tied to a specific object instance. The syntax to invoke an instance
method is referenceVariable.methodName(arguments). A method may have many arguments or no
arguments. For example, the charAt(index) method has one argument, but the length() method has no
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 14
l
ae
Figure 10: Simple Methods for String Objects
ph
For example, the pow method in the Math class can be invoked using Math.pow(2, 2.5).
1
2
3
code
String message = ”Welcome to Java”;
System.out.println(”The length of ” + message + ” is ”
+ message.length());
NOTE: Attempting to access characters in a string s out of bounds is a common programming error. To
avoid it, make sure that you do not use an index beyond s.length() 1. For example, s.charAt(s.length())
would cause a StringIndexOutOfBoundsException.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 15
1 String s3 = s1.concat(s2);
Because string concatenation is heavily used in programming, Java provides a convenient way to accomplish
it. You can use the plus (+) operator to concatenate two strings, so the previous statement is equivalent to
1 String s3 = s1 + s2;
l
method returns a new string with all uppercase letters. For example,
ae
1 ”Welcome”.toLowerCase() returns a New string welcome.
2 ”Welcome”.toUpperCase() returns a New string WELCOME.
The trim() method returns a new string by eliminating whitespace characters (like tab, spaces, new line,
carriage return) from both ends of the string.
ph
1 ”\t Good Night \n \r ”.trim() returns a New string Good Night.
1
2
3
4
following code reads three strings from the keyboard:
Scanner input = new Scanner(System.in);
System.out.print(”Enter three words separated by spaces: ”);
String s1 = input.next();
String s2 = input.next();
Ra
To read a string from the console, invoke the next() method on a Scanner object. For example, the
5 String s3 = input.next();
u
6 System.out.println(”s1 is ” + s1);
7 System.out.println(”s2 is ” + s2);
8 System.out.println(”s3 is ” + s3);
l
The next() method reads a string that ends with a whitespace character. You can use the nextLine()
gu
method to read an entire line of text. The nextLine() method reads a string that ends with the Enter key
pressed. For example, the following statements read a line of text.
1 Scanner input = new Scanner(System.in);
2 System.out.println(”Enter a line : ”);
3 String s = input.nextLine();
An
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 16
l
ae
Figure 12: Comparison Methods for String Objects
1 if ( string1 == string2)
2 System.out.println(”string1 and string2 are the same object”);
ph
3 else
4 System.out.println(”string1 and string2 are different objects”);
However, the == operator checks only whether string1 and string2 refer to the same object; it does not tell
you whether they have the same contents. Therefore, you cannot use the == operator to find out whether
two string variables have the same contents. Instead, you should use the equals method. The following
1
2
3
4
code, for instance, can be used to compare two strings:
if ( string1 .equals( string2 ))
else
System.out.println(”string1 and string2 are not equal”);
Ra
System.out.println(”string1 and string2 have the same contents”);
For example, the following statements display true and then false.
u
1 String s1 = ”Welcome to Java”;
2 String s2 = ”Welcome to Java”;
3 String s3 = ”Welcome to C++”;
l
4 System.out.println(s1.equals(s2)) ; // true
System.out.println(s1.equals(s3)) ; // false
gu
4 Loops
A loop can be used to tell a program to execute statements repeatedly.
An
Suppose that you need to display a string (e.g., Welcome to Java!) a hundred times. It would be te-
dious to have to write the following statement a hundred times:
.
Dr
Java provides a powerful construct called a loop that controls how many times an operation or a sequence
of operations is performed in succession. Using a loop statement, you simply tell the computer to display a
string a hundred times without having to code the print statement a hundred times, as follows:
1 int count = 0;
2 while (count < 100) {
3 System.out.println(”Welcome to Java!”);
4 count++;
5 }
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 17
The variable count is initially 0. The loop checks whether count ¡ 100 is true. If so, it executes the loop
body to display the message Welcome to Java! and increments count by 1. It repeatedly executes the loop
body until count < 100 becomes false. When count < 100 is false (i.e., when count reaches 100), the loop
terminates and the next statement after the loop statement is executed.
Loops are constructs that control repeated executions of a block of statements. The concept of looping
is fundamental to programming. Java provides three types of loop statements: while loops, do-while
loops, and for loops.
el
4.1 The while Loop
A while loop executes statements repeatedly while the condition is true. The syntax for the while loop is:
ha
1 initialization ;
2 while (loop−continuation−condition) {
3 // Loop body
4 Statement(s);
5 }
p
The while loop flow of execution is shown In Figure 13
Ra
u
ul
ng
Figure 13: The while loop repeatedly executes the statements in the loop body when the loop-continuation-
condition evaluates to true
.A
Example code below shows how to repeat subtraction quiz until you get
1 import java. util .Scanner;
2 public class RandomNumbers2 {
3 public static void main(String[] args) {
4 int number1 = (int)(Math.random() ∗ 10);
5 int number2 = (int)(Math.random() ∗ 10);
Dr
6
7 //swap if number1 is less than number2 to avoid negative results
8 if (number1 < number2)
9 {
10 int temp = number1;
11 number1 = number2;
12 number2 = temp;
13 }
14 //Ask a user to enter an answer
15 System.out.print(”What is ” + number1 + ” − ” + number2 + ”? ”);
16 Scanner input = new Scanner(System.in);
17 int resp = input.nextInt();
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 18
18
19 //Perform the difference
20 int diff = number1 − number2;
21
22 //repeat if user entered wrong answer
23 while ( resp != diff ){
24 System.out.print(”Wrong Answer. Try again. \nWhat is ” +
25 number1 + ” − ” + number2 + ”? ”);
26 resp = input.nextInt();
27 }
l
28 System.out.println(”Your answer is Correct! \n” +
29 number1 + ” − ” + number2 + ” = ” + diff);
ae
30 }
31 }
ph
A do-while loop is the same as a while loop except that it executes the loop body first and then checks the
loop continuation condition.
The do-while loop is a variation of the while loop. Its syntax is:
1
2
3
4
do {
// Loop body;
Statement(s);
} while (loop−continuation−condition);
.
Dr
Figure 14: The do-while loop executes the loop body first, then checks the loop-continuation-condition to
determine whether to continue or terminate the loop.
The loop body is executed first, and then the loop-continuation-condition is evaluated. If the evaluation
is true, the loop body is executed again; if it is false, the do-while loop terminates.
The difference between a while loop and a do-while loop is the order in which the loop-continuation-condition
is evaluated and the loop body executed. You can write a loop using either the while loop or the do-while
loop. Sometimes one is a more convenient choice than the other.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 19
4.3 The for loop
A for loop has a concise syntax for writing loops.
l
5
6 }
ae
A for loop can be used to simplify the preceding while loop as:
1 for ( i = initialValue ; i < endValue; i++)
2 // Loop body
3 ...
ph
4 }
Ra
3 Statement(s);
4 }
.
Figure 15: A for loop performs an initial action once, then repeatedly executes the statements in the loop
body, and performs an action after an iteration when the loop-continuation-condition evaluates to true.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 20
The for loop statement starts with the keyword for, followed by a pair of parentheses enclosing the con-
trol structure of the loop. This structure consists of initial-action, loop-continuation-condition, and
action-after-each-iteration. The control structure is followed by the loop body enclosed inside braces.
The initial-action, loop-continuation-condition, and action-after-each-iteration are separated by
semicolons.
A for loop generally uses a variable to control how many times the loop body is executed and when
the loop terminates. This variable is referred to as a control variable. The initial-action often initializes
a control variable, the action-after-each-iteration usually increments or decrements the control
l
variable, and the loop-continuation-condition tests whether the control variable has reached a termi-
ae
nation value.
NOTE: The control variable must be declared inside the control structure of the loop or before the loop.
If the loop control variable is used only in the loop, and not elsewhere, it is a good programming practice
ph
to declare it in the initial-action of the for loop. If the variable is declared inside the loop control structure,
it cannot be referenced outside the loop.
The initial-action in a for loop can be a list of zero or more comma-separated variable declaration statements
or assignment expressions. For example:
1
2
3
for ( int i = 0, j = 0; i + j < 10; i++, j++) {
}
// Do something
Ra
The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. For
example:
1 for ( int i = 1; i < 100; System.out.println(i ) , i++);
u
This example is correct, but it is a bad example, because it makes the code difficult to read. Normally, you
declare and initialize a control variable as an initial action and increment or decrement the control variable
l
as an action after each iteration.
gu
If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given
below in Figure 16 (a), which is an infinite loop, is the same as in (b). To avoid confusion, though, it is
better to use the equivalent loop in (c).
An
.
Figure 16
.
Dr
Listing 4 presents a program that uses nested for loops to display a multiplication table.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 21
1 public class MultiplicationTable {
2 /∗∗ Main method ∗/
3 public static void main(String[] args) {
4 // Display the table heading
5 System.out.println(” Multiplication Table”);
6
7 // Display the number title
8 System.out.print(” ”);
9 for ( int j = 1; j <= 9; j++)
10 System.out.printf(”%4d”, j);
l
11
12 System.out.println(”\n−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−”);
ae
13
14 // Display table body
15 for ( int i = 1; i <= 9; i++) {
16 System.out.print(i + ” | ”);
17 for ( int j = 1; j <= 9; j++) {
ph
18 // Display the product and align properly
19 System.out.printf(”%4d”, i ∗ j ) ;
20 }
21 System.out.println() ;
22 }
23 }
24 }
.
Figure 17: Multiplication Table
The greatest common divisor (gcd) of the two integers 4 and 2 is 2. The greatest common divisor of the
two integers 16 and 24 is 8. How would you write this program to find the greatest common divisor? Would
Dr
you immediately begin to write the code? No. It is important to think before you code. Thinking enables
you to generate a logical solution for the problem without concern about how to write the code.
Let the two input integers be n1 and n2. You know that number 1 is a common divisor, but it may
not be the greatest common divisor. So, you can check whether k (for k = 2, 3, 4, and so on) is a common
divisor for n1 and n2, until k is greater than n1 or n2. Store the common divisor in a variable named gcd.
Initially, gcd is 1. Whenever a new common divisor is found, it becomes the new gcd. When you have
checked all the possible common divisors from 2 up to n1 or n2, the value in variable gcd is the greatest
common divisor. Once you have a logical solution, type the code to translate the solution into a Java
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 22
program as follows:
1 int gcd = 1; // Initial gcd is 1
2 int k = 2; // Possible gcd
3 while (k <= n1 && k <= n2) {
4 if (n1 % k == 0 && n2 % k == 0)
5 gcd = k; // Update gcd
6 k++; // Next possible gcd
7 }
8 // After the loop, gcd is the greatest common divisor for n1 and n2
l
Listing 5: GCD of two integers
ae
The code in Listing 6 shows a complete code for getting GCD of two integers entered by a user.
1 public class GreatestCommonDivisor {
2 /∗∗ Main method ∗/
3 public static void main(String[] args) {
ph
4 // Create a Scanner
5 Scanner input = new Scanner(System.in);
6
7 // Prompt the user to enter two integers
8 System.out.print(”Enter first integer : ”);
9 int n1 = input.nextInt();
10
11
12
13
14
15
16
System.out.print(”Enter second integer: ”);
int n2 = input.nextInt();
22
23 }
24 }
Two keywords, break and continue, can be used in loop statements to provide additional controls. Using
break and continue can simplify programming in some cases. Overusing or improperly using them, however,
can make programs difficult to read and debug.
.
You can also use break in a loop to immediately terminate the loop. Program in Figure 18 presents a
Dr
NOTE: The continue statement is always inside a loop. In the while and do-while loops, the loop-
continuation-condition is evaluated immediately after the continue statement. In the for loop, the
action-after-each-iteration is performed, then the loop-continuation-condition is evaluated, immedi-
ately after the continue statement.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 23
l
ae
.
Figure 18: Effect of break keyword
ph
You can always write a program without using break or continue in a loop. In general, though, using
break and continue is appropriate if it simplifies coding and makes programs easier to read.
1
2
3
while ( factor <= n) {
if (n % factor == 0)
Ra
Suppose you need to write a program to find the smallest factor other than 1 for an integer n (assume n >=
2). You can write a simple and intuitive code using the break statement as follows:
int factor = 2;
4 break;
factor++;
u
5
6 }
7 System.out.println(”The smallest factor other than 1 for ” + n + ” is ” + factor);
l
Listing 7: Factor of a number using break
gu
4 if (n % factor == 0)
5 found = true;
6 else
7 factor++;
8 }
9 System.out.println(”The smallest factor other than 1 for ” + n + ” is ” + factor);
Obviously, the break statement makes this program simpler and easier to read in this case. However, you
should use break and continue with caution. Too many break and continue statements will produce a loop
Dr
with many exit points and make the program difficult to read.
Palindrome checker
A string is a palindrome if it reads the same forward and backward. The words mom, dad, and noon, for
instance, are all palindromes.
The problem is to write a program that prompts the user to enter a string and reports whether the string
is a palindrome. One solution is to check whether the first character in the string is the same as the last
character. If so, check whether the second character is the same as the second-to-last character. This process
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 24
continues until a mismatch is found or all the characters in the string are checked, except for the middle
character if the string has an odd number of characters.
The program in Listing 9 reads a string from the keyboard and checks if its a palindrome.
1 import java. util .Scanner;
2 public class Palindrome {
3 /∗∗ Main method ∗/
4 public static void main(String[] args) {
5 // Create a Scanner
el
6 Scanner input = new Scanner(System.in);
7
8 // Prompt the user to enter a string
9 System.out.print(”Enter a string : ”);
ha
10 String s = input.nextLine();
11
12 // The index of the first character in the string
13 int low = 0;
14
// The index of the last character in the string
p
15
16 int high = s.length() − 1;
17
boolean isPalindrome = true;
Ra
18
19 while (low < high) { //loop over the whole string
20 // if current ”low” character is not same as current ”high” character
21 if (s .charAt(low) != s.charAt(high)) {
22 isPalindrome = false; //then, its not a palindrome
23 break; //stop the loop
24 }
25 low++;
26 high−−;
u
27 }
28 if (isPalindrome)
29 System.out.println(s + ” is a palindrome”);
ul
30 else
31 System.out.println(s + ” is not a palindrome”);
32 }
33 }
ng
Example
A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding
itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 +
.A
2 + 1. There are four perfect numbers less than 10,000. Write a program to find all these four numbers.
1 public class PerfectNumber {
2 public static void main(String[] args) {
3 int number = 1;
4 while(number < 10000)
5 {
int sum = 0;
Dr
6
7 int factor = 1;
8 while( factor < number){
9 if ( number % factor == 0)
10 {
11 //System.out.print(factor + ” ”);
12 sum += factor;
13 }
14 factor++;
15 }
16 if ( sum == number)
17 System.out.println(number);
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 25
18 number++;
19 }
20 }
21 }
5 Methods
l
Methods can be used to define reusable code and organize and simplify coding.
ae
Suppose that you need to find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, re-
spectively. You may write the code as follows:
1 int sum = 0;
ph
2 for ( int i = 1; i <= 10; i++)
3 sum += i;
4 System.out.println(”Sum from 1 to 10 is ” + sum);
5
6 sum = 0;
for ( int i = 20; i <= 37; i++)
Ra
7
8 sum += i;
9 System.out.println(”Sum from 20 to 37 is ” + sum);
10
11 sum = 0;
12 for ( int i = 35; i <= 49; i++)
13 sum += i;
14 System.out.println(”Sum from 35 to 49 is ” + sum);
u
You may have observed that computing these sums from 1 to 10, from 20 to 37, and from 35 to 49 are very
similar except that the starting and ending integers are different. Wouldnt it be nice if we could write the
common code once and reuse it? We can do so by defining a method and invoking it.
l
gu
5
6 return result ;
7 }
8
9 public static void main(String[] args) {
10 System.out.println(”Sum from 1 to 10 is ” + sum(1, 10));
11 System.out.println(”Sum from 20 to 37 is ” + sum(20, 37));
12 System.out.println(”Sum from 35 to 49 is ” + sum(35, 49));
13 }
.
Lines 1 - 7 define the method named sum with two parameters i1 and i2. The statements in the main
Dr
method invoke sum(1, 10) to compute the sum from 1 to 10, sum(20, 37) to compute the sum from 20 to
37, and sum(35, 49) to compute the sum from 35 to 49.
A method is a collection of statements grouped together to perform an operation. Earlier, you have used
predefined methods such as System.out.println, Math.pow, and Math.random. These methods are de-
fined in the Java library. Now, you will learn how to define your own methods and apply method abstraction
to solve complex problems.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 26
5.1 Defining a method
A method definition consists of its method name, parameters, return value type, and body.
Lets look at a method defined to find the larger between two integers. This method, named max, has two
l
int parameters, num1 and num2, the larger of which is returned by the method. Figure 19 illustrates the
ae
components of this method.
ph
Ra
Figure 19: Method definition consist of method header and method body
.
u
The method header specifies the modifiers, return value type, method name, and parameters of the method.
The static modifier is used here so that the method can be invoked without creating an object of the class.
l
gu
A method may return a value. The returnValueType is the data type of the value the method returns.
Some methods perform desired operations without returning a value. In this case, the returnValueType
is the keyword void. For example, the returnValueType is void in the main method, as well as in
System.exit, and System.out.println. If a method returns a value, it is called a value-returning method;
otherwise it is called a void method.
An
The variables defined in the method header are known as formal parameters or simply parameters. A
parameter is like a placeholder: when a method is invoked, you pass a value to the parameter. This
value is referred to as an actual parameter or argument. The parameter list refers to the methods type,
order, and number of the parameters. The method name and the parameter list together constitute the
method signature. Parameters are optional; that is, a method may contain no parameters. For example,
the Math.random() method has no parameters.
.
The method body contains a collection of statements that implement the method. The method body
Dr
of the max method uses an if statement to determine which number is larger and return the value of that
number. In order for a value-returning method to return a result, a return statement using the keyword
return is required. The method terminates when a return statement is executed.
In a method definition, you define what the method is to do. To execute the method, you have to call
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 27
or invoke it. There are two ways to call a method, depending on whether the method returns a value or not.
If a method returns a value, a call to the method is usually treated as a value. For example,
1 int larger = max (3, 4);
calls max(3, 4) and assigns the result of the method to the variable larger. Another example of a call that
is treated as a value is
1 System.out.println(max ( 3, 4) ) ;
l
which prints the return value of the method call max(3, 4) If a method returns void, a call to the method
ae
must be a statement. For example, the method println returns void. The following call is a statement:
1 System.out.println(”Welcome to Java!”);
NOTE: A value-returning method can also be invoked as a statement in Java. In this case, the caller simply
ignores the return value. This is not often done, but it is permissible if the caller is not interested in the
ph
return value.
When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method-ending closing brace
is reached.
1
2
3
4
public static int gcd(int n1, int n2) {
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
Ra
Example of a method that return GCD of two integers passed to it
Overloading methods enables you to define the methods with the same name as long as their signatures are
different.
The max method that was used earlier works only with the int data type. But what if you need to determine
which of two floating-point numbers has the maximum value? The solution is to create another method
with the same name but different parameters, as shown in the following code:
1 public static double max(double num1, double num2) {
.
4 else
5 return num2;
6 }
If you call max with int parameters, the max method that expects int parameters will be invoked; if you
call max with double parameters, the max method that expects double parameters will be invoked. This is
referred to as method overloading; that is, two methods have the same name but different parameter lists
within one class. The Java compiler determines which method to use based on the method signature.
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 28
5.4 The scope of variables
The scope of a variable is the part of the program where the variable can be referenced.
A variable defined inside a method is referred to as a local variable. The scope of a local variable starts
from its declaration and continues to the end of the block that contains the variable. A local variable must
be declared and assigned a value before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the entire method.
l
A variable declared in the initial-action part of a for-loop header has its scope in the entire loop. However,
ae
a variable declared inside a for-loop body has its scope limited in the loop body from its declaration to the
end of the block that contains the variable.
ph
A character is coded using an integer. Generating a random character is to generate an integer.
Every character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate
a random character is to generate a random integer between 0 and 65535 using the following expression
Ra
(note that since 0 <= M ath.random() < 1.0, you have to add 1 to 65535):
1 ( int )(Math.random() ∗ (65535 + 1));
Now lets consider how to generate a random lowercase letter. The Unicodes for lowercase letters are
consecutive integers starting from the Unicode for a, then that for b, c, . . . , and z. The Unicode for a is
1 ( int ) ’a’ ;
All numeric operators can be applied to the char operands. The char operand is cast into a number if the
l
other operand is a number or a character. Therefore, the preceding expression can be simplified as follows:
gu
Therefore, a method that return a random character between any two given characters is
1 /∗∗ Generate a random character between ch1 and ch2 ∗/
2 public static char getRandomCharacter(char ch1, char ch2) {
3 return (char)(ch1 + Math.random() ∗ (ch2 − ch1 + 1));
4 }
Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 29