OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
Fundamental Programming Structures in Java: Strings.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS 117 Spring 2002 Review for Exam 2 March 6, 2002 open book, 1 page of notes.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Flow of Control Part 1: Selection
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
CompSci 230 S Programming Techniques
Information and Computer Sciences University of Hawaii, Manoa
Chapter 4: Control Structures I
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Chapter 4: Control Structures I
OBJECT ORIENTED PROGRAMMING I LECTURE 8 GEORGE KOUTSOGIANNAKIS
Yanal Alahmad Java Workshop Yanal Alahmad
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
SELECTION STATEMENTS (1)
Primitive Types Vs. Reference Types, Strings, Enumerations
INPUT STATEMENTS GC 201.
Control Statement Examples
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Chapter 4: Control Structures I
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
The System.exit() Method
Control Structure Chapter 3.
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Lecture Notes – Week 2 Lecture-2
2.6 The if/else Selection Structure
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 4 PART 2 GEORGE KOUTSOGIANNAKIS
Chap 7. Advanced Control Statements in Java
Control Structure.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II
Presentation transcript:

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)