Download Control Statements

Document related concepts
no text concepts found
Transcript
1
Chapter 4 - Control Structures: Part 1
Outline
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.11
4.12
4.13
Introduction
Algorithms
Pseudocode
Control Structures
if Single-Selection Statement
if else Selection Statement
while Repetition Statement
Compound Assignment Operators
Increment and Decrement Operators
Primitive Types
 2003 Prentice Hall, Inc. All rights reserved.
2
4.1
Introduction
• We learn about Control Structures
– Structured-programming principle
– Control structures help build and manipulate objects
(Chapter 8)
 2003 Prentice Hall, Inc. All rights reserved.
3
4.2
Algorithms
• Algorithm
– Series of actions in specific order
• The actions executed
• The order in which actions execute
• Program control
– Specifying the order in which actions execute
• Control structures help specify this order
 2003 Prentice Hall, Inc. All rights reserved.
4
4.3
Pseudocode
• Pseudocode
– Informal language for developing algorithms
– Not executed on computers
– Helps developers “think out” algorithms
 2003 Prentice Hall, Inc. All rights reserved.
5
4.4
Control Structures
• Sequential execution
– Program statements execute one after the other
• Transfer of control
– Three control structures can specify order of statements
• Sequence structure (default)
• Selection structure
• Repetition structure
• Activity diagram
– Models the workflow (flowchart)
• Action-state symbols
• Transition arrows
 2003 Prentice Hall, Inc. All rights reserved.
6
add grade to total
Corresponding Java statement:
total = total + grade;
add 1 to counter
Corresponding Java statement:
counter = counter + 1;
Fig 4.1 Sequence structure activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
7
Ja va Keyw ord s
abstract
assert
boolean
break
byte
case
catch
char
class
continue
default
do
double
else
extends
final
finally float
for
if
implements import
instanceof int
interface
long
native
new
package
private
protected public
return
short
static
strictfp
super
switch
synchronized this
throw
throws
transient try
void
volatile
while
Keywords that are reserved, but not currently used
const
goto
Fig. 4.2 Ja va keyw o rd s.
 2003 Prentice Hall, Inc. All rights reserved.
8
4.4
Control Structures
• Java has a sequence structure “built-in”
• Java provides three selection structures
– if
– if…else
– switch
• Java provides three repetition structures
– while
– do…while
– for
• Each of these words is a Java keyword
 2003 Prentice Hall, Inc. All rights reserved.
9
4.5
if Single-Selection Statement
• Single-entry/single-exit control structure
• Perform action only when condition is true
• Action/decision programming model
 2003 Prentice Hall, Inc. All rights reserved.
10
if (studentGrade >= 60)
{
System.out.println (“Passed”);
}
[grade >= 60]
print “Passed”
[grade < 60]
Fig 4.3 if single-selections statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
11
4.6
if…else Selection Statement
• Perform action only when condition is true
• Perform different specified action when condition
is false
• Conditional operator (?:)
• Nested if…else selection structures
 2003 Prentice Hall, Inc. All rights reserved.
12
if (studentGrade >= 60)
{
System.out.println (“Passed”);
}
else
{
System.out.println (“Failed”);
}
[grade < 60]
print “Failed”
[grade >= 60]
print “Passed”
Fig 4.4 if…else double-selections statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
13
Conditional Operator (?:)
System.out.println (studentGrade >= 60 ?
“Passed”: “Failed”);
 2003 Prentice Hall, Inc. All rights reserved.
14
Nested if…else selection structures
if (studentGrade >= 90)
System.out.println (“A”);
else if (studentGrade >= 80)
System.out.println (“B”);
else if (studentGrade >= 70)
System.out.println (“C”);
else if (studentGrade >= 60)
System.out.println (“D”);
else
System.out.println (“F”);
 2003 Prentice Hall, Inc. All rights reserved.
15
4.7
while Repetition Statement
• Repeat action while condition remains true
• Condition should eventually become false (or
never-ending loop)
 2003 Prentice Hall, Inc. All rights reserved.
16
while (product <= 1000)
{
product = 2 * product;
}
merge
decision
[product <= 1000]
double product value
[product > 1000]
Corresponding Java statement:
product = 2 * product;
Fig 4.5 while repetition statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
17
4.11 Compound Assignment Operators
• Assignment Operators
– Abbreviate assignment expressions
– Any statement of form
• variable = variable operator expression;
– Can be written as
• variable operator= expression;
– e.g., addition assignment operator +=
•c = c + 3
– can be written as
• c += 3
 2003 Prentice Hall, Inc. All rights reserved.
18
Assig nm ent
Sa m p le
Exp la na tion
op era tor
exp ression
Assume: int c = 3,
d = 5, e = 4, f
= 6, g = 12;
+=
c += 7
c = c + 7
-=
d -= 4
d = d - 4
*=
e *= 5
e = e * 5
/=
f /= 3
f = f / 3
%=
g %= 9
g = g % 9
Fig. 4.12 Arithm etic a ssig nm ent op era to rs.
 2003 Prentice Hall, Inc. All rights reserved.
Assig ns
10 to c
1 to d
20 to e
2 to f
3 to g
19
4.12 Increment and Decrement Operators
• Unary increment operator (++)
– Increment variable’s value by 1
• Unary decrement operator (--)
– Decrement variable’s value by 1
• C++ is a language “one better than” C
• Preincrement / predecrement operator
• Postincrement / postdecrement operator
 2003 Prentice Hall, Inc. All rights reserved.
20
Op era tor Ca lled
++
preincrement
++
postincrement
--
predecrement
--
postdecrement
Fig. 4.13 The inc rem ent
 2003 Prentice Hall, Inc. All rights reserved.
Sa m p le
exp ression
++a
Exp la na tion
Increment a by 1, then use the new
value of a in the expression in
which a resides.
a++
Use the current value of a in the
expression in which a resides, then
increment a by 1.
--b
Decrement b by 1, then use the
new value of b in the expression in
which b resides.
b-Use the current value of b in the
expression in which b resides, then
decrement b by 1.
a nd d ec re m ent op era tors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
21
// Fig. 4.14: Increment.java
// Preincrementing and postincrementing operators.
public class Increment {
Outline
Line 13 postincrements c
public static void main( String args[] )
{
int c;
// demonstrate postincrement
c = 5;
//
System.out.println( c );
//
System.out.println( c++ ); //
System.out.println( c );
//
System.out.println();
assign 5 to c
print 5 Line 21 preincrements
print 5 then postincrement
print 6
Increment.java
Line 13 postincrement
Line 21 preincrement
c
// skip a line
// demonstrate preincrement
c = 5;
//
System.out.println( c );
//
System.out.println( ++c ); //
System.out.println( c );
//
assign 5 to c
print 5
preincrement then print 6
print 6
} // end main
} // end class Increment
5
5
6
5
6
6
 2003 Prentice Hall, Inc.
All rights reserved.
22
4.13 Primitive Types
• Primitive types
– “building blocks” for more complicated types
• Java is strongly typed
– All variables in a Java program must have a type
• Java primitive types
– portable across computer platforms that support Java
 2003 Prentice Hall, Inc. All rights reserved.
23
Typ e
boolean
Size in b its
char
16
byte
8
short
16
int
32
long
64
float
32
double
64
Fig. 4.16 The Ja va
Va lues
true or false
Sta nd a rd
[Note: The representation of a boolean is
specific to the Java Virtual Machine on each
computer platform.]
'\u0000' to '\uFFFF'
(ISO Unicode character set)
(0 to 65535)
–128 to +127
(–27 to 27 – 1)
–32,768 to +32,767
(–215 to 215 – 1)
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
Negative range:
(IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
Negative range:
(IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
p rim itive typ es.
 2003 Prentice Hall, Inc. All rights reserved.
24
Chapter 5 – Control Structures: Part 2
Outline
5.1
5.2
5.3
5.4
5.5
5.6
5.7
5.8
5.9
Introduction
Essentials of Counter-Controlled Repetition
for Repetition Statement
Examples Using the for Statement
do…while Repetition Statement
switch Multiple-Selection Statement
break and continue Statements
Labeled break and continue Statements
Logical Operators
 2003 Prentice Hall, Inc. All rights reserved.
25
5.2
Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires:
–
–
–
–
Control variable (loop counter)
Initial value of the control variable
Increment/decrement of control variable through each loop
Condition that tests for the final value of the control variable
 2003 Prentice Hall, Inc. All rights reserved.
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
// Fig. 5.1: WhileCounter.java
// Counter-controlled repetition.
import java.awt.Graphics;
WhileCounter.ja
va
import javax.swing.JApplet;
Control-variableCondition
name is counter
tests for
counter’s final value
Control-variable initial value is 1
public class WhileCounter extends JApplet {
// draw lines on applet’s background
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
int counter = 1;
Line 14
Line 16
Increment Line
for counter
18
// initialization
while ( counter <= 10 ) { // repetition condition
g.drawLine( 10, 10, 250, counter * 10 );
++counter; // increment
} // end while
} // end method paint
} // end class WhileCounter
 2003 Prentice Hall, Inc.
All rights reserved.
27
5.3
for Repetition Statement
• Handles counter-controlled-repetition details
 2003 Prentice Hall, Inc. All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 5.2: ForCounter.java
// Counter-controlled repetition with the for statement.
import java.awt.Graphics;
import javax.swing.JApplet;
Condition tests for
Control-variable namecounter’s
is counterfinal value
public class ForCounter extends JApplet {
Control-variable initial value is 1
applet’s background
Increment for counter
// draw lines on
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
// for statement header includes initialization,
// repetition condition and increment
for ( int counter = 1; counter <= 10; counter++ )
g.drawLine( 10, 10, 250, counter * 10 );
Outline
ForCounter.java
Line 16
int counter =
1;
Line 16
counter <= 10;
Line 16
counter++;
} // end method paint
} // end class ForCounter
 2003 Prentice Hall, Inc.
All rights reserved.
29
for
keyword
Control
variable
Required
semicolon
separator
Final value of control
variable for which the
condition is true
Required
semicolon
separator
for ( int counter = 1; counter <= 10; counter++ )
Initial value of
control variable
Fig. 5.3
Loop-continuation
condition
Increment of control
variable
for statement header components.
 2003 Prentice Hall, Inc. All rights reserved.
30
5.3
for Repetition Structure (cont.)
for ( initialization; loopContinuationCondition; increment )
statement;
can usually be rewritten as:
initialization;
while ( loopContinuationCondition ) {
statement;
increment;
}
init, condition, increment all optional
Condition assumed to be true (unending loop) if omitted
 2003 Prentice Hall, Inc. All rights reserved.
31
Establish initial value of
control variable
int counter = 1
[counter <= 10]
Draw a line on the
applet
Increment the
control variable
[counter > 10]
Determine whether
the final value of
control variable has
been reached
Fig. 5.4
g.drawLine(
10, 10, 250,
counter * 10 );
for statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
counter++
32
5.4
Examples Using the for Statement
• Varying control variable in for statement
– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in increments of –1
• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in increments of 7
• for ( int i = 7; i <= 77; i += 7 )
 2003 Prentice Hall, Inc. All rights reserved.
33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 5.5: Sum.java
// Summing integers with the for statement.
import javax.swing.JOptionPane;
increment number by 2 each iteration
public class Sum {
public static void main( String args[] )
{
int total = 0; // initialize sum
Outline
Sum.java
Line 12
// total even integers from 2 through 100
for ( int number = 2; number <= 100; number += 2 )
total += number;
// display results
JOptionPane.showMessageDialog( null, "The sum is " + total,
"Total Even Integers from 2 to 100",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class Sum
 2003 Prentice Hall, Inc.
All rights reserved.
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 5.6: Interest.java
// Calculating compound interest.
import java.text.NumberFormat; // class for numeric formatting
Java treats floating-points as
import java.util.Locale; // class for country-specific information
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
Outline
Interest.java
type double
NumberFormat can format
numeric values as currency Lines 13-15
public class Interest {
Display
public static void main( String args[]
) currency values with
{
dollar sign ($)
double amount;
// amount on deposit at end of each year
double principal = 1000.0; // initial amount before interest
double rate = 0.05;
// interest rate
Line 18
Line 19
// create NumberFormat for currency in US dollar format
NumberFormat moneyFormat =
NumberFormat.getCurrencyInstance( Locale.US );
// create JTextArea to display output
JTextArea outputTextArea = new JTextArea();
// set first line of text in outputTextArea
outputTextArea.setText( "Year\tAmount on deposit\n" );
 2003 Prentice Hall, Inc.
All rights reserved.
35
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 10; year++ ) {
// calculate new amount for specified year
amount = principal * Math.pow( 1.0 + rate, year );
// append one line of text to outputTextArea
outputTextArea.append( year + "\t" +
moneyFormat.format( amount ) + "\n" );
Outline
Calculate amount with for
Interest.java
statement
Lines 28-31
} // end for
// display results
JOptionPane.showMessageDialog( null, outputTextArea,
"Compound Interest", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate the application
} // end main
} // end class Interest
 2003 Prentice Hall, Inc.
All rights reserved.
36
5.5
do…while Repetition Statement
• do…while structure
– Similar to while structure
– Tests loop-continuation after performing body of loop
• i.e., loop body always executes at least once
 2003 Prentice Hall, Inc. All rights reserved.
37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 5.7: DoWhileTest.java
// Using the do...while statement.
import java.awt.Graphics;
Outline
DoWhileTest.jav
a
import javax.swing.JApplet;
Oval is drawn before testing
counter’s final value
public class DoWhileTest extends JApplet {
Lines 16-20
// draw lines on applet
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
int counter = 1;
// initialize counter
do {
g.drawOval( 110 - counter * 10, 110 - counter * 10,
counter * 20, counter * 20 );
++counter;
} while ( counter <= 10 ); // end do...while
} // end method paint
} // end class DoWhileTest
 2003 Prentice Hall, Inc.
All rights reserved.
38
action state
[true]
condition
[false]
Fig. 5.8
do…while repetition statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
39
5.6
switch Multiple-Selection Statement
• switch statement
– Used for multiple selections
– case followed by integer or character (case 10 or case ‘y’)
– Multiple cases (without code) indicate the same thing done
for each case
case 3:
case 5:
case 7:
x=y+z;
break;
 2003 Prentice Hall, Inc. All rights reserved.
40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 5.9: SwitchTest.java
// Drawing lines, rectangles or ovals based on user input.
import java.awt.Graphics;
Outline
SwitchTest.java
import javax.swing.*;
public class SwitchTest extends JApplet {
int choice; // user's choice of which shape to draw
// initialize applet by obtaining user's choice
public void init()
{
Get user’s
String input; // user's input
Lines 16-21:
Getting user’s input
input in JApplet
// obtain user's choice
input = JOptionPane.showInputDialog(
"Enter 1 to draw lines\n" +
"Enter 2 to draw rectangles\n" +
"Enter 3 to draw ovals\n" );
choice = Integer.parseInt( input );
// convert input to int
} // end method init
// draw shapes on applet's background
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
for ( int i = 0; i < 10; i++ ) {
// loop 10 times (0-9)
 2003 Prentice Hall, Inc.
All rights reserved.
41
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
switch ( choice ) {
// determine shape to draw
user input (choice) is
Outline
case 1: // draw a line
switch
statement
determines
controlling
expression
g.drawLine( 10, 10, 250, 10 + i * 10 );
SwitchTest.java
which case label to execute,
break; // done processing case
case 2: // draw a rectangle
g.drawRect( 10 + i * 10, 10 + i
50 + i * 10, 50 + i * 10 );
break; // done processing case
depending on controlling expression
Line 32:
controlling
* 10,
expression
case 3: // draw an oval
g.drawOval( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break; // done processing case
Line 32:
switch statement
Line 48
default: // draw string indicating invalid value entered
g.drawString( "Invalid value entered",
10, 20 + i * 15 );
} // end switch
default case for invalid entries
} // end for
} // end method paint
} // end class SwitchTest
 2003 Prentice Hall, Inc.
All rights reserved.
42
Outline
SwitchTest.java
 2003 Prentice Hall, Inc.
All rights reserved.
43
Outline
SwitchTest.java
 2003 Prentice Hall, Inc.
All rights reserved.
44
[true]
case a
case a action(s)
break
case b action(s)
break
case z action(s)
break
[false]
[true]
case b
[false]
.
.
.
[true]
case z
[false]
default action(s)
Fig. 5.10 switch multiple-selection statement activity diagram with break statements.
 2003 Prentice Hall, Inc. All rights reserved.
45
5.7
break and continue Statements
• break/continue
– Alter flow of control
• break statement
– Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
• Escape early from loop or skip remainder of switch
• continue statement
– Skips remaining statements in loop body
– Proceeds to next iteration
• Used in while, for or do…while statements
 2003 Prentice Hall, Inc. All rights reserved.
46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
// Fig. 5.11: BreakTest.java
// Terminating a loop with break.
import javax.swing.JOptionPane;
BreakTest.java
public class BreakTest {
public static void main( String args[] )
{
Loop
String output = "";
int count;
for ( count = 1; count <= 10; count++ ) {
if ( count == 5 )
break;
exit for structure (break)
Line 12
when count equals 5
10 times
Lines 14-15
// loop 10 times
// if count is 5,
// terminate loop
output += count + " ";
} // end for
output += "\nBroke out of loop at count = " + count;
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
// terminate application
} // end main
} // end class BreakTest
 2003 Prentice Hall, Inc.
All rights reserved.
47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
// Fig. 5.12: ContinueTest.java
// Continuing with the next iteration of a loop.
import javax.swing.JOptionPane;
public class ContinueTest {
public static void main( String args[] )
{
String output = "";
ContinueTest.ja
Skip line 16 and proceed va
to
line 11 when count equals 5
Line 11
Loop 10 times
for ( int count = 1; count <= 10; count++ ) {
if ( count == 5 )
continue;
// loop 10 times
Lines 13-14
// if count is 5,
// skip remaining code in loop
output += count + " ";
} // end for
output += "\nUsed continue to skip printing 5";
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
// terminate application
} // end main
} // end class ContinueTest
 2003 Prentice Hall, Inc.
All rights reserved.
5.8
Labeled break and continue
Statements
• Labeled block
– Set of statements enclosed by {}
– Preceded by a label
• Labeled break statement
– Exit from nested control structures
– Proceeds to end of specified labeled block
• Labeled continue statement
–
–
–
–
Skips remaining statements in nested-loop body
Proceeds to beginning of specified labeled block
Controversial – disguised “goto” statement!
Always a better way than labeled continue
 2003 Prentice Hall, Inc. All rights reserved.
48
49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
// Fig. 5.13: BreakLabelTest.java
// Labeled break statement.
import javax.swing.JOptionPane;
public class BreakLabelTest {
stop is the labeled block
public static void main( String args[] )
{
String output = "";
stop: {
Loop 10 times
// count 10 rows
for ( int row = 1; row <= 10; row++ ) {
Nested loop 5 times
// count 5 columns
for ( int column = 1; column <= 5 ; column++ ) {
output += "*
Line 11
Line 14
// labeled block
if ( row == 5 )
break stop;
BreakLabelTest.
java
Line 17
Lines 19-20
// if row is 5,
// jump to end of stop block
";
} // end inner for
Exit to line 35 (next slide)
output += "\n";
} // end outer for
 2003 Prentice Hall, Inc.
All rights reserved.
50
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// following line is skipped
output += "\nLoops terminated normally";
} // end labeled block
JOptionPane.showMessageDialog( null, output,
"Testing break with a label",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
Outline
BreakLabelTest.
java
// terminate application
} // end main
} // end class BreakLabelTest
 2003 Prentice Hall, Inc.
All rights reserved.
51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
// Fig. 5.14: ContinueLabelTest.java
// Labeled continue statement.
import javax.swing.JOptionPane;
public class ContinueLabelTest {
nextRow is the labeled block
public static void main( String args[] )
{
String output = "";
nextRow:
Loop 5 times
Line 11
Line 14
// target label of continue statement
// count 5 rows
for ( int row = 1; row <= 5; row++ ) {
output += "\n";
ContinueLabelTe
st.java
Nested loop 10 times
Line 17
Lines 21-22
// count 10 columns per row
for ( int column = 1; column <= 10; column++ ) {
// if column greater than row, start next row
if ( column > row )
continue nextRow; // next iteration of labeled loop
output += "*
";
} // end inner for
continue to line 11 (nextRow)
} // end outer for
 2003 Prentice Hall, Inc.
All rights reserved.
52
29
30
31
32
33
34
35
36
37
38
JOptionPane.showMessageDialog( null, output,
"Testing continue with a label",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Outline
ContinueLabelTe
st.java
} // end main
} // end class ContinueLabelTest
 2003 Prentice Hall, Inc.
All rights reserved.
53
5.9
Logical Operators
• Logical operators
– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators
–
–
–
–
–
–
&&
&
||
|
^
!
(conditional AND) (short circuit)
(boolean logical AND)
(conditional OR) (short circuit)
(boolean logical OR)
(boolean logical exclusive OR)
(logical NOT)
(project > 75 && exam>= 80)
 2003 Prentice Hall, Inc. All rights reserved.
54
expression1 &&
expression2
false
false
false
false
true
false
true
false
false
true
true
true
Fig. 5.15 && (conditional AND) operator truth table.
expression1
expression2
expression1 ||
expression2
false
false
false
false
true
true
true
false
true
true
true
true
Fig. 5.16 || (conditional OR) operator truth table.
expression1
expression2
 2003 Prentice Hall, Inc. All rights reserved.
55
expression1 ^
expression2
false
false
false
false
true
true
true
false
true
true
true
false
Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table.
expression1
expression2
expression
!expression
false
true
true
false
Fig. 5.18 ! (logical negation, or logical NOT) operator truth table.
 2003 Prentice Hall, Inc. All rights reserved.
56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
// Fig. 5.19: LogicalOperators.java
// Logical operators.
import javax.swing.*;
LogicalOperator
s.java
public class LogicalOperators
public static void main( String args[] )
{
// create JTextArea to display results
JTextArea outputArea = new JTextArea( 17, 20 );
Lines 16-20
Lines 23-27
// attach JTextArea to a JScrollPane so user can scroll results
JScrollPane scroller = new JScrollPane( outputArea );
Conditional AND truth table
// create truth table for && (conditional AND) operator
String output = "Logical AND (&&)" +
"\nfalse && false: " + ( false && false ) +
"\nfalse && true: " + ( false && true ) +
"\ntrue && false: " + ( true && false ) +
"\ntrue && true: " + ( true && true );
Conditional OR truth table
// create truth table for || (conditional OR) operator
output += "\n\nLogical OR (||)" +
"\nfalse || false: " + ( false || false ) +
"\nfalse || true: " + ( false || true ) +
"\ntrue || false: " + ( true || false ) +
"\ntrue || true: " + ( true || true );
 2003 Prentice Hall, Inc.
All rights reserved.
57
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// create truth table for & (boolean logical AND) operator
output += "\n\nBoolean logical AND (&)" +
"\nfalse & false: " + ( false & false ) +
"\nfalse & true: " + ( false & true ) +
"\ntrue & false: " + ( true & false ) +
Boolean logical
"\ntrue & true: " + ( true & true );
Outline
AND
LogicalOperator
s.java
truth table
Lines
// create truth table for | (boolean logical inclusive OR) operator
output += "\n\nBoolean logical inclusive OR (|)" +
"\nfalse | false: " + ( false | false ) +
Lines
"\nfalse | true: " + ( false | true ) +
"\ntrue | false: " + ( true | false ) +
Boolean logical inclusive
Lines
"\ntrue | true: " + ( true | true );
30-34
37-41
44-48
OR truth table
// create truth table for ^ (boolean logical exclusive OR) operator
Lines
output += "\n\nBoolean logical exclusive OR (^)" +
"\nfalse ^ false: " + ( false ^ false ) +
"\nfalse ^ true: " + ( false ^ true ) +
"\ntrue ^ false: " + ( true ^ false ) +
Boolean logical exclusive
"\ntrue ^ true: " + ( true ^ true );
51-53
OR truth table
// create truth table for ! (logical negation) operator
output += "\n\nLogical NOT (!)" +
"\n!false: " + ( !false ) +
"\n!true: " + ( !true );
Logical NOT truth
outputArea.setText( output );
table
// place results in JTextArea
 2003 Prentice Hall, Inc.
All rights reserved.
57
58
59
60
61
62
63
64
JOptionPane.showMessageDialog( null, scroller,
"Truth Tables", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
58
Outline
LogicalOperator
s.java
} // end class LogicalOperators
 2003 Prentice Hall, Inc.
All rights reserved.