Day 03 - Characters, String and Selections
Day 03 - Characters, String and Selections
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
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
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
Proposition
In general,
a + Math.random() * b Returns a random number between a and
a + b, excluding a + b.
11/09/2024
Sample run
Enter three points: 1 1 6.5 1 6.5 2.5
The three angles are 15.26 90.0 74.74
13
Mathematical Functions
Characters
String
Selections – Conditions
Selections - IF
Selections - Switch
Selections – Ternary
Common Errors and Pitfalls
Final Touches
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"");
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?
22
11/09/2024
23
Mathematical Functions
Characters
String
Selections – Conditions
Selections - IF
Selections - Switch
Selections – Ternary
Common Errors and Pitfalls
Final Touches
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).
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
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…
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.
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:
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.
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
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:
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?
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
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
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:
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
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.
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
88
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!