20
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo- Cordero, MS

COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Embed Size (px)

Citation preview

Page 1: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

COP-3330: Object Oriented Programming

Flow ControlMay 16, 2012

Eng. Hector M Lugo-Cordero, MS

Page 2: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

What are flow control instructions?

• A program’s normal execution is sequential, i.e. instructions are executed line by line

• Flow control instructions simply allow to change this• Main difference between C/C++’s and Java’s flow

control– C/C++ utilizes numbers to represent TRUE/FALSE, anything

different than 0 is a TRUE, and the value 0 is FALSE– Java has a boolean data type which may assume the values

true or false. Assigning a number to a boolean variable is an error

Page 3: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Conditions

• Equal: == a == b• Not Equal: != a != b• Greater: > a > b• Less: < a < b• Greater or Equal: >= a >= b• Less or Equal: <= a <= b • Not: ! !(a == 0)

!(b > 2)

Page 4: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Conditional Assignment

• Allows assigning a value if a condition is met, another otherwise

• Syntax:– <variable> = <condition> ? <value_if_true> : <value_if_false>;

• E.g. consider a clock that is stored in 24 hrs format, but has the option of working with AM/PM format

int displayHour = hour > 12 ? hour – 12 : hour;

Page 5: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Multiple Conditions

• Multiple conditions must be met (AND)x == y && x > 0• At least one condition must be met (OR)x == y || x > y• Complex conditions may be not as well!(x == y || x > y)

Page 6: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Conditionals

• if(condition){…code…}• if(condition1){…} else if(condition2){} else{}– The else if are optional and may include as many

as you need– else is optional unlike C/C++ where is required

after using the else if• Omiting the {} will only execute the next

instruction after the if

Page 7: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Switches

• Switches are an alternative for having multiple conditions (equality)

• The condition of a switch is a number or enum• Java 1.7 aka Java 7 allows usage of String

variables within a switch as well• Switches do not accept boolean expressions• Each case in a switch is terminated by a break, if

no break is added then subsequent cases may be executed as well

Page 8: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Switch Example• Exampleif(x == 0) ….else if(x == 1) ……else• May be written as:switch(x){

case 0:break;

case 1:break;

….default:

}• Important: DO NOT FORGET THE BREAK

Page 9: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Enums

• Specify a collection of values where only one may be assigned

• Example the boolean data type may be an enum as well• public enum myBoolean {

FALSE,TRUE;

};• Enums work like this in C/C++, but Java further extends

to having methods for the enums as well– So an enum is also an Object

Page 10: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Loops

• Follow the same convention as in C/C++– for(init_control; condition ;increment){}– while(condition){}– do{}while(condition);

• There is also a foreach which may be used to read sequentially a collection (this will make more sense later)– for(String name : allNames){…}– Equivalent to having a

• for(int i = 0; i < allNames.length; ++i){String name = allNames[i];…

}

Page 11: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Comparing Strings

• An error would be to compare strings with == or !=

• Test for equality .equals– if(lastName.equals(otherLastName))

• Test for equality ignoring case .equalsIgnoreCase– if(user.equalsIgnoreCase(storedUser))

• Both methods (functions) return a boolean

Page 12: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Comparing Objects• As with Strings (which are object in Java as well) == and != have

different sense – == tests to see if the location where two variables are stored are the

same– != tests to see if the location where two variables are stored are not

the same• So how do we test for their values?

– The method compareTo and compare– compareTo is applied to an object– compare is static, hence it receives two parameters

• We shall cover more on this

• Compares return a > 0 number if the first operand is greater, a < 0 number if it is less, and 0 if they are equal

Page 13: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Conditions for Comparing Objects

• A class should implement Comparable, what implements means will be discussed later in course

• Otherwise it may implement Comparator to compare two objects of another class, will cover this as well later

Page 14: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

So what is an object then?

• From Java’s point of view is another data type• To avoid too many abstractions, an object is an area in

memory just like a data type, but it holds a collection of values

• Is this a struct as in C?struct Complex{

double real;double imag;

};• In a sense yes, but no since Java objects are classes and as we

shall see, there are more things that can be done with classes

Page 15: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

compareTo Examplepublic class Complex implements Comparable {

… //all necessary code comes before or later this methodpublic int compareTo(Complex other){

double thisMagnitude = this.Magnitude();double otherMagnitude = other.Magnitude();double thisAngle = this.Angle();double otherAngle = other.Angle();//test for greaterif(thisMagnitude > otherMagnitude){return 1;}//test for lessif(thisMagnitude < otherMagnitude){return -1;}//test for equalreturn thisAngle – otherAngle;

}}

Page 16: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

compare Example

public class ComplexComparator implements Comparator{

public static int compare(Complex first, Complex second){

//may used the already defined method//or redefine the method herereturn first.compareTo(second);

}}

Page 17: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Dealing with booleans• Consider this variable definition

– boolean isPresent = true;• A common non-required way of testing with such values is• For true

– if(isPresent == true) or if(isPresent != false)– Correct: if(isPresent)

• For false – if(isPresent == false) or if(isPresent != true)– Correct: if(!isPresent)

• In a function that checks if a list is empty one could return:– return list.size() == 0– return list.isEmpty()– No need for return true or return false, such may be used under different

situations

Page 18: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Exceptions

• Exceptions are special cases that normally should not occur on a program (hence its name exception), and must be handled before continuing execution

• Example:– double average = sum / count;– What could be a problem with this line?– How do we fix it? If? while? Something better?

Page 19: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Exception Handling

• Each potential problem code is enclosed with a try keyword

• An error or exceptional case may be catch with the catch keyword

• Exceptions are also in C++ and are enclosed by a try{} catch(Exception e){} blocks

• Java also contains another keyword named finally where the code inside is executed always no matter if there is a exception or not, or even if there is a return inside

Page 20: COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS

Exceptions by Example

try{double average = sum / count;return average;

}catch(Exception e){

System.err.println(e.getMessage());return Double.NaN;

}finally{

System.out.println(“Average Function Exited”);}