200 likes | 285 Views
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
E N D
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
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)
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 intdisplayHour = hour > 12 ? hour – 12 : hour;
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)
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
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
Switch Example • Example if(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
Enums • Specify a collection of values where only one may be assigned • Example the boolean data type may be an enum as well • public enummyBoolean { 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
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(inti = 0; i < allNames.length; ++i){ String name = allNames[i]; … }
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
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 compareToand 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
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
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
compareTo Example public class Complex implements Comparable { … //all necessary code comes before or later this method public intcompareTo(Complex other){ double thisMagnitude = this.Magnitude(); double otherMagnitude = other.Magnitude(); double thisAngle = this.Angle(); double otherAngle = other.Angle(); //test for greater if(thisMagnitude > otherMagnitude){ return 1; } //test for less if(thisMagnitude< otherMagnitude){ return -1; } //test for equal return thisAngle – otherAngle; } }
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 here return first.compareTo(second); } }
Dealing with booleans • Consider this variable definition • booleanisPresent = 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
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?
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
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”); }