1 lecture 2 b declaration and use of variables b expressions and operator precedence b introduction...

50
1 Lecture 2 Lecture 2 declaration and use of variables declaration and use of variables expressions and operator precedence expressions and operator precedence introduction to objects introduction to objects class libraries class libraries flow of control flow of control decision-making statements decision-making statements boolean expressions boolean expressions

Upload: isabella-barber

Post on 18-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

1

Lecture 2Lecture 2

declaration and use of variablesdeclaration and use of variables expressions and operator precedenceexpressions and operator precedence introduction to objectsintroduction to objects class librariesclass libraries flow of control flow of control decision-making statementsdecision-making statements boolean expressionsboolean expressions

Page 2: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

2

VariablesVariables

A A variablevariable is a name for a location in memory is a name for a location in memory A variable must be A variable must be declareddeclared, specifying the variable's name , specifying the variable's name

and the type of information that will be held in itand the type of information that will be held in it

int total;int count, temp, result;int sum = 0;int base = 32, max = 149;

data typedata type variable namevariable name

Page 3: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

3

ConstantsConstants

In Java, we use the In Java, we use the finalfinal modifier to declare a constant modifier to declare a constant

final int MIN_HEIGHT = 60;

Constants:Constants:• give names to otherwise unclear literal valuesgive names to otherwise unclear literal values

• facilitate changes to the codefacilitate changes to the code

• prevent inadvertent errorsprevent inadvertent errors

Page 4: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

4

Primitive DataPrimitive Data

There are exactly eight primitive data types in JavaThere are exactly eight primitive data types in Java

Four represent integers:Four represent integers:• bytebyte, , shortshort, , intint, , longlong

Two represent floating point numbers:Two represent floating point numbers:• floatfloat, , doubledouble

One of them represents characters:One of them represents characters:• charchar

And one of them represents boolean values:And one of them represents boolean values:• booleanboolean

Page 5: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

5

Numeric Primitive DataNumeric Primitive Data

The difference between the various numeric primitive types The difference between the various numeric primitive types is their size, and therefore the values they can store:is their size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018

Page 6: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

6

CharactersCharacters

AA char char variable stores a single character from the variable stores a single character from the Unicode character setUnicode character set

The Unicode character set uses sixteen bits per character, The Unicode character set uses sixteen bits per character, allowing for 65,536 unique charactersallowing for 65,536 unique characters

Character literals are delimited by single quotes:Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n''a' 'X' '7' '$' ',' '\n'

Page 7: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

7

BooleanBoolean

AA boolean boolean value represents a true or false conditionvalue represents a true or false condition

A boolean can also be used to represent any two states, such A boolean can also be used to represent any two states, such as a light bulb being on or offas a light bulb being on or off

The reserved wordsThe reserved words true true andand false false are the only valid are the only valid values for a boolean typevalues for a boolean type

boolean done = false;boolean done = false;

Page 8: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

8

Arithmetic ExpressionsArithmetic Expressions

An An expressionexpression is a combination of operators and operands is a combination of operators and operands Arithmetic expressionsArithmetic expressions compute numeric results and make compute numeric results and make

use of the arithmetic operators:use of the arithmetic operators:

Addition +Subtraction -Multiplication *Division /Remainder %

If either or both operands to an arithmetic operator are If either or both operands to an arithmetic operator are floating point, the result is a floating pointfloating point, the result is a floating point

Page 9: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

9

Operator PrecedenceOperator Precedence

What is the order of evaluation in the following What is the order of evaluation in the following expressions?expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

a / (b * (c + (d - e)))4 123

Page 10: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

10

Assignment Assignment

An An assignment statementassignment statement changes the value of a variable changes the value of a variable

The assignment operator has a lower precedence than the arithmetic operatorsThe assignment operator has a lower precedence than the arithmetic operators

First the expression on the right First the expression on the right handhand

side of the = operator is evaluatedside of the = operator is evaluated

Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

total = 55;

Page 11: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

11

Assignment RevisitedAssignment Revisited

The right and left hand sides of an assignment statement The right and left hand sides of an assignment statement can contain the same variablecan contain the same variable

First, one is added to theFirst, one is added to theoriginal value of original value of countcount

Then the result is stored back into Then the result is stored back into countcount(overwriting the original value)(overwriting the original value)

count = count + 1;

Page 12: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

12

Data ConversionsData Conversions

Widening conversionsWidening conversions : usually from small to larger data : usually from small to larger data typetype

eg: eg: shortshort to to intint))

Narrowing conversions: Narrowing conversions: usually from large to smaller data usually from large to smaller data type. type.

eg: eg: intint to a to a shortshort

Page 13: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

13

Data ConversionsData Conversions

In Java, data conversions can occur in three ways:In Java, data conversions can occur in three ways:• assignment conversion (widening only)assignment conversion (widening only)

• arithmetic promotion (widening only)arithmetic promotion (widening only)

• casting (both)casting (both)

Example of cast:Example of cast:

result = (float) total / count;

Page 14: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

14

Creating ObjectsCreating Objects

A variable either holds a primitive type, or it holds a A variable either holds a primitive type, or it holds a referencereference to an object to an object

A class name can be used as a type to declare an A class name can be used as a type to declare an object object reference variablereference variable

String title;

No object has been created with this declarationNo object has been created with this declaration An object reference variable holds the address of an objectAn object reference variable holds the address of an object The object itself must be created separatelyThe object itself must be created separately

Page 15: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

15

Introduction to ObjectsIntroduction to Objects

Initially, we can think of an Initially, we can think of an objectobject as a collection of services as a collection of services that we can tell it to perform for usthat we can tell it to perform for us

The services are defined by methods in a class that defines The services are defined by methods in a class that defines the objectthe object

In the Lincoln program, we invoked the In the Lincoln program, we invoked the printlnprintln method method of the of the System.outSystem.out object: object:

System.out.println ("Whatever you are, be a good one.");

objectobject methodmethodInformation provided to the methodInformation provided to the method

(parameters)(parameters)

Page 16: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

16

The String ClassThe String Class

Every character string is an object in Java, defined by the Every character string is an object in Java, defined by the StringString class class

Every string literal, delimited by double quotation marks, Every string literal, delimited by double quotation marks, represents a represents a StringString object object

The The string concatenation operatorstring concatenation operator (+) is used to append one (+) is used to append one string to the end of anotherstring to the end of another

It can also be used to append a number to a stringIt can also be used to append a number to a string A string literal cannot be broken across two lines in a A string literal cannot be broken across two lines in a

programprogram See Facts.java (page 56)See Facts.java (page 56)

Page 17: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

17

String ConcatenationString Concatenation

The plus operator (+) is also used for arithmetic additionThe plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the The function that the + operator performs depends on the

type of the information on which it operatestype of the information on which it operates If both operands are strings, or if one is a string and one is If both operands are strings, or if one is a string and one is

a number, it performs string concatenationa number, it performs string concatenation If both operands are numeric, it adds themIf both operands are numeric, it adds them The + operator is evaluated left to rightThe + operator is evaluated left to right Parentheses can be used to force the operation orderParentheses can be used to force the operation order See Addition.java (page 58)See Addition.java (page 58)

Page 18: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

18

Escape SequencesEscape Sequences

What if we wanted to print a double quote character?What if we wanted to print a double quote character? The following line would confuse the compiler because it The following line would confuse the compiler because it

would interpret the second quote as the end of the stringwould interpret the second quote as the end of the string

System.out.println ("I said "Hello" to you.");

An An escape sequenceescape sequence is a series of characters that represents is a series of characters that represents a special charactera special character

An escape sequence begins with a backslash character (An escape sequence begins with a backslash character (\\), ), which indicates that the character(s) that follow should be which indicates that the character(s) that follow should be treated in a special waytreated in a special way

System.out.println ("I said \"Hello\" to you.");

Page 19: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

19

Escape SequencesEscape Sequences

Some Java escape sequences:Some Java escape sequences:

See Roses.java (page 59)See Roses.java (page 59)

Escape Sequence

\b\t\n\r\"\'\\

Meaning

backspacetab

newlinecarriage returndouble quotesingle quotebackslash

Page 20: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

20

Creating ObjectsCreating Objects

We use the We use the newnew operator to create an object operator to create an object

title = new String ("Java Software Solutions");

This calls the This calls the StringString constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object

Creating an object is called Creating an object is called instantiationinstantiation

An object is an An object is an instanceinstance of a particular class of a particular class

Page 21: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

21

Creating ObjectsCreating Objects

Because strings are so common, we don't have to use the Because strings are so common, we don't have to use the newnew operator to create a operator to create a StringString object object

title = "Java Software Solutions";

This is special syntax that only works for stringsThis is special syntax that only works for strings

Once an object has been instantiated, we can use the Once an object has been instantiated, we can use the dot dot operatoroperator to invoke its methods to invoke its methods

title.length()

Page 22: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

22

String MethodsString Methods

The The StringString class has several methods that are useful for class has several methods that are useful for manipulating stringsmanipulating strings

Many of the methods Many of the methods return a valuereturn a value, such as an integer or a , such as an integer or a new new StringString object object

See the list of See the list of StringString methods on page 75 and in Appendix methods on page 75 and in Appendix MM

See See StringMutationStringMutation.java .java (page 77)(page 77)

Page 23: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

23

Class LibrariesClass Libraries

A A class libraryclass library is a collection of classes that we can use when is a collection of classes that we can use when developing programsdeveloping programs

There is a There is a Java standard class libraryJava standard class library that is part of any that is part of any Java development environmentJava development environment

These classes are not part of the Java language per se, but These classes are not part of the Java language per se, but we rely on them heavilywe rely on them heavily

The The SystemSystem class and the class and the StringString class are part of the class are part of the Java standard class libraryJava standard class library

Other class libraries can be obtained through third party Other class libraries can be obtained through third party vendors, or you can create them yourselfvendors, or you can create them yourself

Page 24: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

24

PackagesPackages

The classes of the Java standard class library are organized The classes of the Java standard class library are organized into packagesinto packages

Some of the packages in the standard class library are:Some of the packages in the standard class library are:

Package

java.langjava.appletjava.awtjavax.swingjava.netjava.util

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and componentsNetwork communicationUtilities

Page 25: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

25

The import DeclarationThe import Declaration

When you want to use a class from a package, you could When you want to use a class from a package, you could use its use its fully qualified namefully qualified name

java.util.Random

Or you can Or you can importimport the class, then just use the class name the class, then just use the class nameimport java.util.Random;

To import all classes in a particular package, you can use To import all classes in a particular package, you can use the * wildcard characterthe * wildcard character

import java.util.*;

All classes of All classes of java.langjava.lang package automatically imported package automatically imported That's why we didn't have to explicitly import the That's why we didn't have to explicitly import the SystemSystem

or or StringString classes in earlier programs classes in earlier programs

Page 26: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

26

Class MethodsClass Methods

Some methods can be invoked through the class name, Some methods can be invoked through the class name, instead of through an object of the classinstead of through an object of the class

These methods are called These methods are called class methodsclass methods or or static methodsstatic methods

The The MathMath class contains many static methods, providing class contains many static methods, providing various mathematical functions, such as absolute value, various mathematical functions, such as absolute value, trigonometry functions, square root, etc.trigonometry functions, square root, etc.

temp = Math.cos(90) + Math.sqrt(delta);

Page 27: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

27

The Keyboard ClassThe Keyboard Class

The The KeyboardKeyboard class is NOT part of the Java standard class is NOT part of the Java standard class libraryclass library

It is provided by the authors of the textbook to make It is provided by the authors of the textbook to make reading input from the keyboard easyreading input from the keyboard easy

Details of the Details of the KeyboardKeyboard class are explored in Chapter 8 class are explored in Chapter 8 For now we will simply make use of itFor now we will simply make use of it The The KeyboardKeyboard class is part of a package called class is part of a package called cs1cs1, and , and

contains several static methods for reading particular types contains several static methods for reading particular types of dataof data

See See Echo.java Echo.java (page 86)(page 86) See Quadratic.java (page 87)See Quadratic.java (page 87)

Page 28: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

28

Flow of ControlFlow of Control

Unless indicated otherwise, the order of statement Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in execution through a method is linear: one after the other in the order they are writtenthe order they are written

Some programming statements modify that order:Some programming statements modify that order:• conditional or selection statements (if, if-else, switch)conditional or selection statements (if, if-else, switch)

• repetition statements (while, do-while, for)repetition statements (while, do-while, for)

Page 29: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

29

The if StatementThe if Statement

The The if statementif statement has the following syntax: has the following syntax:

if ( condition ) statement;

ifif is a Java is a Javareserved wordreserved word

The condition must be a The condition must be a boolean expressionboolean expression..It must evaluate to either true or false.It must evaluate to either true or false.

If the condition is true, the statement is executed.If the condition is true, the statement is executed.If it is false, the statement is skipped.If it is false, the statement is skipped.

Page 30: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

30

The if StatementThe if Statement

An example of an 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 First, the condition is evaluated. The value of sumsumis either greater than the value of is either greater than the value of MAXMAX, or it is not., or it is not.

If the condition is true, the assignment statement is executed.If the condition is true, the assignment statement is executed.If it is not, the assignment statement is skipped.If it is not, the assignment statement is skipped.

Either way, the call to println is executed next.Either way, the call to println is executed next.

See Age.java (page 112)See Age.java (page 112)

Page 31: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

31

Logic of an if statementLogic of an if statement

conditionevaluated

falsefalse

statement

truetrue

Page 32: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

32

Boolean ExpressionsBoolean Expressions

A condition often uses one of Java's A condition often uses one of Java's equality operators equality operators or or relational operatorsrelational operators, which all return boolean results:, which all return boolean results:

==== equal toequal to

!=!= not equal tonot equal to

<< less thanless than

>> greater thangreater than

<=<= less than or equal toless than or equal to

>=>= greater than or equal togreater than or equal to

Note the difference between the equality operator (Note the difference between the equality operator (====) and ) and the assignment operator (the assignment operator (==))

Page 33: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

33

The if-else StatementThe if-else Statement

An An else clauseelse clause can be added to an if statement to make it an can be added to an if statement to make it an if-else statementif-else statement::

if ( condition ) statement1;else statement2;

See Wages.java (page 116)See Wages.java (page 116)

If the condition is true, statement1 is executed; if the If the condition is true, statement1 is executed; if the condition is false, statement2 is executedcondition is false, statement2 is executed

One or the other will be executed, but not bothOne or the other will be executed, but not both

Page 34: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

34

Logic of an if-else statementLogic of an if-else statement

conditionevaluated

statement1

truetrue falsefalse

statement2

Page 35: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

35

Block StatementsBlock Statements

Several statements can be grouped together into a Several statements can be grouped together into a block block statementstatement

A block is delimited by braces ( { … } )A block is delimited by braces ( { … } )

A block statement can be used wherever a statement is A block statement can be used wherever a statement is called for in the Java syntaxcalled for in the Java syntax

For example, in an if-else statement, the if portion, or the For example, in an if-else statement, the if portion, or the else portion, or both, could be block statementselse portion, or both, could be block statements

See Guessing.java (page 117)See Guessing.java (page 117)

Page 36: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

36

Nested if StatementsNested if Statements

The statement executed as a result of an if statement or else The statement executed as a result of an if statement or else clause could be another if statementclause could be another if statement

These are called These are called nested if statementsnested if statements

See MinOfThree.java (page 118)See MinOfThree.java (page 118)

An else clause is matched to the last unmatched if (no An else clause is matched to the last unmatched if (no matter what the indentation implies)matter what the indentation implies)

Page 37: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

37

Comparing CharactersComparing Characters

We can use the relational operators on character dataWe can use the relational operators on character data The results are based on the Unicode character setThe results are based on the Unicode character set The following condition is true because the character '+' The following condition is true because the character '+'

comes before the character 'J' in Unicode:comes before the character 'J' in Unicode:

if ('+' < 'J') System.out.println ("+ is less than J");

The uppercase alphabet (A-Z) and the lowercase alphabet The uppercase alphabet (A-Z) and the lowercase alphabet (a-z) both appear in alphabetical order in Unicode(a-z) both appear in alphabetical order in Unicode

Page 38: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

38

Comparing StringsComparing Strings

Remember that a character string in Java is an objectRemember that a character string in Java is an object

We cannot use the relational operators to compare stringsWe cannot use the relational operators to compare strings

The The equalsequals method can be called on a string to determine method can be called on a string to determine if two strings contain exactly the same characters in the if two strings contain exactly the same characters in the same ordersame order

The String class also contains a method called The String class also contains a method called compareTocompareTo to determine if one string comes before another to determine if one string comes before another alphabetically (as determined by the Unicode character set)alphabetically (as determined by the Unicode character set)

Page 39: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

39

Comparing Floating Point Comparing Floating Point ValuesValues

We also have to be careful when comparing two floating We also have to be careful when comparing two floating point values (point values (floatfloat or or doubledouble) for equality) for equality

You should rarely use the equality operator (You should rarely use the equality operator (====) when ) when comparing two floatscomparing two floats

In many situations, you might consider two floating point In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly numbers to be "close enough" even if they aren't exactly equalequal

Therefore, to determine the equality of two floats, you may Therefore, to determine the equality of two floats, you may want to use the following technique:want to use the following technique:

if (Math.abs (f1 - f2) < 0.00001) System.out.println ("Essentially equal.");

Page 40: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

40

The switch StatementThe switch Statement

The The switch statementswitch statement provides another means to decide provides another means to decide which statement to execute nextwhich statement to execute next

The switch statement evaluates an expression, then The switch statement evaluates an expression, then attempts to match the result to one of several possible attempts to match the result to one of several possible casescases

Each case contains a value and a list of statementsEach case contains a value and a list of statements

The flow of control transfers to statement list associated The flow of control transfers to statement list associated with the first value that matcheswith the first value that matches

Page 41: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

41

The switch StatementThe switch Statement

The general syntax of a switch statement is:The general syntax of a switch statement is:

switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...

}

switchswitchandandcasecase

arearereservedreserved

wordswords

If If expressionexpressionmatches matches value2value2,,control jumpscontrol jumpsto hereto here

Page 42: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

42

The switch StatementThe switch Statement

Often a Often a break statementbreak statement is used as the last statement in each is used as the last statement in each case's statement listcase's statement list

A break statement causes control to transfer to the end of A break statement causes control to transfer to the end of the switch statementthe switch statement

If a break statement is not used, the flow of control will If a break statement is not used, the flow of control will continue into the next casecontinue into the next case

Sometimes this can be helpful, but usually we only want to Sometimes this can be helpful, but usually we only want to execute the statements associated with one caseexecute the statements associated with one case

Page 43: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

43

The switch StatementThe switch Statement

A switch statement can have an optional A switch statement can have an optional default casedefault case

The default case has no associated value and simply uses The default case has no associated value and simply uses the reserved word the reserved word defaultdefault

If the default case is present, control will transfer to it if no If the default case is present, control will transfer to it if no other case value matchesother case value matches

Though the default case can be positioned anywhere in the Though the default case can be positioned anywhere in the switch, it is usually placed at the endswitch, it is usually placed at the end

If there is no default case, and no other value matches, If there is no default case, and no other value matches, control falls through to the statement after the switchcontrol falls through to the statement after the switch

Page 44: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

44

The switch StatementThe switch Statement

The expression of a switch statement must result in an The expression of a switch statement must result in an integral data typeintegral data type, like an integer or character; it cannot be , like an integer or character; it cannot be a floating point valuea floating point value

Note that the implicit boolean condition in a switch Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with statement is equality - it tries to match the expression with a valuea value

You cannot perform relational checks with a switch You cannot perform relational checks with a switch statementstatement

See GradeReport.java (page 121)See GradeReport.java (page 121)

Page 45: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

45

Logical OperatorsLogical Operators

Boolean expressions can also use the following Boolean expressions can also use the following logical logical operatorsoperators::

!! Logical NOTLogical NOT

&&&& Logical ANDLogical AND

|||| Logical ORLogical OR

They all take boolean operands and produce boolean They all take boolean operands and produce boolean resultsresults

Logical NOT is a unary operator (it has one operand), but Logical NOT is a unary operator (it has one operand), but logical AND and logical OR are binary operators (they logical AND and logical OR are binary operators (they each have two operands)each have two operands)

Page 46: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

46

Logical NOTLogical NOT

The The logical NOTlogical NOT operation is also called operation is also called logical negationlogical negation or or logical complementlogical complement

If some boolean condition If some boolean condition aa is true, then is true, then !a!a is false; if is false; if aa is is false, then false, then !a!a is true is true

Logical expressions can be shown using Logical expressions can be shown using truth tablestruth tables

a

truefalse

!a

falsetrue

Page 47: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

47

Logical AND and Logical ORLogical AND and Logical OR

The The logical andlogical and expression expression

a && b

is true if both is true if both aa and and bb are true, and false otherwise are true, and false otherwise

The The logical orlogical or expression expression

a || b

is true if a or b or both are true, and false otherwiseis true if a or b or both are true, and false otherwise

Page 48: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

48

Truth TablesTruth Tables

A truth table shows the possible true/false combinations of A truth table shows the possible true/false combinations of the termsthe terms

Since Since &&&& and and |||| each have two operands, there are four each have two operands, there are four possible combinations of true and falsepossible combinations of true and false

a

truetruefalsefalse

b

truefalsetruefalse

a && b

truefalsefalsefalse

a || b

truetruetruefalse

Page 49: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

49

Logical OperatorsLogical Operators

Conditions in selection statements and loops can use logical Conditions in selection statements and loops can use logical operators to form complex expressionsoperators to form complex expressions

if (total < MAX && !found) System.out.println ("Processing…");

Logical operators have precedence relationships between Logical operators have precedence relationships between themselves and other operatorsthemselves and other operators

Page 50: 1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making

50

Truth TablesTruth Tables

Specific expressions can be evaluated using truth tablesSpecific expressions can be evaluated using truth tables

total < MAX

falsefalsetruetrue

found

falsetruefalsetrue

!found

truefalsetruefalse

total < MAX && !found

falsefalsetruefalse