Introduction to Java_chapter3
Introduction to Java_chapter3
Statements
Lecture notes for computer programming 1
Faculty of Engineering and Information Technology
Prepared by: Iyad Albayouk
١
The boolean Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j.
Java provides six comparison operators
(also known as relational operators) that can
be used to compare two values. The result of
the comparison is a Boolean value: true or
false.
٢
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
٣
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
٤
Truth Table for Operator !
p !p Example
true false !(1 > 2) is true, because (1 > 2) is false.
false true !(1 > 0) is false, because (1 > 0) is true.
٥
Truth Table for Operator &&
p1 p2 p1 && p2 Example
false false false (3 > 2) && (5 >= 5) is true, because (3 > 2)
false true false and (5 >= 5) are both true.
true false false (3 > 2) && (5 > 5) is false, because (5 > 5) is
true true true false.
٦
Truth Table for Operator ||
p1 p2 p1 || p2 Example
false false false (2 > 3) || (5 > 5) is false, because (2 > 3) and
false true true (5 > 5) are both false.
true false true (3 > 2) || (5 > 5) is true, because (3 > 2) is
true true true true.
٧
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example
false false false (2 > 3) ^ (5 > 1) is true, because (2 > 3) is
false true true false and (5 > 1) is true.
true false true (3 > 2) ^ (5 > 1) is false, because both (3 > 2)
true true false and (5 > 1) are true.
٨
Examples
System.out.println("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));
٩
Example: Determining Leap
Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
١٠
Example: Determining Leap Year?, cont.
import java.util.Scanner;
public class LeapYear {
public static void main(String args[]) {
// Create a Scanner
Scanner scanner = new Scanner(System.in);
// Get input
System.out.print("Enter a year: ");
int year = scanner.nextInt();
// Check if the year is a leap year
boolean isLeapYear =
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// Display the result in a message dialog box
System.out.println(year + " is a leap year? " + isLeapYear);
}
} ١١
Example: A Simple Math Learning
Tool
This example creates a program to let a first grader practice additions.
The program randomly generates two single-digit integers number1
and number2 and displays a question such as “What is 7 + 9?” to the
student, as shown below. After the student types the answer in the
input dialog box, the program displays a message dialog box to
indicate whether the answer is true or false.
١٢
Example: A Simple Math
Learning Tool, cont
import javax.swing.*;
public class LearnAddition {
public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() * 7 % 10);
String answerString = JOptionPane.showInputDialog
("What is " + number1 + " + " + number2 + "?");
int answer = Integer.parseInt(answerString);
JOptionPane.showMessageDialog(null,
number1 + " + " + number2 + " = " + answer + " is " +
(number1 + number2 == answer));
}
}
١٣
The & and | Operators
&&: conditional AND operator
&: unconditional AND operator
||: conditional OR operator
|: unconditional OR operator
١٦
Simple if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (booleanExpression) { System.out.println("The
statement(s);
} area"
+ " for the circle of radius "
+ radius + " is " + area);}
fa lse fa lse
B o o le a n (ra d iu s > = 0 )
E x p r essio n
tru e tr u e
S ta te m e n t(s) a re a = r a d iu s * r a d iu s * P I;
S y ste m .o u t.p rin tln (" T h e a r ea fo r th e c ir cle o f " +
" r a d iu s " + r a d iu s + " is " + a r ea );
(A ) (B )
١٧
Note
Outer parentheses required Braces canbe omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) { if ((i > 0) && (i < 10))
Equivalent
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10");
}
(a)
(b)
١٨
Caution
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
This error often occurs when you use the next-line block
style.
١٩
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true false
Boolean
Expression
Statement(s) for the true case Statement(s) for the false case
٢٠
if...else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
٢١
Nested if and Multi-Way if-else
Statements
if (score >= 90.0) if (score >= 90.0)
grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivalent grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';
٢٢
Nested if and Multi-Way if-else Statements, cont
٢٣
Note
The else clause matches the most recent if clause in
the same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");
(a) (b)
٢٤
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
if (number % 2 == 0)
Equivalent boolean even
even = true;
else = number % 2 == 0;
even = false;
(a) (b)
٢٦
CAUTION
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
٢٧
Example: An Improved Math Learning
Tool
This example creates a program to teach a first
grade child how to learn subtractions. The program
randomly generates two single-digit integers
number1 and number2 with number1 > number2 and
displays a question such as “What is 9 – 2?” to the
student, as shown in the figure. After the student
types the answer in the input dialog box, the program
displays a message dialog box to indicate whether
the answer is correct, as shown in figure.
٢٨
Example: An Improved Math Learning Tool, cont
import java.util.Scanner;
public class SubtractionTutor {
public static void main(String[] args) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. If number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp; }
// 3. Prompt the student to answer “what is number1 – number2?”
System.out.print("What is " + number1 + " - " + number2 + "? ");
Scanner scanner = new Scanner(System.in);
int answer = scanner.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer)
System.out.println("You are correct!");
else
System.out.println("Your answer is wrong.\n" + number1 + " - "
+ number2 + " should be " + (number1 - number2)); }} ٢٩
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
٣٠
switch Statement Flow Chart
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
٣١
switch Statement Rules
The switch-expression
must yield a value of switch (switch-expression) {
char, byte, short, or int
type and must always case value1: statement(s)1;
be enclosed in break;
parentheses.
case value2: statement(s)2;
The value1, ..., and valueN break;
must have the same data type …
as the value of the switch-
expression. The resulting case valueN: statement(s)N;
statements in the case break;
statement are executed when default: statement(s)-for-
the value in the case statement default;
matches the value of the
}
switch-expression. Note that
value1, ..., and valueN are
constant expressions, meaning
that they cannot contain
variables in the expression,
such as 1 + x. ٣٢
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the
case value1: statement(s)1;
end of each case in order to
terminate the remainder of the break;
switch statement. If the break case value2: statement(s)2;
statement is not present, the
next case statement will be break;
executed. …
case valueN: statement(s)N;
The default case, which is break;
optional, can be used to default: statement(s)-for-
perform actions when none of default;
the specified cases matches
the switch-expression. }
The case statements are executed in
sequential order, but the order of the cases
(including the default case) does not matter.
However, it is good programming style to
follow the logical sequence of the cases and
place the default case at the end. ٣٣
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
٣٤
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
٣٥
Conditional Operator
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(booleanExpression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
٣٦
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
٣٧
Formatting Output
Use the new JDK 1.5 printf statement.
System.out.printf(format, items);
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,
character, boolean value, or a string. Each specifier begins
with a percent sign.
٣٨
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
String s =
String.format("count is %d and amount is %f", 5, 45.56));
٤٠
Operator Precedence
var++, var--
+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
٤١
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the
expression in the inner parentheses is executed
first.) When evaluating an expression without
parentheses, the operators are applied according to
the precedence rule and the associativity rule.
٤٢
Operator Associativity
When two operators with the same
precedence are evaluated, the associativity
of the operators determines the order of
evaluation. All binary operators except
assignment operators are left-associative.
a – b + c – d is equivalent to ((a – b) + c) –
d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c
= 5)) ٤٣
Example
Applying the operator precedence and associativity
rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is
evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false
٤٤
Operand Evaluation Order
The precedence and associativity rules
specify the order of the operators, but do
not specify the order in which the
operands of a binary operator are
evaluated. Operands are evaluated from
left to right in Java.
The left-hand operand of a binary
operator is evaluated before any part of
the right-hand operand is evaluated.
٤٥
Operand Evaluation Order, cont.
If no operands have side effects that change the
value of a variable, the order of operand
evaluation is irrelevant. Interesting cases arise
when operands do have a side effect. For
example, x becomes 1 in the following code,
because a is evaluated to 0 before ++a is
evaluated to 1.
int a = 0;
int x = a + (++a);
But x becomes 2 in the following code, because
++a is evaluated to 1, then a is evaluated to 1.
int a = 0;
int x = ++a + a;
٤٦
Rule of Evaluating an Expression
Rule 1: Evaluate whatever subexpressions you
can possibly evaluate from left to right.
٤٧
Rule of Evaluating an Expression
Applying the rule, the expression 3 + 4 * 4 > 5 * (4 +
3) - 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) 4 * 4 is the first subexpression that can
be evaluated from left.
3 + 16 > 5 * (4 + 3) - 1
(2) 3 + 16 is evaluated now.
19 > 5 * (4 + 3) - 1
(3) 4 + 3 is now the leftmost
19 > 5 * 7 - 1 subexpression that should be
(4) 5 * 7 is evaluated now.
19 > 35 – 1
(5) 35 – 1 is evaluated now.
19 > 34
(6) 19 > 34 is evaluated now.
false
٤٨
Confirmation Dialogs
٤٩
Example of Confirmation Dialogs
import javax.swing.JOptionPane;
public class ConfirmationDialogs {
public static void main(String[] args) {
int option = JOptionPane.showConfirmDialog(null,"Select options[ yes,no,cancel]:");
if(option==0)
JOptionPane.showMessageDialog(null,"yes");
else if(option==1)
JOptionPane.showMessageDialog(null,"no");
else
JOptionPane.showMessageDialog(null,"cancel");
}
}
٥٠