University of Aden
Faculty of Computer &
Information Technology
Computer Programming I
Java Programming Language
DR .\ Wadah Ahmed Munassar
Course Plan
# Lectures
1- An introduction to Java Programming
Basic Elements of Java -2
3- Introduction to Objects and Input/Output
Control Structures I: Selection -4
5- Control Structures II: Looping
User-Defined Methods -6
User-Defined Classes -7
Arrays -8
9- Inheritance and Polymorphism 2
Lecture 2: Control Structures I: Selection
Control Structures I: Selection
Java Programming Language Slide 3
Outline
✔ Program Control Structures
✔ Relational Operators
✔ Boolean data type
1st Part
✔ Logical Operators
✔ Precedence of Operators
✔ Short-Circuit Evaluation
✔ One-way selection ( if statement)
✔ Two-way selection (if… else statements) 2nd Part
✔ Compound (block of) statements
✔ Multiple selections (nested if & if… else)
✔ Conditional operator
✔ switch structures
Java Programming Language Slide 4
Control Structures
Control structures take decisions about program flow
based on given parameters.
A control structures are of these three types:
✔ In sequence
Transfer
Sequentialof Statement 1
✔ By making a selection or a choice, which is also called a
control
Execution
branch.
✔ By repetition, executing a statement
Statement 2 over and over using
a structure called a loop
Java Programming Language Slide 5
Flow of Execution
Java Programming Language Slide 6
Relational Operators
Relational Operators used to make comparisons in
a java program
Description Operators
Equal to ==
Not equal to !=
Less than <
Less than or equal to <=
Greater than >
Greater than or equal to >=
Java Programming Language Slide 7
Boolean data type
The boolean data type declares a variable with the
value either true or false.
✔ boolean x = ( 10 == 5 ); // false
✔ boolean x = ( 10 != 5 ); // true
✔ boolean x = ( 10 < 5 ) ; // false
✔ boolean x = ( 10 <= 10 ) ; // true
✔ boolean x = ( 10 > 10 ) ; // false
✔ boolean x = ( 10 >= 5 ) ; // true
Java Programming Language Slide 8
Logical Operators
✔ The logical operators can be used to create a
compound Boolean expression.
Description Operators
NOT !
AND &&
OR ||
Exclusive OR ^
Java Programming Language Slide 9
Logical Operators (continued)
✔ The NOT operator (!) reverses the truth value of its
operand.
✔ If an expression evaluates to true, its negation evaluates
to false, and vice versa.
!(Expression) Expression
false true
true false
Java Programming Language Slide 10
Logical Operators (continued)
✔ The following truth table shows that the AND (&&)
operator evaluates to true only when both of its individual
operands are true.
Expression(1)&& Expression(2) Expression(2) Expression(1)
true true true
false false true
false true false
false false false
Java Programming Language Slide 11
Logical Operators (continued)
✔ The following truth table shows that the OR (||) operator
evaluates to true except when both operands are false.
Expression(1)|| Expression(2) Expression(2) Expression(1)
true true true
true false true
true true false
false false false
Java Programming Language Slide 12
Logical Operators (continued)
✔ The following truth table shows that the exclusive or (^)
operator evaluates to true if and only if the two operands
have different values.
Expression(1)^ Expression(2) Expression(2) Expression(1)
false false false
true true false
true false true
false true true
Java Programming Language Slide 13
Logical Operators (continued)
✔ Write java program that checks whether a number is
divisible
✔ by 2 AND 3 ��
✔
✔ by 2 OR 3 ✔
✔
✔ by 2 OR 3 but not both. ✔
��
12 9
Java Programming Language Slide 14
Java Application: Logical Operators
import java.util.*;
public class LogicalOperators {
public static void main(String[] args) {
// Create Scanner
Scanner input = new Scanner(System.in);
// Receive an input
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 2 == 0 && number % 3 == 0)
System.out.println(number + " is divisible by 2 and 3.");
if (number % 2 == 0 || number % 3 == 0)
System.out.println(number + " is divisible by 2 or 3.");
if (number % 2 == 0 ^ number % 3 == 0)
System.out.println(number + " divisible by 2 or 3, but not both.");
}}
Java Programming Language Slide 15
Java Application: Logical Operators_1
import java.util.Scanner;
public class LogicalOperators_1 {
public static void main(String[] args) {
// Create Scanner
Scanner input = new Scanner(System.in);
System.out.print("Please Enter Integer number: ");
int x = input.nextInt();
boolean number = (x % 2 == 0 && x % 3 == 0);
System.out.println("The value of "+x+ " number when divided "
+ "by 2 AND 3 is "+ number);
number = (x % 2 == 0 || x % 3 == 0);
System.out.println("The value of "+x+ " number when divided "
+ "by 2 OR 3 is "+ number);
number = (x % 2 == 0 ^ x % 3 == 0);
System.out.println("The value of "+x+ " number when divided "
+ "by 2 AND 3 but not both is "+ number); }}
Java Programming Language Slide 16
Precedence of Operators
Precedence Operators
first (highest) !, +, - (unary operators)
Second *, /, %
Third +, -
Fourth =< ,< ,=> ,>
Fifth ==, !=
Sixth &&
Seventh ||
last (lowest) = (assignment operator)
Java Programming Language Slide 17
Precedence of Operators (continued)
(17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3 + 3 == 6)
(17 < 12 + 5) || (16 == 16) && !(6 == 6)
(17 < 17) || true && !(true)
false || true && false
false || false
false
Java Programming Language Slide 18
Short-Circuit Evaluation
Short-Circuit Evaluation: a process in which the computer evaluates
a logical expression from left to right and stops as soon as the
value of the expression is known
Example:
int age = 25; true
char grade = ‘B’;
(age >= 21) || (x == 5); // true
(grade == ‘A’) && (x >= 7); // false
false
Java Programming Language Slide 19
Java Application: Leap Year
• Write a program that prompts the user to enter a
year and then check whether the input year is a
leap year or not.
• Leap year is a year where an extra day is added to
the end of the shortest month (February).
• Leap year has 366 days instead of the usual 365
days and occur almost every four years.
Java Programming Language Slide 20
Java Application: Leap Year (continued)
• To determine whether a year is leap year or not, we
have to check the following:
✔ If the year is evenly divisible by 4 but not by 100 ( it is
leap year).
✔ If the year can also be divided evenly by 100, then it is
not a leap year, unless the year is also evenly divisible by
400, then it is a leap year.
Java Programming Language Slide 21
Java Application: Leap Year (continued)
• Step 1: check if the year is evenly divisible by 4.
• Step 2: check if the year is evenly divisible by 4 but
not by 100.
• Step 3: check if the year is evenly divisible by 4, and
it can also be divided evenly by 100, if so,
check if the year is also evenly divisible by 400
• Otherwise, the year is not a leap year.
Java Programming Language Slide 22
Java Application: Leap Year (continued)
1 Check if the year is evenly divisible by 4
true
false
// A leap year is divisible by 4
boolean LeapYear = (year % 4 == 0)
ItItisisnot a year
leap leap year
Java Programming Language Slide 23
Java Application: Leap Year (continued)
2
check if the year is evenly divisible by 4 but not by
100
true
true true
false
// A leap year is divisible by 4 but not by 100
boolean LeapYear = (year % 4 == 0 && year % 100 != 0)
It is
It is notleap yearyear
a leap
Java Programming Language Slide 24
Java Application: Leap Year (continued)
3 check if the year is evenly divisible by 4, and it can also be
divided evenly by 100, if so, it should check if the year is
also evenly divisible by 400
true false
// A leap year is divisible by 4 but not by 100 false
true
// or divisible by 400
boolean LeapYear = (year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0);
It isaleap
It is not leapyear
year
Java Programming Language Slide 25
Java Application: Leap Year (continued)
import java.util.*;
public class LeapYear {
Output (1):
public static void Enter
main(String[] args) {
a year: 2020
Scanner input = 2020
new Scanner(System.in);
is a leap year? true
System.out.print("Enter a year: ");
int year = input.nextInt();
Output (2):
// Check if the Enter
year isa year:
a leap2021
year
boolean LeapYear2021 is a %leap
= (year 4 ==year?
0 && false
year % 100 != 0)
|| (year % 400 == 0);
// Display the result
System.out.println(year + " is a leap year? " + LeapYear); }}
Java Programming Language Slide 26
Selection
• One-way selection
• Two-way selection
• Compound (block of) statements
• Multiple selections (nested if)
• Conditional operator
• switch structures
Java Programming Language Slide 27
One-way selection
✔ Java if statement: The Java if statement tests the condition. It
executes the if block if boolean expression evaluate to true.
Syntax:
if (boolean-expression)
statement boolean-expre False
ssion
Example: True
double percent = input.nextDouble();
statements
if (percent >= 90)
System.out.println("You got an
A");
Java Programming Language Slide 28
One-way selection (continued)
import java.util.*;
public class OneWaySelection {
public static void main(String[] args) {
Output:
// create Scanner
Please Enter the number: 9
Scanner input = new Scanner (System.in);
9 is odd number
System.out.print("Please Enter the number: ");
int x = input.nextInt();
Output:
Please Enter the number: 10
if (x % 2 == 0)10 is even number
System.out.println(x+" is even number");
if (x % 2 == 1)
System.out.print(x+ " is odd number");
}
}
Java Programming Language Slide 29
Two-way selection
✔ Java if else statement: The Java if-else statement also tests the
condition. It executes the if block if boolean expression is true
otherwise else block is executed.
Syntax:
if (boolean-expression) True boolean-expre False
<statement-s> ssion
else
<statement-s> statements statements
Java Programming Language Slide 30
Two-way selection (continued)
Example:
double gpa = input.nextDouble();
if (gpa >= 4.5)
System.out.println("Your gpa is accepted ");
else
System.out.println(“Sorry, your gpa is not accepted");
Java Programming Language Slide 31
Two-way selection (continued)
import java.util.*;
public class TwoWaySelection {
public static void main(String[] args) {
Output:
// create Scanner
Please Enter the number: 10
Scanner input =Output:
new Scanner (System.in);
10 is even number
Please Enter
System.out.print("Please thethe
Enter number: 10 ");
number:
10 is even number
int x = input.nextInt();
10 is odd number
if (x % 2 == 0)
System.out.println(x+" is even number");
else
System.out.print(x+ " is odd number");
}
}
Java Programming Language Slide 32
if & if… else statements
✔ What is the output of the code in (a) and (b) if number
is 30? What if number is 35?
(a) (b)
if (number % 2 == 0) if (number % 2 == 0)
System.out.println(number+" is even"); System.out.println(number+" is even");
else
System.out.print(number+ " is odd"); System.out.print(number+ " is odd");
35
30
30 is even
30
35 is even
odd 35 is odd
30 is odd
Java Programming Language Slide 33
Common Errors
✔ Note: Adding a semicolon at the end of an if clause is a
common mistake.
if (number % 2 == 0) ;
System.out.println(number+" is even");
System.out.print(number+ " is odd");
ERROR
This mistake is hard to find, because it is not a
compilation error or a runtime error, it is a logic error
Java Programming Language Slide 34
Stand-alone else statement error
✔ In java, else statement cannot be separated from the if
statement.
if (number % 2 == 0) ;
System.out.println(number+" is even");
else
System.out.print(number+ " is odd");
Syntax error
ERROR
else statement cannot be stand-alone in Java
Java Programming Language Slide 35
Compound (Block of) Statements
if (age > 18)
{
System.out.println("Eligible to vote.");
System.out.println("No longer a minor.");
}
else Syntax errorThis statement will be executed
whatever a status of a condition
{
System.out.println("Not eligible to vote.");
System.out.println("Still a minor.");
}
A compound statements consists of a sequence of statements enclosed in
braces.
Java Programming Language Slide 36
Multiple Selections: Nested If else
✔ An if statement can be inside another if statement to form a
nested if statement.
if (<condition>) { if (score >= 90) {
<statement(s)> ; System.out.println(“A");
} else if } else if
(<condition>) { (score >= 80) {
<statement(s)> ; System.out.println(“B");
} else { } else {
<statement(s)> ; System.out.println(“C");
} }
Java Programming Language Slide 37
Multiple Selections: Nested If else (continued)
Multiple Selections False
Score >= 90
if (score >= 90) True False
Score >= 80
System.out.print("A");
grade is A
else if (score >= 80) False
True Score >= 70
System.out.print("B");
grade is B
else if (score >= 70) False
System.out.print("C"); True Score >= 60
else if (score >= 60) grade is C
System.out.print("D"); True
grade is D
else
grade is F
System.out.print("F");
Java Programming Language Slide 38
Pairing an else with an if
In a nested if statement, Java associates an else with the most
recent incomplete if—that is, the most recent if that has not
been paired with an else.
if (temperature >= 50)
if (temperature >= 80)
System.out.println("Good day for swimming.");
else
System.out.println("Good day for golfing.");
Java Programming Language Slide 39
Pairing an else with an if (continued)
if (temperature >= 50)
if (temperature >= 80)
System.out.println("Good day for swimming.");
else
System.out.println("Good day for golfing.");
else
System.out.println("Good day to play tennis.");
Java Programming Language Slide 40
Comparing if… else statements with a series
of if statements
if (month == 1) if (month == 1)
System.out.print("January"); System.out.print("January");
else if (month == 2) if (month == 2)
System.out.print("February"); System.out.print("February");
else if (month == 3) if (month == 3)
System.out.print("March"); System.out.print("March");
else if (month == 4) if (month == 4)
System.out.print("April"); System.out.print("April");
else if (month == 5) if (month == 5)
System.out.print(“May"); System.out.print(“May");
else if (month == 6) if (month == 6)
System.out.print("June"); System.out.print("June");
Java Programming Language Slide 41
Conditional (? :) Operator
✔ Conditional operator: It is a ternary operator, which means that
it takes three arguments.
✔ Syntax
expression1 ? expression2 : expression3
if (a >= b)
max = a; max = (a >= b) ? a : b;
else
max = b;
Java Programming Language Slide 42
Conditional (? :) Operator (continued)
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
23 is
is even
odd
is equivalent to num
num =
=32
System.out.println(
(num % 2 == 0)? num + “is even” :num + “is odd”);
Java Programming Language Slide 43
switch Structures
✔ A switch statement executes statements based on the value of a
variable or an expression.
month =
month =24
? April
February
switch (month)
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
The entire
switch
case 3: System.out.println("March");
break; statement
is skipped.
case 4: System.out.println(“April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println(“June");
break;
Java Programming Language Slide 44
switch Structures (continued)
switch (month)
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
default: System.out.println("Error: The month is
+ "invalid");
Java Programming Language Slide 45
switch Structures (continued)
✔ In Java, switch, case, break, and default are reserved words.
✔ The value of the identifier or the expression can be only of type int, byte, short, or
char.
✔ A particular case value must appear only once.
✔ One or more statements may follow a case label, so you do not need to use braces
to turn multiple statements into a single compound statement.
✔ If the value of the expression does not match any of the case values, the
statements following the default label execute.
✔ A break statement causes an immediate exit from the switch structure.
Java Programming Language Slide 46
Programming Exercises
1. Programming exercise number (1) page 241.
2. Programming exercise number (8) page 243.
3. Programming exercise number (9) page 244.
Java Programming Language Slide 47