OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS CS 201 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology- George Koutsogiannakis
PREVIOUS TOPICS FORMING CONDITIONS FOR SELECTION RELATIONAL OPERATORS BOOLEAN EXPRESSIONS- TRUTH TABLES BOOLEAN OPERATIONS DE MORGANS LAWS if and else SELECTIONS If else SELECTIONS
NEW TOPICS SWITCH SELECTION STRUCTURE. COMPARING OBJECTS. COMPARING STRINGS. STRING TOKENIZER. CONDITIONAL OPERATOR.
The switch Statement In some selection operations, the switch statement can be used instead of an if/else/if statement Requirements: we must be comparing the value of a character (char) or integer (byte, short, or int) expression to constants of the same types
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 following that case constant are executed in sequence until either a break statement or the end of the switch block is reached. Thus, 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.
Example: a Simple Calculator Prompt user for two doubles (num1, num2) and a char (operation), which can be 'a' for addition or 's' for subtraction switch ( operation ) { case 'a': result = num1 + num2; break; case 's': result = num1 - num2; default: System.out.println( "Unrecognized option" ); }
A Case-Insensitive Calculator switch ( operation ) { case 'a': case 'A': result = num1 + num2; break; case 's': case 'S': result = num1 - num2; default: System.out.println( "Unrecognized option" ); }
Switch and if/else if A switch structure with break statements is equivalent to a if/else if blocks of code. The default condition is a single else at the end after the last else if.
Comparing objects for Equality Suppose that we have template class Student. In class StudentClient we instantiate two objects of Student class. Student st1=new Student(); Student st2=new Student(); Can we ask if the two are equal? And do we mean by equal?
Comparing objects for Equalit Equal refers to the values of the objects’ attributes. Therefore we want to compare the values of the attributes of the two objects Asking for the evaluation : if(st1==st2) does not compare the objects. Instead it compares the memory addresses that represent those two objects.
Comparing Object References The equality operator (==) compares object references (addresses in memory). Example: Suppose that we have a class called SimpleDate. The class has attributes: month, day, year. Suppose that we have d1 and d2 as two SimpleDate object references. Notice that object refernces refer to declarations only without the instantiation of the objects i.e.
Comparing Object References SimpleDate d1; SimpleDate d2; The two lines of code above indicates declarations only. At this time d1 and d2 have not been instantiated. The system knows that two memory locations are needed an addresses have been provided but no data has been generated as yet to be stored at these addresses. The line of code: if (d1 = = d2) evaluates to true only if d1 and d2 point to the same object reference, that is, the same memory location. *** The equality operator does not compare the data (month, day, and year) in those objects.
Comparing Object References Suppose we instantiate the two references d1 and d2: d1=new SimpleDate(11, 24, 2009); d2=new SimpleDate(10, 28, 2010); Again the line of code: if (d1= = d2) yields true if the two addresses in memory (address d1 and address d2 are the same).
Comparing Object Data To compare object data, use the equals method Example: If st1 and st2 are Student objects, if (st1.equals( st2 )) returns true if the attributes have equal values i.e firstName, lastName, studentID e.t.c. Or in the case of the SimpleDate class : if (d1.equals(d2)) Return type Method name and argument list boolean 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; false otherwise
Comparing SimpleDate Objects Suppose that we have 4 SimpleDate objects
Comparing SimpleDate Objects if(d1==d3) evaluates to true because the two objects have the same address (point to the same memory location). if (d1==d2) evaluates to false. if (d1.equals(d2)) evaluates true because the attributes of d1 and d2 have the same values. if (d1.equals(d4)) evaluates to false.
The equals method The method equals belongs to a library class called Object. Every program that we write is an extension of the library class Object. Therefore it inherits (it gets to use without creating an object to invoke them) all the methods of library class Object.
Modifying the equals method We can apply our own equals method in a class (usually the template class). Equals is a method that belongs to Object pre defined class (library class). All java objects that we create are also part of the Object pre defined class (even our template class objects). This give us the right to use the equals method of the Object class. We can modify the equals method in our template class to provide our own definition of what constitutes equality between two objects of this class. This is called “method overriding”
Modifying equals In our template class we introduce the method: public boolean equals(Object_Type o) where Object_Type is the name of the class that the object belongs to (template class). Notice that executing this method returns true or false (a boolean). Inside the method set up the conditions for equality: i.e. It could be that we define two objects of People class (as an example) as being equal as long as the current IDs are the same (regardless of the values of the other attributes ). i.e if(this.personID()==o.getpersonID()) return true;
Comparing Strings compareTo Strings are objects Thus, to compare two Strings, use the equals method Example: s1 and s2 are Strings s1.equals( s2 ) returns true only if each character in s1 matches the corresponding character in s2 Two other methods of the String class also can be used for comparing Strings: equalsIgnoreCase compareTo
The equalsIgnoreCase Method Return type Method name and argument list boolean 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. Example: String s1 = "Exit", s2 = "exit"; if ( s1.equalsIgnoreCase( s2 ) ) System.exit( 0 );
The compareTo Method Return type Method name and argument list int 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. A character with a lower Unicode numeric value is considered less than a character with a higher Unicode numeric value. That is, a is less than b and A is less than a. (See Appendix C for Unicode values.) See Text Example 5.12 ComparingStrings.java
StringTokenizer Library class StringTokenizer class is part of java.util package The string tokenizer class breaks a string into tokens and returns the tokens. Tokens can be defined according to delimiter. Delimiters are the characters that separate tokens. i.e Suppose we have the string “the day is Friday, the week is the third, the year is 2008” If we define the delimiter to be the character comma (,) then we have the following tokens: 1st token: “the day is Friday” 2nd token: “the week is the third” 3rd token: “the year is 2008”
StringTokenizer StringTokenizer Constructors: public StringTokenizer(String str) Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. Delimiter characters themselves will not be treated as tokens. Parameters:str - a string to be parsed.
StringTokenizer Another StringTokenizer constructor: public StringTokenizer(String str, String delim) Constructs a string tokenizer for the specified string. The characters in the delim argument is the delimiter for separating tokens. Delimiter characters themselves will not be treated as tokens. Parameters:str - a string to be parsed.delim - the delimiters.
StringTokenizer Methods of StringTokenizer: public boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer's string. If this method returns true, then a subsequent call to nextToken with no argument will successfully return a token. Returns:true if and only if there is at least one token in the string after the current position; false otherwise. We will use this method within an if structure as a condition to be evaluated.
StringTokenizer public String nextToken() Returns the next token from this string tokenizer.
StringTokenizer Example public class Tokenize { `public static void main(String[] args) String tokenizeit=args[0]; StringTokenizer stk=new StringTokenizer(tokenizeit, ","); int counttok=stk.countTokens():; if(stk.hasMoreTokens()) //get the first token String token=stk.nextToken(); System.out.println("The token is:"+token); } //get the second token } //actually we would need a loop to capture all the tokens the easy way!!!
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.
Equivalent Code The following statement stores the absolute value of the integer a into the integer absValue. int absValue = ( a > 0 ? a : -a ); The equivalent statements using if/else are: int absValue; if ( a > 0 ) absValue = a; else absValue = -a;
Study Guide Chapter 5 Sections 5.9, 5.10, 5.11 Study API for StringTokenizer (not covered in text)