SlideShare una empresa de Scribd logo
1 de 58
https://www.facebook.com/Oxus20
oxus20@gmail.com
Condition
al
Statement
Conditional statements
Author: Parwiz Danyar
Outline
The if Statement and Conditions
Other Conditional Statements
Comparing Data
After :
The while Statement
Iterators
Other Repetition Statements
https://www.facebook.com/Oxus20
Flow of Control
» Unless specified otherwise, the order of
statement execution through a method is
linear: one statement after another in sequence
» Some programming statements allow us to:
˃ decide whether or not to execute a particular statement
˃ execute a statement over and over, repetitively
» These decisions are based on boolean
expressions (or conditions) that evaluate to
true or false
» The order of statement execution is called the
flow of control
https://www.facebook.com/Oxus20
Conditional Statements
» A conditional statement lets us choose which
statement will be executed next
» Therefore they are sometimes called
selection statements
» Conditional statements give us the power to
make basic decisions
» The Java conditional statements are the:
˃ if statement
˃ if-else statement
˃ switch statement
https://www.facebook.com/Oxus20
The if Statement
» The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
https://www.facebook.com/Oxus20
Logic of an if statement
condition
evaluated
statement
true
false
https://www.facebook.com/Oxus20
Boolean Expressions
 A condition often uses one of Java's equality
operators or relational operators, which all return
boolean results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
 Note the difference between the equality operator
(==) and the assignment operator (=)
https://www.facebook.com/Oxus20
The if Statement
» An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
• First the condition is evaluated -- the value of sum
is either greater than the value of MAX, or it is not
• If the condition is true, the assignment statement
is executed -- if it isn’t, it is skipped.
• Either way, the call to println is executed next
https://www.facebook.com/Oxus20
Age.java
…
public static void main (String[] args)
{
final int MINOR = 21;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter your age: ");
int age = scan.nextInt();
System.out.println ("You entered: " + age);
if (age < MINOR)
System.out.println ("Youth is a wonderful thing. "
+ "Enjoy.");
System.out.println ("Age is a state of mind.");
}
}
https://www.facebook.com/Oxus20
Age.java Output
----jGRASP exec: java Age
Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.
----jGRASP: operation complete.
----jGRASP exec: java Age
Enter your age: 100
You entered: 100
Age is a state of mind.
----jGRASP: operation complete.
https://www.facebook.com/Oxus20
Indentation
 The statement controlled by the if statement is
indented to indicate that relationship
 The use of a consistent indentation style makes a
program easier to read and understand
 Although it makes no difference to the compiler, proper
indentation is crucial
"Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live."
-- Martin Golding
https://www.facebook.com/Oxus20
The if Statement
» What do the following statements do?
if (top >= MAXIMUM)
top = 0;
Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUM
if (total != stock + warehouse)
inventoryError = true;
Sets a flag to true if the value of total is not equal to
the sum of stock and warehouse
• The precedence of the arithmetic operators is
higher than the precedence of the equality and
relational operators
https://www.facebook.com/Oxus20
Logical Operators
 Boolean expressions can also use the following
logical operators:
! Logical NOT
&& Logical AND
|| Logical OR
 They all take boolean operands and produce
boolean results
 Logical NOT is a unary operator (it operates on one
operand)
 Logical AND and logical OR are binary operators
(each operates on two operands)
https://www.facebook.com/Oxus20
Logical NOT
» The logical NOT operation is also called
logical negation or logical complement
» If some boolean condition a is true, then !a is
false; if a is false, then !a is true
» Logical expressions can be shown using a
truth table
a !a
true false
false true
https://www.facebook.com/Oxus20
Logical AND and
Logical OR
» The logical AND expression
a && b
is true if both a and b are true, and false
otherwise
» The logical OR expression
a || b
is true if a or b or both are true, and false
otherwisehttps://www.facebook.com/Oxus20
Logical Operators
» Expressions that use logical operators can
form complex conditions
if (total < MAX+5 && !found)
System.out.println ("Processing…");
• All logical operators have lower precedence than
the relational operators
• Logical NOT has higher precedence than logical
AND and logical OR
https://www.facebook.com/Oxus20
Logical Operators
» A truth table shows all possible true-false
combinations of the terms
» Since && and || each have two operands,
there are four possible combinations of
conditions a and b
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
https://www.facebook.com/Oxus20
Boolean Expressions
» Specific expressions can be evaluated using
truth tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
https://www.facebook.com/Oxus20
Short-Circuited
Operators» The processing of logical AND and logical OR
is “short-circuited”
» If the left operand is sufficient to determine the
result, the right operand is not evaluated
• This type of processing must be used carefully
if (count != 0 && total/count > MAX)
System.out.println ("Testing…");
https://www.facebook.com/Oxus20
English conditions in
Java
» true if ch is the first letter in the alphabet
» Test if a variable’s value is within a
specified range
˃ true if x is between min and max inclusive (including min and
max)
˃ true if x is between min and max exclusive (excluding the
endpoints
» Test if variable’s value is outside the
range
˃ true if x is less than min or greater than max
https://www.facebook.com/Oxus20
Testing
» Execute all paths through the program
˃ Recall the flow-chart
» Good idea to test all combinations of an &&
and a ||
» When numeric ranges, test the values
around change in behavior
» Not necessary to test all possible values
» Most cases it is impossible to test
exhaustively
https://www.facebook.com/Oxus20
Outline
The if Statement and Conditions
Other Conditional Statements
Comparing Data
https://www.facebook.com/Oxus20
The if-else Statement
» An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed;
if the condition is false, statement2 is executed
• One or the other will be executed, but not both
https://www.facebook.com/Oxus20
from Wages.java (page
211)final double RATE = 8.25; // regular pay rate
final int STANDARD = 40; // standard hours in a work
// week
Scanner scan = new Scanner (System.in);
double pay = 0.0;
System.out.print ("Enter the number of hours worked: ");
int hours = scan.nextInt();
System.out.println ();
// Pay overtime at "time and a half"
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) *
(RATE * 1.5);
else
pay = hours * RATE;
https://www.facebook.com/Oxus20
Logic of an if-else
statement
condition
evaluated
statement1
true false
statement2
https://www.facebook.com/Oxus20
else if draft
String grdStr;
if (grade >= 90)
grdStr = “A”;
else
if (grade >= 80)
grdStr = “B”;
else
if (grade >= 70)
grdStr = “C”;
else
if (grade >= 60)
grdStr = “D”;
else
grdStr = “F”;
String grdStr;
if (grade >= 90)
grdStr = “A”;
else if (grade >= 80)
grdStr = “B”;
else if (grade >= 70)
grdStr = “C”;
else if (grade >= 60)
grdStr = “D”;
else
grdStr = “F”;
https://www.facebook.com/Oxus20
Indentation Revisited
» Remember that indentation is for the human
reader, and is ignored by the computer
if (total > MAX)
System.out.println ("Error!!");
errorCount++;
Despite what is implied by the indentation, the
increment will occur whether the condition is
true or not
https://www.facebook.com/Oxus20
Block Statements
» Several statements can be grouped
together into a block statement delimited by
braces
» A block statement can be used wherever a
statement is called for in the Java syntax
rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
https://www.facebook.com/Oxus20
Block Statements
» In an if-else statement, the if portion, or
the else portion, or both, could be block
statementsif (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
https://www.facebook.com/Oxus20
Guessing.java
…
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print ("I'm thinking of a number between 1 " +
"and " + MAX + ". Guess what it is: ");
guess = scan.nextInt();
if (guess == answer)
System.out.println ("You got it! Good guessing!");
else
{
System.out.println ("That is not correct, sorry.");
System.out.println ("The number was " + answer);
}
}
}
https://www.facebook.com/Oxus20
Nested if Statements
» The statement executed as a result of an
if statement or else clause could be
another if statement
» These are called nested if statements
» An else clause is matched to the last
unmatched if (no matter what the
indentation implies)
» Braces can be used to specify the if
statement to which an else clause belongs
https://www.facebook.com/Oxus20
MinOfThree.java
…
int num1, num2, num3, min = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter three integers: ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
System.out.println ("Minimum value: " + min);
}
}
https://www.facebook.com/Oxus20
Importance of Curly
Braces
» Print “We have a problem” if examGrade < 60
» Print “We have a real problem” if examGrade
< 60 and quizGrade < 10
» Print “Ok” if examGrade >= 60
int examGrade, quizGrade;
if (examGrade < 60)
System.out.println(“We have a problem”);
if (quizGrade < 10)
System.out.println(“We have a real
problem”);
else
System.out.println(“Ok”);
https://www.facebook.com/Oxus20
Exam Grade Flowchart
int examGrade, quizGrade;
if (examGrade < 60)
System.out.println(“We have a problem”);
if (quizGrade < 10)
System.out.println(“We have a real problem”);
else
System.out.println(“Ok”);
https://www.facebook.com/Oxus20
Writing Cases
» Print “We have a problem” if examGrade < 60
» Print “We have a real problem” if examGrade < 60 and
quizGrade < 10
» Print “Ok” if examGrade >= 60
examGrade < 60 quizGrade < 10 Action
Case 1 “We have a problem”
Case 2 “We have a problem” and
“We have a real problem”
Case 3 “Ok”
https://www.facebook.com/Oxus20
pinna
stalkTwists
divided2
divided3
Shaded-Limestone
nearOak
Id=“Maidenhair”
id=“Sensitive Fern”
id=“Fancy Fern”
id = “Unknown”
id=“Walking Fern”
id = “Oak Fern”
id = “Unknown”
Fern Flow Chart
(false) (true)
https://www.facebook.com/Oxus20
Cases
pinna shadedLimestone nearOak stalkTwists divided2 divided3 output
“Maidenhair”
“Sensitive
Fern”
“Fancy Fern”
“Unknown”
(1)
“Walking
Fern”
“Oak Fern”
“Unknown”
(2)
To produce output, some variables must be true, others false,
and for some, it does not matter. (Place true, false, or ? in the table.)
https://www.facebook.com/Oxus20
The switch Statement
» The switch statement provides another way
to decide which statement to execute next
» The switch statement evaluates an
expression, then attempts to match the
result to one of several possible cases
» Each case contains a value and a list of
statements
» The flow of control transfers to statement
associated with the first case value that
matches
https://www.facebook.com/Oxus20
The switch Statement
» The general syntax of a switch statement is:
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
https://www.facebook.com/Oxus20
The switch Statement
» Often a break statement is used as the last
statement in each case's statement list
» A break statement causes control to transfer
to the end of the switch statement
» If a break statement is not used, the flow of
control will continue into the next case
» Sometimes this may be appropriate, but often
we want to execute only the statements
associated with one case
https://www.facebook.com/Oxus20
The switch Statement
» An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
https://www.facebook.com/Oxus20
The switch Statement
» A switch statement can have an optional
default case
» The default case has no associated value
and simply uses the reserved word
default
» If the default case is present, control will
transfer to it if no other case value matches
» If there is no default case, and no other
value matches, control falls through to the
statement after the switch
https://www.facebook.com/Oxus20
The switch Statement
» The expression of a switch statement
must result in an integral type, meaning an
int or a char
» It cannot be a boolean value, a floating
point value (float or double), or another
integer type
» The implicit boolean condition in a switch
statement is equality
» You cannot perform relational checks with a
switch statement
https://www.facebook.com/Oxus20
GradeReport.java
public class GradeReport
{
//----------------------------------------------------------
// Reads a grade from the user and prints comments
// accordingly.
//----------------------------------------------------------
public static void main (String[] args)
{
int grade, category;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a numeric grade (0 to 100): ");
grade = scan.nextInt();
category = grade / 10;
System.out.print ("That grade is ");
https://www.facebook.com/Oxus20
GradeReport.java
switch (category)
{
case 10:
System.out.println ("a perfect score. Well done.");
break;
case 9:
System.out.println ("well above average. Great.");
break;
case 8:
System.out.println ("above average. Nice job.");
break;
case 7:
System.out.println ("average.");
break;
case 6:
System.out.println ("below average.");
System.out.println ("See the instructor.");
break;
default:
System.out.println ("not passing.");
}
}
}
https://www.facebook.com/Oxus20
Outline
The if Statement and Conditions
Other Conditional Statements
Comparing Data
https://www.facebook.com/Oxus20
Comparing Data
» When comparing data using boolean
expressions, it's important to understand
the nuances of certain data types
» Let's examine some key situations:
˃ Comparing floating point values for equality
˃ Comparing characters
˃ Comparing strings (alphabetical order)
˃ Comparing object vs. comparing object references
https://www.facebook.com/Oxus20
Comparing Float Values
» You should rarely use the equality operator
(==) when comparing two floating point values
(float or double)
» Two floating point values are equal only if their
underlying binary representations match
exactly
» Computations often result in slight differences
that may be irrelevant
» In many situations, you might consider two
floating point numbers to be "close enough"
even if they aren't exactly equal
https://www.facebook.com/Oxus20
Comparing Float Values
» To determine the equality of two floats, you
may want to use the following technique:
if (Math.abs(f1 - f2) < TOLERANCE)
System.out.println ("Essentially equal");
• If the difference between the two floating point
values is less than the tolerance, they are
considered to be equal
• The tolerance could be set to any appropriate
level, such as 0.000001
https://www.facebook.com/Oxus20
Comparing Characters
» As we've discussed, Java character data is based
on the Unicode character set
» Unicode establishes a particular numeric value for
each character, and therefore an ordering
» We can use relational operators on character data
based on this ordering
» For example, the character '+' is less than the
character 'J' because it comes before it in the
Unicode character set
» Appendix C provides an overview of Unicode
https://www.facebook.com/Oxus20
Comparing Characters
» In Unicode, the digit characters (0-9) are
contiguous and in order
» Likewise, the uppercase letters (A-Z) and
lowercase letters (a-z) are contiguous and in
order
Characters Unicode Values
0 – 9 48 through 57
A – Z 65 through 90
a – z 97 through 122
https://www.facebook.com/Oxus20
Comparing Strings
» Remember that in Java a character string is an
object
» The equals method can be called with strings
to determine if two strings contain exactly the
same characters in the same order
» The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
https://www.facebook.com/Oxus20
Comparing Strings
» We cannot use the relational operators to
compare strings
» The String class contains a method called
compareTo to determine if one string
comes before another
» A call to name1.compareTo(name2)
˃ returns zero if name1 and name2 are equal (contain the same
characters)
˃ returns a negative value if name1 is less than name2
˃ returns a positive value if name1 is greater than name2
https://www.facebook.com/Oxus20
Comparing Strings
if (name1.compareTo(name2) < 0)
System.out.println (name1 + "comes first");
else
if (name1.compareTo(name2) == 0)
System.out.println ("Same name");
else
System.out.println (name2 + "comes first");
• Because comparing characters and strings is
based on a character set, it is called a
lexicographic ordering
https://www.facebook.com/Oxus20
Lexicographic Ordering
» Lexicographic ordering is not strictly
alphabetical when uppercase and lowercase
characters are mixed
» For example, the string "Great" comes
before the string "fantastic" because all of
the uppercase letters come before all of the
lowercase letters in Unicode
» Also, short strings come before longer strings
with the same prefix (lexicographically)
» Therefore "book" comes before
"bookcase"https://www.facebook.com/Oxus20
Comparing Objects
» The == operator can be applied to objects – it
returns true if the two references are aliases of
each other
» The equals method is defined for all objects, but
unless we redefine it when we write a class, it has
the same semantics as the == operator
» It has been redefined in the String class to
compare the characters in the two strings
» When you write a class, you can redefine the
equals method to return true under whatever
conditions are appropriate
https://www.facebook.com/Oxus20
== vs. equals
 What is printed?
public static void main(String [] args)
{
GregorianCalendar today1 = new GregorianCalendar();
GregorianCalendar today2 = new GregorianCalendar();
GregorianCalendar todayCopy = today1;
System.out.println("today1 == today2: " +
(today1 == today2));
System.out.println("today1 == todayCopy: " +
(today1 == todayCopy));
System.out.println("todayCopy == today2: " +
(todayCopy == today2));
System.out.println("today1.equals(today2): " +
today1.equals(today2));
System.out.println("today1.equals(todayCopy): " +
today1.equals(todayCopy));
System.out.println("todayCopy.equals(today2): " +
todayCopy.equals(today2));
}
https://www.facebook.com/Oxus20
END
https://www.facebook.com/Oxus20
58

Más contenido relacionado

Destacado

PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented ProgrammingAbdul Rahman Sherzad
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingLynn Langit
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryOXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesOXUS 20
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepOXUS 20
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debugboyw165
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsOXUS 20
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesAbdul Rahman Sherzad
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
 

Destacado (20)

PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids Programming
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debug
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
Java essential notes
Java essential notesJava essential notes
Java essential notes
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 

Similar a Conditional Statement

03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
C programming
C programmingC programming
C programmingXad Kuain
 
Control Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxControl Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxdoncreiz1
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2sotlsoc
 
Session 07 - Flow Control Statements
Session 07 - Flow Control StatementsSession 07 - Flow Control Statements
Session 07 - Flow Control StatementsSiddharthSelenium
 
Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1sotlsoc
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5Vince Vo
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 

Similar a Conditional Statement (20)

03a control structures
03a   control structures03a   control structures
03a control structures
 
Bsit1
Bsit1Bsit1
Bsit1
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
C programming
C programmingC programming
C programming
 
control statement
control statement control statement
control statement
 
Control Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxControl Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptx
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2
 
Fekra c++ Course #2
Fekra c++ Course #2Fekra c++ Course #2
Fekra c++ Course #2
 
Session 07 - Flow Control Statements
Session 07 - Flow Control StatementsSession 07 - Flow Control Statements
Session 07 - Flow Control Statements
 
Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
M C6java5
M C6java5M C6java5
M C6java5
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
Ch4
Ch4Ch4
Ch4
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 

Más de OXUS 20

Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersOXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIOXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 

Más de OXUS 20 (7)

Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 

Último

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

Último (20)

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Conditional Statement

  • 2. Outline The if Statement and Conditions Other Conditional Statements Comparing Data After : The while Statement Iterators Other Repetition Statements https://www.facebook.com/Oxus20
  • 3. Flow of Control » Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence » Some programming statements allow us to: ˃ decide whether or not to execute a particular statement ˃ execute a statement over and over, repetitively » These decisions are based on boolean expressions (or conditions) that evaluate to true or false » The order of statement execution is called the flow of control https://www.facebook.com/Oxus20
  • 4. Conditional Statements » A conditional statement lets us choose which statement will be executed next » Therefore they are sometimes called selection statements » Conditional statements give us the power to make basic decisions » The Java conditional statements are the: ˃ if statement ˃ if-else statement ˃ switch statement https://www.facebook.com/Oxus20
  • 5. The if Statement » The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped. https://www.facebook.com/Oxus20
  • 6. Logic of an if statement condition evaluated statement true false https://www.facebook.com/Oxus20
  • 7. Boolean Expressions  A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to  Note the difference between the equality operator (==) and the assignment operator (=) https://www.facebook.com/Oxus20
  • 8. The if Statement » An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); • First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next https://www.facebook.com/Oxus20
  • 9. Age.java … public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. " + "Enjoy."); System.out.println ("Age is a state of mind."); } } https://www.facebook.com/Oxus20
  • 10. Age.java Output ----jGRASP exec: java Age Enter your age: 12 You entered: 12 Youth is a wonderful thing. Enjoy. Age is a state of mind. ----jGRASP: operation complete. ----jGRASP exec: java Age Enter your age: 100 You entered: 100 Age is a state of mind. ----jGRASP: operation complete. https://www.facebook.com/Oxus20
  • 11. Indentation  The statement controlled by the if statement is indented to indicate that relationship  The use of a consistent indentation style makes a program easier to read and understand  Although it makes no difference to the compiler, proper indentation is crucial "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding https://www.facebook.com/Oxus20
  • 12. The if Statement » What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse • The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators https://www.facebook.com/Oxus20
  • 13. Logical Operators  Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR  They all take boolean operands and produce boolean results  Logical NOT is a unary operator (it operates on one operand)  Logical AND and logical OR are binary operators (each operates on two operands) https://www.facebook.com/Oxus20
  • 14. Logical NOT » The logical NOT operation is also called logical negation or logical complement » If some boolean condition a is true, then !a is false; if a is false, then !a is true » Logical expressions can be shown using a truth table a !a true false false true https://www.facebook.com/Oxus20
  • 15. Logical AND and Logical OR » The logical AND expression a && b is true if both a and b are true, and false otherwise » The logical OR expression a || b is true if a or b or both are true, and false otherwisehttps://www.facebook.com/Oxus20
  • 16. Logical Operators » Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) System.out.println ("Processing…"); • All logical operators have lower precedence than the relational operators • Logical NOT has higher precedence than logical AND and logical OR https://www.facebook.com/Oxus20
  • 17. Logical Operators » A truth table shows all possible true-false combinations of the terms » Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true true true true true false false true false true false true false false false false https://www.facebook.com/Oxus20
  • 18. Boolean Expressions » Specific expressions can be evaluated using truth tables total < MAX found !found total < MAX && !found false false true false false true false false true false true true true true false false https://www.facebook.com/Oxus20
  • 19. Short-Circuited Operators» The processing of logical AND and logical OR is “short-circuited” » If the left operand is sufficient to determine the result, the right operand is not evaluated • This type of processing must be used carefully if (count != 0 && total/count > MAX) System.out.println ("Testing…"); https://www.facebook.com/Oxus20
  • 20. English conditions in Java » true if ch is the first letter in the alphabet » Test if a variable’s value is within a specified range ˃ true if x is between min and max inclusive (including min and max) ˃ true if x is between min and max exclusive (excluding the endpoints » Test if variable’s value is outside the range ˃ true if x is less than min or greater than max https://www.facebook.com/Oxus20
  • 21. Testing » Execute all paths through the program ˃ Recall the flow-chart » Good idea to test all combinations of an && and a || » When numeric ranges, test the values around change in behavior » Not necessary to test all possible values » Most cases it is impossible to test exhaustively https://www.facebook.com/Oxus20
  • 22. Outline The if Statement and Conditions Other Conditional Statements Comparing Data https://www.facebook.com/Oxus20
  • 23. The if-else Statement » An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both https://www.facebook.com/Oxus20
  • 24. from Wages.java (page 211)final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work // week Scanner scan = new Scanner (System.in); double pay = 0.0; System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; https://www.facebook.com/Oxus20
  • 25. Logic of an if-else statement condition evaluated statement1 true false statement2 https://www.facebook.com/Oxus20
  • 26. else if draft String grdStr; if (grade >= 90) grdStr = “A”; else if (grade >= 80) grdStr = “B”; else if (grade >= 70) grdStr = “C”; else if (grade >= 60) grdStr = “D”; else grdStr = “F”; String grdStr; if (grade >= 90) grdStr = “A”; else if (grade >= 80) grdStr = “B”; else if (grade >= 70) grdStr = “C”; else if (grade >= 60) grdStr = “D”; else grdStr = “F”; https://www.facebook.com/Oxus20
  • 27. Indentation Revisited » Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not https://www.facebook.com/Oxus20
  • 28. Block Statements » Several statements can be grouped together into a block statement delimited by braces » A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; } https://www.facebook.com/Oxus20
  • 29. Block Statements » In an if-else statement, the if portion, or the else portion, or both, could be block statementsif (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } https://www.facebook.com/Oxus20
  • 30. Guessing.java … final int MAX = 10; int answer, guess; Scanner scan = new Scanner (System.in); Random generator = new Random(); answer = generator.nextInt(MAX) + 1; System.out.print ("I'm thinking of a number between 1 " + "and " + MAX + ". Guess what it is: "); guess = scan.nextInt(); if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } } } https://www.facebook.com/Oxus20
  • 31. Nested if Statements » The statement executed as a result of an if statement or else clause could be another if statement » These are called nested if statements » An else clause is matched to the last unmatched if (no matter what the indentation implies) » Braces can be used to specify the if statement to which an else clause belongs https://www.facebook.com/Oxus20
  • 32. MinOfThree.java … int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextInt(); num2 = scan.nextInt(); num3 = scan.nextInt(); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println ("Minimum value: " + min); } } https://www.facebook.com/Oxus20
  • 33. Importance of Curly Braces » Print “We have a problem” if examGrade < 60 » Print “We have a real problem” if examGrade < 60 and quizGrade < 10 » Print “Ok” if examGrade >= 60 int examGrade, quizGrade; if (examGrade < 60) System.out.println(“We have a problem”); if (quizGrade < 10) System.out.println(“We have a real problem”); else System.out.println(“Ok”); https://www.facebook.com/Oxus20
  • 34. Exam Grade Flowchart int examGrade, quizGrade; if (examGrade < 60) System.out.println(“We have a problem”); if (quizGrade < 10) System.out.println(“We have a real problem”); else System.out.println(“Ok”); https://www.facebook.com/Oxus20
  • 35. Writing Cases » Print “We have a problem” if examGrade < 60 » Print “We have a real problem” if examGrade < 60 and quizGrade < 10 » Print “Ok” if examGrade >= 60 examGrade < 60 quizGrade < 10 Action Case 1 “We have a problem” Case 2 “We have a problem” and “We have a real problem” Case 3 “Ok” https://www.facebook.com/Oxus20
  • 36. pinna stalkTwists divided2 divided3 Shaded-Limestone nearOak Id=“Maidenhair” id=“Sensitive Fern” id=“Fancy Fern” id = “Unknown” id=“Walking Fern” id = “Oak Fern” id = “Unknown” Fern Flow Chart (false) (true) https://www.facebook.com/Oxus20
  • 37. Cases pinna shadedLimestone nearOak stalkTwists divided2 divided3 output “Maidenhair” “Sensitive Fern” “Fancy Fern” “Unknown” (1) “Walking Fern” “Oak Fern” “Unknown” (2) To produce output, some variables must be true, others false, and for some, it does not matter. (Place true, false, or ? in the table.) https://www.facebook.com/Oxus20
  • 38. The switch Statement » The switch statement provides another way to decide which statement to execute next » The switch statement evaluates an expression, then attempts to match the result to one of several possible cases » Each case contains a value and a list of statements » The flow of control transfers to statement associated with the first case value that matches https://www.facebook.com/Oxus20
  • 39. The switch Statement » The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words If expression matches value2, control jumps to here https://www.facebook.com/Oxus20
  • 40. The switch Statement » Often a break statement is used as the last statement in each case's statement list » A break statement causes control to transfer to the end of the switch statement » If a break statement is not used, the flow of control will continue into the next case » Sometimes this may be appropriate, but often we want to execute only the statements associated with one case https://www.facebook.com/Oxus20
  • 41. The switch Statement » An example of a switch statement: switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } https://www.facebook.com/Oxus20
  • 42. The switch Statement » A switch statement can have an optional default case » The default case has no associated value and simply uses the reserved word default » If the default case is present, control will transfer to it if no other case value matches » If there is no default case, and no other value matches, control falls through to the statement after the switch https://www.facebook.com/Oxus20
  • 43. The switch Statement » The expression of a switch statement must result in an integral type, meaning an int or a char » It cannot be a boolean value, a floating point value (float or double), or another integer type » The implicit boolean condition in a switch statement is equality » You cannot perform relational checks with a switch statement https://www.facebook.com/Oxus20
  • 44. GradeReport.java public class GradeReport { //---------------------------------------------------------- // Reads a grade from the user and prints comments // accordingly. //---------------------------------------------------------- public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is "); https://www.facebook.com/Oxus20
  • 45. GradeReport.java switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Great."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average."); System.out.println ("See the instructor."); break; default: System.out.println ("not passing."); } } } https://www.facebook.com/Oxus20
  • 46. Outline The if Statement and Conditions Other Conditional Statements Comparing Data https://www.facebook.com/Oxus20
  • 47. Comparing Data » When comparing data using boolean expressions, it's important to understand the nuances of certain data types » Let's examine some key situations: ˃ Comparing floating point values for equality ˃ Comparing characters ˃ Comparing strings (alphabetical order) ˃ Comparing object vs. comparing object references https://www.facebook.com/Oxus20
  • 48. Comparing Float Values » You should rarely use the equality operator (==) when comparing two floating point values (float or double) » Two floating point values are equal only if their underlying binary representations match exactly » Computations often result in slight differences that may be irrelevant » In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal https://www.facebook.com/Oxus20
  • 49. Comparing Float Values » To determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); • If the difference between the two floating point values is less than the tolerance, they are considered to be equal • The tolerance could be set to any appropriate level, such as 0.000001 https://www.facebook.com/Oxus20
  • 50. Comparing Characters » As we've discussed, Java character data is based on the Unicode character set » Unicode establishes a particular numeric value for each character, and therefore an ordering » We can use relational operators on character data based on this ordering » For example, the character '+' is less than the character 'J' because it comes before it in the Unicode character set » Appendix C provides an overview of Unicode https://www.facebook.com/Oxus20
  • 51. Comparing Characters » In Unicode, the digit characters (0-9) are contiguous and in order » Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122 https://www.facebook.com/Oxus20
  • 52. Comparing Strings » Remember that in Java a character string is an object » The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order » The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); https://www.facebook.com/Oxus20
  • 53. Comparing Strings » We cannot use the relational operators to compare strings » The String class contains a method called compareTo to determine if one string comes before another » A call to name1.compareTo(name2) ˃ returns zero if name1 and name2 are equal (contain the same characters) ˃ returns a negative value if name1 is less than name2 ˃ returns a positive value if name1 is greater than name2 https://www.facebook.com/Oxus20
  • 54. Comparing Strings if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); • Because comparing characters and strings is based on a character set, it is called a lexicographic ordering https://www.facebook.com/Oxus20
  • 55. Lexicographic Ordering » Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed » For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode » Also, short strings come before longer strings with the same prefix (lexicographically) » Therefore "book" comes before "bookcase"https://www.facebook.com/Oxus20
  • 56. Comparing Objects » The == operator can be applied to objects – it returns true if the two references are aliases of each other » The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator » It has been redefined in the String class to compare the characters in the two strings » When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate https://www.facebook.com/Oxus20
  • 57. == vs. equals  What is printed? public static void main(String [] args) { GregorianCalendar today1 = new GregorianCalendar(); GregorianCalendar today2 = new GregorianCalendar(); GregorianCalendar todayCopy = today1; System.out.println("today1 == today2: " + (today1 == today2)); System.out.println("today1 == todayCopy: " + (today1 == todayCopy)); System.out.println("todayCopy == today2: " + (todayCopy == today2)); System.out.println("today1.equals(today2): " + today1.equals(today2)); System.out.println("today1.equals(todayCopy): " + today1.equals(todayCopy)); System.out.println("todayCopy.equals(today2): " + todayCopy.equals(today2)); } https://www.facebook.com/Oxus20