Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

School of Computing and Informatics

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

1. Read in the circle’s radius

2. Compute the area using the formula:


ng

area = radius × radius × π

3. Display the radius and the area


.A

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

program would look like this:


1 public class ComputeArea{
2 //Code to calculate area will be here
3 }

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:

• Reading the radius.

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.

The complete code for calculating area of a circle is


1 public class ComputeArea{
2 public static void main(String[] args){

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

1.2 Reading Input from the console


Reading input from the console enables the program to accept input from the user.
ng

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

1 Scanner input = new Scanner(System.in)

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 }

Listing 2: Area of Circle with Console input

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

• An identifier cannot be true, false, or null.


• An identifier can be of any length.
NOTE: Identifiers are for naming variables, methods, classes, and other items in a program. Descriptive
identifiers make programs easy to read. Avoid using abbreviations for identifiers. Using complete words
is more descriptive. For example, numberOfStudents is better than numStuds, numOfStuds, or nu-
mOfStudents. We use descriptive names for complete programs in the text. However, we will occasionally
.

use variable names such as i, j, k, x, and y in the code snippets for brevity. These names also provide a
Dr

generic tone to the code snippets.

NOTE: Variables, variable declaration and assignment remains as discussed in C and C++

1.4 Named Constants


A named constant is an identifier that represents a permanent value.

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.

1.5 Naming Conventions

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.

1.6 Numeric Data Types and Operations


Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and %.
.

1.6.1 Numeric Types


Dr

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

and float type.


An

Figure 2: Methods for Scanner Objects


.
Dr

1.6.3 Numeric Operators


The operators for numeric data types include the standard arithmetic operators: addition (+), subtraction
(), multiplication (*), division (/), and remainder (%), as shown in Figure 3. The operands are the values
operated by an operator.
When both operands of a division are integers, the result of the division is the quotient and the frac-
tional part is truncated. For example, 5 / 2 yields 2, not 2.5, and 5 / 2 yields -2, not 2.5. To perform

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

1.6.4 Exponent Operations


.

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.

2.1 boolean Data Type


Ra
The boolean data type declares a variable with the value either true or false.

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

Figure 4: Relational operators

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

3 System.out.println(”The area for the circle of radius ” +


4 radius + ” is ” + area);
5 }

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

will not be executed.

2.3 Two-Way if-else Statements


An if-else statement decides the execution path based on whether the condition is true or false.

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

the condition is true or false.

Here is the syntax for a two-way if-else statement:


1 if (boolean−expression) {
2 //statement(s)−for−the−true−case;
3 }
4 else {
5 //statement(s)−for−the−false−case;
6 }

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

The flowchart of the statement is shown in Figure 6.


For example, consider the following code:
1
2
3
4
5
6
7
if (radius >= 0) {

}
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.

2.4 Nested if and Multi-Way if-else Statements


An

An if statement can be inside another if statement to form a nested if statement.

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.

The nested if statement can be used to implement multiple alternatives.


.

2.5 Generating Random Numbers


Dr

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 }

Listing 3: Subtraction Game


An

2.6 Logical Operators


The logical operators ! (NOT), && (AND), || (OR), and ˆ (exclusive OR) can be used to create a compound
Boolean expression.

Sometimes, whether a statement is executed is determined by a combination of several conditions. You


can use logical operators to combine these conditions to form a compound Boolean expression. Logical
operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value.
.
Dr

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.

3.0.1 Trigonometric Methods


The Math class contains the following methods as shown in Figure 7 for performing trigonometric functions:

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

1 Math.toDegrees(Math.PI / 2) returns 90.0


2 Math.toRadians(30) returns 0.5236 (same as /6)
3 Math.sin(0) returns 0.0
4 Math.sin(Math.toRadians(270)) returns −1.0
5 Math.sin(Math.PI / 6) returns 0.5
6 Math.sin(Math.PI / 2) returns 1.0
An

7 Math.cos(0) returns 1.0


8 Math.cos(Math.PI / 6) returns 0.866
9 Math.cos(Math.PI / 2) returns 0
10 Math.asin(0.5) returns 0.523598333 (same as /6)
11 Math.acos(0.5) returns 1.0472 (same as /3)
12 Math.atan(1.0) returns 0.785398 (same as /4)

3.0.2 Exponent Methods


.

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

3.0.4 The min, max and abs Methods


The min and max methods return the minimum and maximum numbers of two numbers (int, long, float,
or double). For example, max(4.4, 5.0) returns 5.0, and min(3, 2) returns 2.

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

3.0.5 The random Method


You have used the random() method in the preceding section. This method generates a random double
value greater than or equal to 0.0 and less than 1.0 (0 ≤ M ath.random() < 1.0). You can use it to write a
simple expression to generate random numbers in any range. For example,

l
ae
ph
In general,

3.1 The String Type


Ra
u
A string is a sequence of characters.

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

arguments. Recall that the syntax to invoke a static method is ClassName.methodName(arguments).

ph
For example, the pow method in the Math class can be invoked using Math.pow(2, 2.5).

3.1.1 Getting String Length


You can use the length() method to return the number of characters in a string. For example, the following

1
2
3
code
String message = ”Welcome to Java”;
System.out.println(”The length of ” + message + ” is ”
+ message.length());

displays The length of Welcome to Java is 15.


Ra
u
When you use a string, you often know its literal value. For convenience, Java allows you to use the string
literal to refer directly to strings without creating new variables. Thus, ”Welcome to Java”.length() is
correct and returns 15. Note that ”” denotes an empty string and ””.length() is 0.
l
gu

3.1.2 Getting Characters from a String


The s.charAt(index) method can be used to retrieve a specific character in a string s, where the index is
between 0 and s.length() - 1. For example, message.charAt(0) returns the character W, as shown in
Figure 11. Note that the index for the first character in the string is 0.
. An

Figure 11: Accessing characters in a String object using index


Dr

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.

3.1.3 Concatenating Strings


You can use the concat method to concatenate two strings. The statement shown below, for example,
concatenates strings s1 and s2 into s3:

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;

3.1.4 Converting Strings


The toLowerCase() method returns a new string with all lowercase letters and the toUpperCase()

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.

3.1.5 Reading a String from the Console

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

4 System.out.println(”The line entered is ” + s);

3.1.6 Reading a Character from the Console


To read a character from the console, use the nextLine() method to read a string and then invoke the
charAt(0) method on the string to return a character. For example, the following code reads a character
from the keyboard:
.

1 Scanner input = new Scanner(System.in);


Dr

2 System.out.print(”Enter a character: ”);


3 String s = input.nextLine();
4 char ch = s.charAt(0);
5 System.out.println(”The character entered is ” + ch);

3.2 Comparing Strings


The String class contains the methods as shown in Figure 12 for comparing two strings
How do you compare the contents of two strings? You might attempt to use the == operator,as follows:

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

So, how do you solve this problem?

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 }

4.2 The do-while loop

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);

Its execution flowchart is shown in Figure 14


Ra
l u
gu
. An

.
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.

Often you write a while loop in the following common form:


1 i = initialValue ; // Initialize loop control variable
2 while ( i < endValue)
3 // Loop body
4 ...
i++; // Adjust loop control variable

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 }

In general, the syntax of a for loop is:


1 for ( initial −action; loop−continuation−condition; action−after−each−iteration) {
2 // Loop body;

Ra
3 Statement(s);
4 }

The flowchart of the for loop is shown in Figure 15.


l u
gu
. An
Dr

.
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

4.4 Nested Loops


A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops.
Each time the outer loop is repeated, the inner loops are re-entered, and started anew.

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 }

Listing 4: Multiplication table using for loop

Figure 17 shows the output of the code in Listing 4.


Ra
l u
gu
An

.
Figure 17: Multiplication Table

Greatest Common Divisor


.

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

int gcd = 1; // Initial gcd is 1


int k = 2; // Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
Ra
17 gcd = k; // Update gcd
u
18 k++;
19 }
20
l
21 System.out.println(”The greatest common divisor for ” + n1 +
” and ” + n2 + ” is ” + gcd);
gu

22
23 }
24 }

Listing 6: GCD of two integers


An

4.5 Keywords break and continue


The break and continue keywords provide additional controls in a loop.

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

program to demonstrate the effect of using break in a loop.


You can also use the continue keyword in a loop. When it is encountered, it ends the current iteration and
program control goes to the end of the loop body. In other words, continue breaks out of an iteration while
the break keyword breaks out of a loop.

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

You may rewrite the code without using break as follows:


1 boolean found = false;
2 int factor = 2;
3 while ( factor <= n && !found) {
An

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);

Listing 8: Factor of a number without using break


.

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

Listing 9: Palindrome checker

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 }

Listing 10: Perfect Numbers less than 10000

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

The preceding code can be simplified as follows:


1 public static int sum(int i1, int i2) {
2 int result = 0;
3 for ( int i = i1; i <= i2; i++)
4 result += i;
An

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.

The syntax for defining a method is as follows:


1 modifier returnValueType methodName(list of parameters) {
2 // Method body;
3 }

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.

5.2 Calling a Method


Calling a method executes the code in the method.

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

5 while (k <= n1 && k <= n2) {


u
6 if (n1 % k == 0 && n2 % k == 0)
7 gcd = k; // Update gcd
8 k++;
l
9 }
gu

10 return gcd; // Return gcd


11 }

5.3 Overloading methods


An

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) {
.

2 if (num1 > num2)


3 return num1;
Dr

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.

5.5 Example: Generating Random Characters

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’ ;

Thus, a random integer between (int)’a’ and (int)’z’ is


u
1 ( int )(( int ) ’a’ + Math.random() ∗ ((int)’z’ − (int)’a’ + 1));

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

1 ’a’ + Math.random() ∗ (’z’ − ’a’ + 1);

and a random lowercase letter is


1 (char)( ’a’ + Math.random() ∗ (’z’ − ’a’ + 1));
An

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 }

and this method can be reused to get a random lower-case character as


1 public static char getRandomLowerCaseLetter() {
.

2 return getRandomCharacter(’a’, ’z’);


}
Dr

Dr. Raphael Angulu, BCS 210/BIT 210 SCI, MMUST, 2023: Initial Chapters Notes 29

You might also like