[go: up one dir, main page]

0% found this document useful (0 votes)
14 views45 pages

Day 03 - Characters, String and Selections

The document outlines a lecture on programming concepts, focusing on mathematical functions, character and string manipulation, and conditional statements in Java. It covers the use of the Math class for various mathematical operations, the character data type and its encoding, as well as string operations and methods. The lecture aims to enhance understanding of programming techniques for solving problems using Java.

Uploaded by

cchucc123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views45 pages

Day 03 - Characters, String and Selections

The document outlines a lecture on programming concepts, focusing on mathematical functions, character and string manipulation, and conditional statements in Java. It covers the use of the Math class for various mathematical operations, the character data type and its encoding, as well as string operations and methods. The lecture aims to enhance understanding of programming techniques for solving problems using Java.

Uploaded by

cchucc123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

11/09/2024

Characters, String and Selections


Faculty of Information Technology, Hanoi University

What You Are About To Achieve 2


 The previous lecture introduced fundamental programming techniques and taught
you how to write simple programs to solve basic problems. By the end of this
lecture, we are going to:
 Understand the use of basic math functions such as min, max, and abs to
manipulate numeric values.
 Explore the capabilities of random number generation using the random function
for various use cases.
 Learn how to manipulate and analyze characters and strings through various
string methods and properties.
 Master conditional statements using if, if else, and nested if to control the flow of
your program.
 Implement decision-making logic using switch statements for clearer, structured
branching.
 Apply the ternary operator for concise conditional expressions.
11/09/2024

3
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches

Mathematical Functions 4
 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 in the previous lecture. This section
introduces other useful methods in the Math class. They can be categorized as:
 Trigonometric methods
 Exponent methods
 Service methods
 Service methods include the rounding, minimum, maximum, absolute, 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.
11/09/2024

Mathematical Functions – Trigonometric methods 5


 The Math class contains the following methods as shown below for performing
trigonometric functions:

Mathematical Functions – Trigonometric methods 6


 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 is equal to 𝜋/2 in radians, and 30 degrees is equal
to 𝜋/6 in radians.
 For example:
Math.toDegrees(Math.PI / 2) returns 90.0 Math.cos(0) returns 1.0
Math.toRadians(30) returns 0.5236 (same as π/6) Math.cos(Math.PI / 6) returns 0.866
Math.sin(0) returns 0.0 Math.cos(Math.PI / 2) returns 0 Math.asin(0.5)
Math.sin(Math.toRadians(270)) returns -1.0 returns 0.523598333 (same as π/6)
Math.sin(Math.PI / 6) returns 0.5 Math.acos(0.5) returns 1.0472 (same as π/3)
Math.sin(Math.PI / 2) returns 1.0 Math.atan(1.0) returns 0.785398 (same as π/4)
11/09/2024

Mathematical Functions – Exponents methods 7


 There are five methods related to exponents in the Math class as shown below:

 For example,
 Math.exp(1) returns 2.71828  Math.pow(3, 2) returns 9.0
 Math.log(Math.E) returns 1.0  Math.pow(4.5, 2.5) returns 22.91765
 Math.log10(10) returns 1.0  Math.sqrt(4) returns 2.0
 Math.pow(2, 3) returns 8.0  Math.sqrt(10.5) returns 4.24

Mathematical Functions – Rounding methods 8


 The Math class contains five rounding methods as shown below.

 For example,
 Math.ceil(2.1) returns 4.0  Math.rint(-2.0) returns –2.0
 Math.ceil(2.0) returns 2.0  Math.rint(-2.1) returns -2.0
 Math.ceil(-2.0) returns -2.0  Math.rint(2.5) returns 2.0
 Math.ceil(-2.1) returns -2.0  Math.rint(4.5) returns 4.0
 Math.floor(2.1) returns 2.0  Math.rint(-2.5) returns -2.0
 Math.floor(2.0) returns 2.0  Math.round(2.6f) returns 3 // Returns int
 Math.floor(-2.0) returns –2.0  Math.round(2.0) returns 2 // Returns long
 Math.floor(-2.1) returns -4.0  Math.round(-2.0f) returns -2 // Returns int
 Math.rint(2.1) returns 2.0  Math.round(-2.6) returns -3 // Returns long
 Math.round(-2.4) returns -2 // Returns long
11/09/2024

Mathematical Functions – min, max, abs 9


 If you want to find minimum, maximum of two numbers (int, long, float, double), then
use the min and max methods. But if you want to find the absolute value of a number,
you can use abs method.
 For example,
 Math.max(2, 3) returns 3
 Math.max(2.5, 3) returns 4.0
 Math.min(2.5, 4.6) returns 2.5
 Math.abs(-2) returns 2
 Math.abs(-2.1) returns 2.1

Mathematical Functions – random method 10


 In addition, you can use the random() method to generate a random double value greater
than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). You can use it to write a
simple expression to generate random numbers in any range.
 For example,
(int)(Math.random() * 10) Returns a random integer between 0 and 9.
50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99.

Proposition
 In general,
a + Math.random() * b Returns a random number between a and
a + b, excluding a + b.
11/09/2024

Mathematical Functions – Case Study 11


 Now, you can use the math methods to solve many computational problems. For
example, given the three sides of a triangle, compute the angles by using the following
formula:

Sample run
Enter three points: 1 1 6.5 1 6.5 2.5
The three angles are 15.26 90.0 74.74

“Tired of dealing with numbers?


Let’s switch things up with a new challenge.
12
11/09/2024

13
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches

Character Datatype & Operations 14


 In addition to processing numeric values, you can process characters in Java. The
character data type, char, is used to represent a single character. A character literal is
enclosed in single quotation marks. Consider the following code:
char letter = 'A';
char numChar = '4';
 The first statement assigns character A to the char variable letter. The second statement
assigns digit character 4 to the char variable numChar.
Caution
 A string literal must be enclosed in quotation marks (" "). A character literal is a single
character enclosed in single quotation marks (' '). Therefore, "A" is a string, but 'A' is a
character.
11/09/2024

Character Datatype & Operations 15


 As you know, computers don’t understand letters as we do - they only understand
numbers (0s and 1s). So, when we work with characters in programming, what’s really
happening behind the scenes is that each character is being translated into a unique
numerical code, using a system called encoding. In Java, this encoding is based on
Unicode, a global standard designed to represent characters from virtually every
language. Initially, Unicode could represent up to 65,536 characters, but as the need to
support more languages and symbols grew, it was expanded to handle over a million
characters today.

Character Datatype & Operations 16


 Java’s char data type was originally designed to handle 16-bit Unicode characters.
However, as more characters from around the world needed to be represented, Unicode
was expanded. This encoding system allows us to handle characters from nearly every
language on the planet.
11/09/2024

Character Datatype & Operations 17


 Before Unicode, there was ASCII (American Standard Code for Information
Interchange), which used just 8 bits to represent characters like English letters and
numbers. Unicode not only supports these ASCII characters but expands it further to
represent characters from every language. This gives us a lot of flexibility in Java for
working with different languages and scripts.

Character Datatype & Operations 18


 Here are some commonly used characters…

 You can use ASCII characters such as 'X', '1', and '$' in a Java program as well as
Unicodes. Thus, for example, the following statements are equivalent:
char letter = 'A';
char letter = '\u0041'; // Character A's Unicode is 0041
 Both statements assign character A to the char variable letter.
Caution
 The increment and decrement operators can also be used on char variables to get the next
or preceding Unicode character. For example, the following statements display character b.
char ch = 'a';
System.out.println(++ch);
11/09/2024

19
Nobita
Well, interesting! But, suppose I want to print a message with quotation
marks in the output. Can I write a statement like this?
System.out.println("He said "Java is fun"");

No, this statement has a compile error. The compiler thinks


the second quotation character is the end of the string and
does not know what to do with the rest of characters.
Nobita Delivered
Then how to overcome this?

To address this issue, Java uses a special notation to


represent special characters, as shown in this picture

Delivered

20
Nobita
Uhmmm… I have another question! As you said, each character has their
own numeric value, then can I cast a char to numeric types and vice versa?

The answer is yes! When an integer is cast into a char, only its lower 16
bits of data are used; the other part is ignored. But if a floating-point value
is cast into a char, the floating-point value is first cast into an int, which is
then cast into a char.
char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is
char ch = (char) 65.5; // Decimal 65 is assigned to ch
Nobita
Delivered
What if casting a char into numeric
types?

When a char is cast into a numeric type, the character’s


Unicode is cast into the specified numeric type.
int i = (int)'A'; // The Unicode of character A is assigned to i
Delivered
11/09/2024

Character Datatype & Operations 21


 One more interesting thing is that two characters can be compared using the relational
operators just like comparing two numbers. This is done by comparing the Unicodes of
the two characters. For example,
'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98).
'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65).
'1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8' (56).
 Also, Java provides the following methods in the Character class for testing characters

Need to use a sequence of characters?


It's time to take a challenge.

22
11/09/2024

23
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches

The String Type 24


 The char type represents only one character. To represent a string of characters, use the
data type called String. For example, the following code declares message to be a string
with the value "Welcome to Java".
String message = "Welcome to Java";

Stringis 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 for a variable. The
variable declared by a reference type is known as a
reference variable that references an object.
11/09/2024

The String Type 25


 Here lists some String methods for obtaining string length, for accessing characters in the
string, for concatenating strings, for converting a string to upper or lowercases, and for
trimming a string.

Proposition
 Strings are objects in Java. The methods above can only be invoked from a specific string instance. For this reason, these methods
are called instance methods. A noninstance 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 arguments. Recall that the
syntax to invoke a static method is ClassName.methodName(arguments). For example, the pow method in the Math class can be
invoked using Math.pow(2, 2.5).

The String Type - Operations 26


 The figure shows only a little aspect of the operations, let’s dive deeper! Suppose we
have a string like this:
String message = "Welcome to Java";
11/09/2024

The String Type - Operations 27


 You can use the length() method to return the number of characters in a string. For
example,
System.out.println("The length of " + message + " is " + message.length()); // 15

The String Type - Operations 28


 You can use the concat method to concatenate two strings. The statement shown below,
for example, concatenates strings s1 and s2 into s3:
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
String s3 = s1 + s2;
 Here are some examples:
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
11/09/2024

The String Type - Operations 29


 You can also convert strings. The toLowerCase() method returns a new string with all
lowercase letters and the toUpperCase() method returns a new string with all uppercase
letters. For example,
"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
 The trim() method returns a new string by eliminating whitespace characters from both
ends of the string. The characters ' ', \t, \f, \r, or \n are known as whitespace characters.
For example,
"\t Good Night \n".trim() returns a new string Good Night.

The String Type - Operations 30


 And, to read a string from the console, invoke the next(), or nextLine() method on a Scanner
object. For example,

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


System.out.print("Enter three words separated System.out.print(“Enter your fullname: ");
by spaces: "); String fullname = input.nextLine();
String s1 = input.next(); System.out.println(“Your fullname is " + fullname);
String s2 = input.next(); Proposition
String s3 = input.next();  The nextLine() method reads a string that ends with the
System.out.println("s1 is " + s1); Enter key pressed.
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Proposition
 The next() method reads a string that ends with a
whitespace character.
11/09/2024

The String Type - Operations 31


 Also, in some cases, for some reasons, you might have to compare two strings, then
these following methods can help you.

The String Type - Operations 32


 How do you compare the contents of two strings? You might attempt to use the ==
operator, as follows
if (string1 == string2)
System.out.println("string1 and string2 are the same object");

 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.
if (string1.equals(string2))
System.out.println("string1 and string2 have the same contents");
11/09/2024

The String Type - Operations 33


 The compareTo method can also be used to compare two strings. For example, consider
the following code:
s1.compareTo(s2)
 The method returns the value 0 if s1 is equal to s2, a value less than 0 if s1 is
lexicographically (i.e., in terms of Unicode ordering) less than s2, and a value greater
than 0 if s1 is lexicographically greater than s2.
The actual value returned from the compareTo method depends on the offset
of the first two distinct characters in s1 and s2 from left to right. For
example, suppose s1 is abc and s2 is abg, and s1.compareTo(s2) returns -4.
The first two characters (a vs. a) from s1 and s2 are compared. Because they
are equal, the second two characters (b vs. b) are compared. Because they
are also equal, the third two characters (c vs. g) are compared. Since the
character c is 4 less than g, the comparison returns -4.

The String Type - Operations 34


 You can obtain a single character from a string using the charAt method. You can also
obtain a substring from a string using the substring method in the String class:
11/09/2024

The String Type - Operations 35


 Then, if you want to find a certain character or a substring of a string, the String class
provides several versions of indexOf and lastIndexOf methods to fulfill this.

The String Type - Operations 36


In some case, you might need the conversion between String and numeric
types. In this case, please note that you can easily convert a numeric string to a
number in Java:
 To convert a string to an integer, use Integer.parseInt(), like this:
int intValue = Integer.parseInt("123");
 For converting a string to a double, use Double.parseDouble(), like this:
double doubleValue = Double.parseDouble("123.45");
Be careful, if the string isn’t numeric, it will cause a runtime error. To go the
other way and convert a number into a string, simply use the concatenation
operator:
String s = number + "";
11/09/2024

37
Nobita
Now that we’ve equipped ourselves with the ability of gathering user’s input.
We can ask someone for their name, their age, and so on… But with any good
conversation, how we response is just as important as the way we say it.
Think about it, if our output is disorganized or hard to read, the user might
miss our message. It’s like trying to read a letter that’s full of smudges and
crossed-out words. Then how to fix this?

Let’s take the next step in our journey and learn how to format
our console output…
Nobita
Delivered
Really? Let’s go…

Text I/O – Formatting Console Output 38


 In Java, we have powerful tools at our disposal to ensure our output looks just right.
Whether it's aligning text, formatting numbers, or creating a clean, professional display,
we can use printf() and String.format() to take our output from basic to polished.
 The syntax to invoke this method is
System.out.printf(format, item1, item2, ..., itemk)
where format is a string that may consist of substrings and format specifiers.
 A format specifier specifies how an item should be displayed. An item may be a numeric
value, a character, a Boolean value, or a string. A simple format specifier consists of a
percent sign (%) followed by a conversion code. Here is an example:
11/09/2024

Text I/O – Formatting Console Output 39


 Table below lists some frequently used simple format specifiers.

Text I/O – Formatting Console Output 40


 Items must match the format specifiers in order, in number, and in exact type. For
example, the format specifier for count is %d and for amount is %f. By default, a floating-
point value is displayed with six digits after the decimal point. You can specify the width
and precision in a format specifier, as shown in the examples in Table below.
11/09/2024

Text I/O – Formatting Console Output 41


 If an item requires more spaces than the specified width, the width is automatically
increased. For example, the following code:

The specified width for int item 1234 is 3, which is smaller than its actual size 4. The width is
automatically increased to 4. The specified width for string item Java is 2, which is smaller than
its actual size 4. The width is automatically increased to 4. The specified width for double item
51.6653 is 4, but it needs width 5 to display 51.67, so the width is automatically increased to 5.

Text I/O – Formatting Console Output 42


 By default, the output is right justified. You can put the minus sign (-) in the format
specifier to specify that the item is left justified in the output within the specified field.
For example, the following statements:
11/09/2024

Feeling a bit tired?


Let's take a 5-minute
break. Rest up, and
we'll be back shortly!

44
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches
11/09/2024

Selections 45
 Before diving deeper, let’s recall an example from the previous lecture:

Have you ever see or imagine of a


circle with negative radius? As you
can see, if I enter a negative value
for radius, the program still displays
an result. In fact, if the radius is
negative, the program should not
compute the area. So, how can you
deal with this situation?

Selections 46
 Like all high-level programming languages, Java provides selection statements which let
you choose actions with alternative courses. These decision-making structures are often
best represented visually through a flowchart. In a flowchart, the diamond-shaped
symbol is used to indicate a decision point where the program evaluates a condition and
takes a different path depending on whether the condition is true or false.
11/09/2024

Selections – Conditions 47
 In terms of conditions, Java Selection uses conditions that are Boolean expressions. A
Boolean expression is an expression that evaluates to a Boolean value: true or false.
These expressions form the basis of decision-making in Java, allowing the program to
choose between different actions depending on the result of the condition.

Now, to fully understand how


these conditions work, we need
to dive deeper into the concept of
the Boolean data type in Java.

Selections – Conditions 48
 In this section, we are going to discuss about:
 Conditions - Boolean Datatype
 Logical Operators
 Operator Precedence and Associativity
11/09/2024

Selections – Conditions 49
 Let's take a closer look at how we form these Boolean expressions. One common way is
by comparing values using relational operators. For example, how do we check if a
number is greater than 0, equal to 0, or less than 0? Java provides six relational operators,
also known as comparison operators, which allow us to compare two values and return a
Boolean value - either true or false, as shown below:

Selections – Conditions 50
 A variable that holds a Boolean value is known as a Boolean variable. The boolean data
type is used to declare Boolean variables. A boolean variable can hold one of the two
values: true or false

You know, very often, you will need to combine


multiple conditions or refine your decision-
making process in more complex ways. In this
situation, how can we? – Yeah, Logical operators!
11/09/2024

Selections – Conditions 51
 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. Java provides 4 logical
operators:

Next, let's examine the


truth tables for each of
these logical operators.

Selections – Conditions 52
 Truth Table for Operator !
11/09/2024

Selections – Conditions 53
 Truth Table for Operator &&

false

Selections – Conditions 54
 Truth Table for Operator ||
11/09/2024

55
Suppose that you have this expression:
3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 - 3 > 5)
What is its value? What is the execution order
of the operators?

To answer these questions, we need to understand operator precedence.


The precedence rule determines how operators are prioritized in an
expression. Operators with higher precedence are evaluated before
those with lower precedence. For example, logical operators have
lower precedence than relational operators, and relational operators
have lower precedence than arithmetic operators. Let's take a look at
the precedence table to see how these operators are ordered.

Selections – Operator Precedence 56

If operators with the same precedence


are next to each other, their
associativity determines the order of
evaluation. All binary operators
except assignment operators are left
associative.
11/09/2024

That’s all about Conditions,


do you have any question?
If not? Let’s dive into how these conditions make sense…
57

58
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches
11/09/2024

Selections – If 59
 If you want to make decisions based on certain conditions, Java provides the selection
statements, 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
 Conditional expressions.

Selections – If 60
 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:
if (boolean-expression) {
statement(s);
}

Proposition
 The flowchart illustrates how Java executes the syntax of an if statement. The diamond box
denotes a Boolean condition and a rectangle box represents statements. As you can see, if the
boolean-expression evaluates to true, the statements in the block are executed.
11/09/2024

Selections – Two-way if-else 61


 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 the condition is true or false.
Here is the syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
} else {
statement(s)-for-the-false-case;
}

Proposition
 An if-else statement executes statements for the true case if the Boolean expression evaluates
to true; otherwise, statements for the false case are executed.

Selections – Nested if 62
 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. For example, the following is a nested if statement:
if (i > k) {
if (j > k)
System.out.println("i and j are greater than k"); }
else
System.out.println("i is less than or equal to k");
11/09/2024

Selections – Multiple-way if 63
 The nested if statement can be used to implement multiple alternatives. Here is an
example:

Selections – Multiple-way if 64
 However, nested if-else statement can be organized as if-else if statement. This structure
simplifies the logic by reducing complexity and enhancing code readability:

Proposition
 On the right side is the preferred coding style for multiple alternative if statements. This style,
called multi-way if-else statements, avoids deep indentation and makes the program easy to
read.
11/09/2024

 The code is too long?


 Tired of repeated if-
else statements?
Let’s try another way…

65

66
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches
11/09/2024

Selections – switch 67
 The if statement allows decisions to be made based on a true or false condition. In some cases,
multiple conditions need to be handled, often leading to the use of nested if statements.
However, excessive nesting can make the code harder to read and maintain. To streamline this
process, Java offers the switch statement, which is ideal for handling multiple conditions more
clearly and efficiently.
 For example, when calculating taxes based on different income brackets, a switch statement can
replace a complex nested if structure.

Selections – switch 68
 The flowchart of the preceding switch statement:

Here you can see the


switch statement checks
all cases and executes
the statements in the
matched case.
11/09/2024

Selections – switch 69
 Here is the full syntax for the switch statement:

switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

Selections – switch 70
 The switch statement observes the following rules:
 The switch-expression must yield a value of char, byte, short, int, or String type and
must always be enclosed in parentheses.
 The value1, . . ., and valueN must have the same data type as the value of the
switchexpression. Note that value1, . . ., and valueN are constant expressions,
meaning that they cannot contain variables, such as 1 + x.
 When the value in a case statement matches the value of the switch-expression, the
statements starting from this case are executed until either a break statement or the
end of the switch statement is reached.
 The default case, which is optional, can be used to perform actions when none of the
specified cases matches the switch-expression.
 The keyword break is optional. The break statement immediately ends the switch
statement.
11/09/2024

Selections – switch 71
 Do not forget to use a break statement when one is needed. Once a case is matched,
the statements starting from the matched case are executed until a break statement or
the end of the switch statement is reached. This is referred to as fall-through behavior.
For example, the following code displays Weekdays for day of 1 to 5 and Weekends for
day 0 and 6.

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

72
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches
11/09/2024

Selections – Ternary 73
 In some cases, ou might want to assign a value to a variable that is restricted by certain
conditions. For example, the following statement assigns 1 to y if x is greater than 0, and
-1 to y if x is less than or equal to 0.
if (x > 0)
y = 1;
else
y = -1;
 Alternatively, as in the following example, you can use a conditional expression to
achieve the same result.
y = (x > 0) ? 1 : -1;

Selections – Ternary 74
 Conditional expressions are in a completely different style, with no explicit if in the
statement. The syntax is:
boolean-expression ? expression1 : expression2;
 The result of this conditional expression is expression1 if boolean-expression is true;
otherwise the result is expression2.
Example
 The following statement displays the message “num is even” if num is even, and otherwise displays
“num is odd.”
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");

Proposition
 The symbols ? and : appear together in a conditional expression. They form a conditional
operator and also called a ternary operator because it uses three operands. It is the only
ternary operator in Java.
11/09/2024

M-A Question:
Now that we understand
how selection statements
work, then are there any
considerations we should
keep in mind?

75

76
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches
11/09/2024

Common Errors and Pitfalls 77


 Common Error 1: Forgetting Necessary Braces
The braces can be omitted if the block contains a single statement. However, forgetting the
braces when they are needed for grouping multiple statements is a common programming
error. If you modify the code by adding new statements in an if statement without braces,
you will have to insert the braces. For example, the following code in (a) is wrong. It
should be written with braces to group multiple statements, as shown in (b).

Common Errors and Pitfalls 78


 Common Error 2: Wrong Semicolon at the if Line
Adding a semicolon at the end of an if line, as shown in (a) below, is a common mistake.
This mistake is hard to find, because it is neither a compile error nor a runtime error; it is a
logic error. The code in (a) is equivalent to that in (b) with an empty block.
This error often occurs when you use the next-line block style. Using the end-of-line block
style can help prevent this error.
11/09/2024

Common Errors and Pitfalls 79


 Common Error 3: Redundant Testing of Boolean Values
To test whether a boolean variable is true or false in a test condition, it is redundant to use the
equality testing operator like the code in (a)

Instead, it is better to test the boolean variable directly, as shown in (b). Another good
reason for doing this is to avoid errors that are difficult to detect. Using the = operator
instead of the == operator to compare the equality of two items in a test condition is a
common error. It could lead to the following erroneous statement:
if (even = true)
System.out.println("It is even.");
This statement does not have compile errors. It assigns true to even, so that even is always
true.

Common Errors and Pitfalls 80


 Common Error 4: Dangling else Ambiguity
The code in (a) below has two if clauses and one else clause. Which if clause is matched by the else
clause? The indentation indicates that the else clause matches the first if clause.
However, the else clause actually matches the second if clause. This situation is known as the
dangling else ambiguity. The else clause always matches the most recent unmatched if clause in the
same block. So, the statement in (a) is equivalent to the code in (b).
11/09/2024

Common Errors and Pitfalls 81


 Common Error 5: Equality Test of Two Floating-Point Values
As discussed in last lecture, floating-point numbers have a limited precision and calculations; involving
floating-point numbers can introduce round-off errors. So, equality test of two floating-point values is not
reliable. For example, you expect the following code to display true, but surprisingly it displays false.
double x = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1;
System.out.println(x == 0.5);
Here, x is not exactly 0.5, but is 0.5000000000000001. You cannot reliably test equality of two floating-point
values. However, you can compare whether they are close enough by testing whether the difference of the
two numbers is less than some threshold. That is, two numbers x and y are very close if |x-y| < 𝜀 (a Greek
letter pronounced epsilon) for a very small value, is commonly used to denote a very small value. Normally,
you set 𝜀 to 10 for comparing two values of the double type and to 10 for comparing two values of the
float type. For example, the following code
final double EPSILON = 1E-14;
double x = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1;
if (Math.abs(x - 0.5) < EPSILON)
System.out.println(x + " is approximately 0.5");
will display that 0.5000000000000001 is approximately 0.5.
The Math.abs(a) method can be used to return the absolute value of a.

Feeling stuck or unsure


what can you do when
facing other errors? –
Don’t worry, we will
provide some guideline
later.

82
11/09/2024

83
 Mathematical Functions
 Characters
 String
 Selections – Conditions
 Selections - IF
 Selections - Switch
 Selections – Ternary
 Common Errors and Pitfalls
 Final Touches

Final Touches 84
 By the end of this section, we are going to discuss on:
 How to use Math.random() to obtain a random double value
 The way to simplify Boolean variable assignment
 Avoiding duplicated code in different cases
11/09/2024

Final Touches – Math.random() 85


 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.
 Some programers generate random numbers using System.currentTimeMillis(). A better
approach is to use the random() method in the Math class. Invoking this method returns
a random double value d such that 0.0 <= d < 1.0. Thus, (int)(Math.random() * 10)
returns a random single-digit integer (i.e., a number between 0 and 9).

Final Touches – Simplify Assignment 86


 In addition, often, new programmers write the code that assigns a test condition to a
boolean variable like the code in (a):

This is not an error, but it


should be better written
as shown in (b).
11/09/2024

Final Touches – Avoid Duplicated Code 87


 Or, for some reasons, new programmers write the duplicate code in different cases that
should be combined in one place. For example, the highlighted code in the following
statement is duplicated.
if (inState) {
Here you can see the new code
tuition = 5000;
removes the duplication and
System.out.println("The tuition is " + tuition);
makes the code easy to
} else {
maintain, because you only need
tuition = 15000;
to change in one place if the
System.out.println("The tuition is " + tuition);
print statement is modified.
}
This is not an error, but it should be better written as follows:
if (inState) {
tuition = 5000;
} else {
tuition = 15000;
}
System.out.println("The tuition is " + tuition);

88

This brings me to the end of


this lecture. Do you have
any question?
11/09/2024

89

Thanks!
Any questions?
For an in-depth understanding of Java, I highly recommend
referring to the textbooks. This slide provides a brief overview
and may not cover all the details you're eager to explore!

You might also like