Download presentation
Presentation is loading. Please wait.
1
If-statements & Indefinite Loops
CSE 115 Spring 2006 April 24, 26, &
2
Selection Choice in a program.
We’ve seen polymorphism already as a mechanism for a way for a program to behave differently under different conditions. There is another construct for selection built into Java: if-statements.
3
If-statements Syntax if (booleanExpression) {
//code executed if boolean //Expression is true }
4
If-else statements if (booleanExpression) {
//code executed if boolean //Expression is true } else { //code executed if boolean //Expression is false
5
If-else statements (more than two choices)
if (booleanExpression1) { //code executed if boolean //Expression1 is true } else if (booleanExpression2) { //Expression2 is true else { //code executed if neither boolean //Expression1 or booleanExpression2 is //true
6
Loops (Iteration/Repetition)
The ability to do a task repeatedly. The functionality of repetition is most often implemented in programming languages using loops.
7
Indefinite Loop There are two types of indefinite loops built into Java, the while-loop and the do-while-loop. An indefinite loop is normally used when you do not know how many times you want a specific task to be performed.
8
Entry vs. Exit Test Loop A “while-loop” is also characterized as an entry-test loop (like the for-loop). That is, a condition about whether the loop should continue is tested before actually doing the work of the loop. A “do-while-loop” is an exit-test loop. That is, the work of the loop is done before the condition is tested about whether the loop should continue.
9
Syntax of while-loop { //loop body }
while (booleanExpression) { //loop body } Essentially, keep looping until the condition is false.
10
Syntax of do-while-loop
//loop body } while (booleanExpression); Essentially, do it once and then keep looping until the condition is false.
11
The equals method The == operator does not always give us the desired results when comparing two objects (non-primitives). We need to use the equals method to obtain information about object equality. All classes inherit this method from java.lang.Object, but need to override it to perform as appropriate.
12
The toString method Another method inherited from java.lang.Object that should be overridden to perform appropriately for each object. This method gives a String representation of an object that can be printed out to the console using System.out.println statements.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.