Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Flow of Control: Selection and Equality Operators - Prof. Ramakrishna Varadarajan, Assignments of Javascript programming

An overview of selection statements, equality operators, relational operators, and logical operators in java programming. It covers topics such as forming conditions, if/else statements, comparing floating-point numbers, comparing objects, and the switch statement. It also explains the use of logical operators and short-circuit evaluation.

Typology: Assignments

Pre 2010

Uploaded on 09/17/2009

koofers-user-s6c
koofers-user-s6c 🇺🇸

10 documents

1 / 54

Toggle sidebar

Related documents


Partial preview of the text

Download Flow of Control: Selection and Equality Operators - Prof. Ramakrishna Varadarajan and more Assignments Javascript programming in PDF only on Docsity! Chapter 5 Flow of Control Part 1: Selection Topics • Forming Conditions • if/else Statements • Comparing Floating-Point Numbers • Comparing Objects – The equals Method – String Comparison Methods • The Conditional Operator ( ?: ) • The switch Statement Examples • If int variable age holds the value 32: ( age == 32 ) evaluates to true ( age != 32 ) evaluates to false Use the equality operators only with primitive types and object references, not to compare object data! • Do not confuse the equality operator (==) with the assignment operator (=). Relational Operators • Used to compare the values of two expressions • Result is true or false is greater than or equal to binary>= is greater than binary> is less than or equal to binary<= is less than binary< MeaningType (number of operands) Relational Operators Logical Operators • The NOT operator ( ! ) inverts the value of its operand. If the operand is true, the result will be false; and if the operand is false, the result will be true. • The AND operator ( && ) takes two boolean expressions as operands; if both operands are true, the result will be true, otherwise it will be false. • The OR operator ( || ) takes two boolean expressions as operands. If both operands are false, the result will be false; otherwise it will be true. Truth Table falsefalsetruefalsefalse truefalsetruetruefalse truefalsefalsefalsetrue truetruefalsetruetrue a || ba && b!aba For operator precedence, see Appendix B Short-Circuit Evaluation • For any logical operator, the operands are evaluated left to right • If the result of the logical operation can be determined after evaluating the first operand, the second operand is not evaluated. – If the first operand of an || is true, the result will be true – If the first operand of an && is false, the result will be false • See Example 5.1 Logical Operators.java Negation of Equality and Relational Operators a < ba >= b a <= ba > b a > ba <= b a >= ba < b a == ba != b a != ba == b !( Expression )Expression Examples These expressions are equivalent: ( age <= 18 || age >= 65 ) !( age > 18 && age < 65 ) !( age > 18 ) || !( age < 65 ) Simple if Statement • Used when program should perform an operation for one set of data, but do nothing for all other data • Syntax: if ( condition ) { // true block // executed if condition is true } • Curly braces are optional if true block contains only one statement Simple if Example • See Example 5.2 PassingGrade.java Do not put a semicolon after the condition. Doing so indicates that the true block is empty and can cause a logic error at run time. if /else • Used when data falls into two mutually exclusive categories and program should perform different operations for each set • Sample uses: – If password is correct, welcome user; otherwise, ask for reentry. – If person is old enough to vote, issue a voting card; otherwise, refuse the request. Example • See Example 5.3 Divider.java if/else if • Used when data falls into multiple mutually exclusive categories and program should do different operations for each set • Ex: – Determine letter grade based on numeric grade – Determine ticket price (different prices for child, adult, and senior) if/else if Syntax if ( condition 1 ) { // true block for condition 1 } else if (condition 2 ) { // true block for condition 2 } … else // false block for all conditions Finding the Smallest of Three Numbers read number1 read number2 read number3 if number1 is less than number2 smallest is number1 else smallest is number2 if number3 is less than smallest smallest is number3 See Example 5.5 FindSmallest.java Nested if Statements • if statements can be written as part of the true or false block of another if statement. • Typically, you nest if statements when more information is required beyond the results of the first if condition • The compiler matches any else clause with the most previous if statement that doesn't already have an else clause. • You can use curly braces to force a desired if/else pairing. Example if ( x == 2 ) if ( y == x ) System.out.println( "x and y equal 2" ); else System.out.println( "x equals 2," + " but y does not" ); • The else clause is paired with the second if , that is: if ( y == x ) Example 5.6: Generate a Secret Number generate a secret random number between 1 and 10 prompt the user for a guess if guess is not between 1 and 10 print message else if guess equals the secret number print congratulations else print the secret number if ( guess is within 3 numbers ) print "You were close" else print "You missed by a mile" print "Better luck next time" Testing Techniques • Execution Path Testing – Develop a test plan that includes running the program multiple times with data values that cause all true and false blocks to be executed. – Check results against the program specifications • Black Box Testing – Treat program like a black box (we don't know how the code is written) – Develop test data based on program specifications When testing your program, develop input values that execute all possible paths and verify that the logic correctly implements the program specifications. Comparing Objects • The equality operator ( == ) compares object references. • Example: – If d1 and d2 are two Date object references, then ( d1 == d2 ) evaluates to true only if d1 and d2 point to the same object, that is, the same memory location. *** The equality operator does not compare the data (month, day, and year) in those objects. Comparing Object Data • To compare object data, use the equals method • Example (with d1 and d2 Date object references): d1.equals( d2 ) returns true if the month, day, and year of d1 equals the month, day, and year of d2. equals( Object obj ) returns true if the data of the object obj is equal to the data in the object used to call the method boolean Method name and argument listReturn type Comparing Date Objects • See Example 5.10 ComparingObjects.java The equalsIgnoreCase Method • Example: String s1 = "Exit", s2 = "exit"; if ( s1.equalsIgnoreCase( s2 ) ) System.exit( 0 ); equalsIgnoreCase( String str ) compares the value of two Strings, treating uppercase and lowercase characters as equal. Returns true if the Strings are equal; returns false otherwise. boolean Method name and argument listReturn type The compareTo Method • A character with a lower Unicode numeric value is considered less than a character with a higher Unicode numeric value. • a is less than b and A is less than a • See Example 5.11 ComparingStrings.java compareTo( String str ) compares the value of the two Strings. If the String object is less than the String argument, str, a negative integer is returned. If the String object is greater than the String argument, a positive number is returned; if the two Strings are equal, 0 is returned. int Method name and argument listReturn type The Conditional Operator (?:) • The conditional operator ( ?: ) contributes one of two values to an expression based on the value of the condition. • Some uses are – handling invalid input – outputting similar messages. • Syntax: ( condition ? trueExp : falseExp ) If condition is true, trueExp is used in the expression If condition is false, falseExp is used in the expression Syntax of switch switch ( char or integer expression ) { case constant1: // statement(s); break; // optional case constant2: // statement(s); break; // optional … default: // optional statement(s); … } Operation of switch • The expression is evaluated, then its value is compared to the case constants in order. • When a match is found, the statements under that case constant are executed in sequence until either a break statement or the end of the switch block is reached. • Once a match is found, if other case constants are encountered before a break statement, then the statements for these case constants are also executed. Some Finer Points of switch • The break statements are optional. Their job is to terminate execution of the switch statement. • The default label and its statements, are also optional. They are executed when the value of the expression does not match any of the case constants. • The statements under the case constant are also optional, so multiple case constants can be written in sequence if identical operations will be performed for those values.
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved