Java No W: Java Conditional Control Structure

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

Java No w

Java Conditional Control Structure


The switch Statement

Conditional Statements
Conditional statements control the sequence of statement execution, depending on the value of an expression The Java switch statement is controlled by an integer or char expression. Syntax: switch ( <integer expression> ) { case <value>: <statement list> break; case <value>: <statement list> break; . . . default: <statement list> break; } Control is transferred to the case according to the value of the control expression. The default clause is executed if the value of the control expression does not match any of the case values. Style: The statement lists should be indented. Program listing: / ************************************************************ *** * File: Switcher.java * Purpose: Program to show conditional control * with switch statements * Author: John Young * Date: May 24, 2004 *********************************************************** ****/ public class Switcher { public static void main (String [] Argv) { int Value;

A Program Using a Switch Statement


Value = 479; switch (Value % 4) { case 0: System.out.println (Value + " is divisible by 4."); break; case 2: System.out.println (Value + " is divisible by 2."); break; default: System.out.println (Value + " is an odd number."); break; } } } 479 is an odd number. Program output:

Introduction to Java Control Structures


Their Types and Descriptions
Feb 16, 2009 Ana Mills

Control Structures - Ana Mills Control structures are a dynamic part of Java and come in several types: sequences, subprograms, selection statements, and loops.

Java programs, large or small, are written to follow standard forms of organization. Although it may be possible to write a Java program following only the default form of organization, such a program would be clumsy and largely useless.

The types of organization, known as control structures, fall into five categories: sequential structures, subprogram structures, selection structures, looping structures, and asynchronous structures.

Sequences in Java

A sequence in Java is basically a list of commands that computer executes in order from beginning to end. Most small daily activities are sequential, such as cooking a meal or brushing teeth. A computer, like a human, finds sequential operations to be the simplest and as such the sequence is the default structure for Java programs:
Ads by Google

Barcodes for Java Barcoding servlet, applet, bean Supports all major 1D/2D standards www.java4less.com UP IT Training Center Enhance your IT skills with our full-time & short course programs. ittc.up.edu.ph/upittc/

Read on

public static void main(String args[]){ int var1=1; int var2=2; }


Java Variables Introduction to Java Loops Computer Programming Fundamentals

The Java Virtual Machine declares each variable and assigns each value to those variables in order without variance. This is easy for simple programs, but is limiting if the programmer wants the program to respond to different situations.

Subprograms in Java

Similar to sequential structures, subprograms essentially consist of multiple methods within the main method. If a program executes a bunch of operations in sequential order, it follows that the program will execute a bunch of methods in order. These methods can themselves have any number of methods nested within that execute sequentially; this type of structure is known as the subprogram. public static void main (String args[]){ public class Method1(){ int var1=1; public class Method2(){ ...etc. } } } The JVM follows the methods to the innermost method and executes any operations there, and if that method specifies allows for returning results, passes the result to the nearest outer method and continues computing each method until it reaches the main method again.

Obviously, this is a very intricate form of programming, since each method can contain any number of structures like loops or branch statements, and there can be multiple subprograms. Good commenting practice is encouraged for these situations!

Selections in Java

Also known as branch, conditional or decision structures, selections allow the program to execute different operations depending on events or conditions. This entails the use of the switch-case statement and the classic If-Then-Else statement. With its roots in classic mathematics, the if-then-else is used in Java to quantify simple decisions under certain conditions. If something occurs, do this; else, do something different. The simplest form the selection statement can take is just the if-then statement: if (testVar){ //Commands to execute } Note that the parameter testVar looks to see if the variable exists and does not have 'false' assigned to it; the test can be modified to run when testVar does equal 'false': if(!TestVar). The if-then-else statement can be expanded to test and execute commands for many different situations using the if-then-else statement.

Looping in Java

Loops are another essential part of modern programming languages, with no exception in Java. Their premise is simple: the computer executes some operation or group of operations until told to do otherwise or stop. The loop comes in several variations, each with their own slight variance in structure and purpose: for loops, while loops, do-while loops, and and the brand new for-each loop. While each has differences, all consist of loosely the same structure:
A loop entry, or the point where the loop begins execution A loop test, where the computer tests to see if the loop should begin, repeat, or skip to the next command in the program Iteration, or a single cycle through the loop's group of operations A termination condition, or the specified situation or event that a loop reaches when it's time to stop looping

Summary

Although there is some variance in opinion on how many types of control structures Java has, what they are and which statements are which, this article serves as an introduction to some of the main concepts of control flow in Java programs. Sequences, subprograms, selection statements, and loops are all foundational concepts commonly found in any developed Java program.
Ads by Google

Agriculture & Food Agriculture and Food Trade portal. Fresh & Reputable prducts available Agrotrade.net

Easy Structure Analysis Alfa Helix & Beta Sheet Prediction User-friendly & Integrated Graphics clcbio.com

RECKLI-Matrizen Ihr Partner fr texturierten Sichtbeton und Abformtechnik. www.reckli.net

Copyright Ana Mills. Contact the author to obtain permission for republication.

Recommend Article! Print Article

Control Structures - Ana Mills


What do you think about this article?

Top of Form

657419

15

80650

C9F0F895FB98A

NOTE: Because you are not a Suite101 member, your comment will be moderated before it is viewable.
1

Submit comment

What is 5+3?
Bottom of Form

Basic Structure and Types


Feb 15, 2009 Ana Mills

Loops - Ana Mills This article presents the basic types and structures of a Java loop. For the purpose of simplicity, only the while statement will be used.

A programming loop is a control structure that allows a programmer to execute the same instruction or group of instructions over and over until some condition is met. All loops have a basic structure to them, though there are many types:
The loop entry is the point at which the program's control enters the loop and begins executing the first instructions. The loop test at the beginning of the loop takes over the program control and determines whether the loop can begin, repeat, or skip to the commands after the loop. The iteration is a single cycle made through to loop, i.e. if the computer executes the loop 12 times the loop has 12 iterations. The termination condition is whatever is built in to the loop to cause the looping to stop. The program control exits the loop and continues exiting whatever commands come after.

Count-Controlled Loops

An obvious type of loop is the count-controlled loop, wherein the programmer explicitly states how many times he wants the loop to execute. A count-controlled loop obviously first needs some kind of counter that while increment each time the loop is executed. This is done rather simply, as shown here in this while loop: public static void main (String args[]){
Ads by Google

UP IT Training Center Enhance your IT skills with our full-time & short course programs. ittc.up.edu.ph/upittc/ C Programming C Experts are Ready to Help. Join Now for Free. www.CFanatic.com/C-Programming

int count = 1; while (count <= 5){ //Commands to be executed... count=count +1;

Read on
Java Variables Changing Cell Color w/VBA in Excel How to lay out computer code

} } Note that the incrementing line can also be written as follows: count=count++; Whatever the programmer writes in the while loop will be executed five times. If the loop test was specified like count < 5, the loop would iterate only four times. Because the count variable started out at 1, the loop needs only four more iterations to reach the terminating condition.

Event-Controlled Loops

Another type of loop is the event-controlled loop. These loops are little more picky about their terminating conditions, allowing the programmer to specify how many iterations are made based on certain events rather than on an arbitrary number. As the programmer may not know how many iterations will need to be made, event-controlled loops are very useful. Three of the most common types are:
End-of-file Loops, which receive some file as input and terminate when the loop reaches the end of the file. where the computer tries to read another line of data but finds none, a terminating condition. Sentinel-controlled Loops, which specify a certain input value as 'sentinel' and terminate when that value is entered as a parameter. For example, if a data file has a list of numbers from -100 to 100 and a loop only needs to perform calculations on the negative integers, 0 would be defined as a sentinel to prevent processing the positive integers in the file input. Flag-controlled Loops, which use a boolean variable as a flag to determine whether a terminating condition has been reached and the loop can stop processing.

SummaryLoops come in several flavors, but they all have the same basic premise: process the same commands over and over until the computer is told to stop. How the computer is told to stop determines the different types of loops, and different statements are typically used for each type, such as using the for statement for count-controlled loops. This tutorial is a gentle precursor to using those different statements, to understand the concepts behind them.
Ads by Google

USPS Shipping Integration USPS Shipping, Tracking, & Labels .NET, Java , ActiveX, Delphi, etc www.nsoftware.com

Java Declare Variable Learn How to Declare a Variable Free Java How Tos Source Code www.f5java.com/JavaDeclareVariable

Programming C and C++ Learn Basic and Advanced Concepts Free Sample Code & Downloads www.softwareandfinance.com

Copyright

Control structure includes the looping control structure and conditional or branching control structure. In a looping control structure, series of statements are repeated. In a conditional or branching control structure, a portion of the program is executed once depending on what conditions occur in the code. Loops: The purpose of loop statements is to repeat Java statements more than times. There are several kinds of loop statements in Java. for loop: for loop is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and increment/decrement. initialization: It is an expression that sets the value of the loop control variable. It executes only once. condition: This must be a boolean expression. It tests the loop control variable against a target value and hence works as a loop terminator. Increment/decrement: It is an expression that increments or decrements the loop control variable. Example: int a; for (a=0; a<=10; a++) { System.out.println("a = " +a); } while loop: in while loop the statement(s) will be executed as long as Expression evaluates to true. If there is only a single statement inside the braces, you may omit the braces. Example: class counting{ public static void main (String args[]){ int i = 0; while (i < =5){ System.out.println("count");

i = i + 1; } } } do-while loop: The do-while statement is like the while statement, except that the associated block always gets executed at least once. Syntax: do { statement (s) } while (Expression);

Example: public class MyClass { public static void main(String[] args) { int i = 0; do { System.out.println(i); i++; } while (i < 10); } } if statement: The if statement is the simple form of control flow statement. It directs the program to execute a certain section of code if and only if the test evaluates to true. That is the if statement in Java is a test of any boolean expression. Syntax: if (Expression) { statement (s) } else { statement (s) }

Example: public class MainClass { public static void main(String[] args) { int a = 3; if (a > 3) a++; else a = 3; } } Example: class IfElseexamp { public static void main(String[] args) { int testscore = 66; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }

The output will be D

The Switch Statement: The Switch Statement is an alternative to a series of else if is the switch statement. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types. The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case. Switch Statement Syntax: switch (expression) { case value_1 : statement (s); break; case value_2 : statement (s); break; . . . case value_n : statement (s); break; default: statement (s); } Example: class Switchexamp { public static void main(String[] args) { int month = 5; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break;

case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Wrong Input"); break; } } } The output will be May

Attention Necessary Alert body passed to window.alert


Top of Form

Bottom of Form

OK
Top of Form

Comparisons And Flow Control Structures


In this lesson of the Java tutorial, you will learn... 1. Understand boolean values and expressions 2. Create complex boolean expressions using AND and OR logic 3. Write flow control statements using if and if ... else structures 4. Compare objects for equality and identity 5. Write loops using while, do ... while, and for loop structures

Controlling Program Flow


Boolean-Valued Expressions
Java has a data type called boolean
possible values are true or false can be operated on with logical or bitwise operators, but cannot be treated as a 0 or 1 mathematically can be specified as a parameter type or return value for a method a boolean value will print as true or false simple comparisons, such as greater than, equal to, etc. values returned from functions complex combinations of simpler conditions branching to another section of the program under specified conditions repeating loops of the same section of code

The result of a conditional expression (such as a comparison operation) is a boolean value

Condition expressions are used for program control

Comparison Operators
This chart shows the comparison operators and the types of data they can be applied to Operator boolean == != > < >= Purpose (Operation Performed) numeric primitives and char is equal to (note the two equals signs!) is not equal to is greater than is less than is greater than or equal to Types of Data objects X X XX XX X X X

This chart shows the comparison operators and the types of data they can be applied to Operator boolean <= Purpose (Operation Performed) numeric primitives and char is less than or equal to Types of Data objects X

note that it is unwise to use == or != with floating-point data types, as they can be imprecise

Comparing Objects

The operators == and != test if two references point to exactly the same object in memory they test that the numeric values of the two references are the same The equals(Object o) method compares the contents of two objects to see if they are the same (you can override this method for your classes to perform any test you want)

Conditional Expression Examples

a = 3; b = 4; a == b will evaluate to false a != b will evaluate to true a > b will evaluate to false a < b will evaluate to true a >= b will evaluate to false a <= b will evaluate to true String s = "Hello"; String r = "Hel"; String t = r + "lo"; s == t will evaluate to false s != t will evaluate to true (they are not the same object - they are two different objects that have the same contents) s.equals(t) will evaluate to true String s = "Hello"; String t = s; s == t will evaluate to true s != t will evaluate to false (they are the same object) s.equals(t) will evaluate to true Note: Java will intern a literal String that is used more than once in your code; that is, it will use the same location for all occurrences of that String String s = "Hello"; String t = "Hello"; s == t will evaluate to true, because the String object storing "Hello" is stored only once, and both s and t reference that location s != t will evaluate to false (they are the same object) s.equals(t) will evaluate to true

Complex boolean Expressions

Java has operators for combining boolean values with AND and OR logic, and for negating a value (a NOT operation)

there are also bitwise operators for AND, OR and bitwise inversion (changing all 1 bits to 0, and vice versa) since a boolean is stored as one bit, the bitwise AND and OR operators will give the same logical result, but will be applied differently (see below) for some reason, the bitwise NOT cannot be applied to a boolean value

Logic Bitwise al && || ! logical AND logical OR logical NOT & bitwise AND

| bitwise OR ~ bitwise NOT (inversion) Effect

Examples:
Code Testing if a value falls within a range

( ( a >= 0 ) && (a <= is true if a is falls between 0 and 10; it must satisfy both 10 ) ) conditions
Testing if a value falls outside a range

is true if a falls outside the range 0 to 10; it may be either below or above that range ( !( ( a >= 0 ) && (a <= inverts the test for a between 0 and 10; so a must be outside the 10) ) ) range instead of inside it The && and || operations are called short-circuiting, because if the first condition determines the final outcome, the second condition is not evaluated ( ( a < 0 ) || (a > 10 ) )
to force both conditions to be evaluated, use & and | for AND and OR, respectively

Example: to test if a reference is null before calling a boolean valued method on it String s = request.getParameter("shipovernite"); if (s != null && s.equalsIgnoreCase("YES")) { . . . } equalsIgnoreCase will only be called if the reference is not null

Simple Branching
if Statement
Syntax

The result of a conditional expression can be used to control program flow

if (condition) statement;

Syntax

or

if (condition) { zero to many statements; }


causes "one thing" to occur when a specified condition is met the one thing may be a single statement or a block of statements in curly braces the remainder of the code (following the if and the statement or block it owns) is then executed regardless of the result of the condition.

The conditional expression is placed within parentheses The following flowchart shows the path of execution:

if Statement Examples
Absolute Value If we needed the absolute value of a number (a number that would always be positive):

Code Sample: Java-Control/Demos/If1.java


public class If1 { public static void main(String[] args) {

int a = 5; System.out.println("original if ( a < 0 ) { a = -a; } System.out.println("absolute a = -10; System.out.println("original if ( a < 0 ) { a = -a; } System.out.println("absolute } } Random Selection

number is: " + a); value is: " + a); number is: " + a); value is: " + a);

Task: write a brief program which generates a random number between 0 and 1. Print out that the value is in the low, middle, or high third of that range (Math.random() will produce a double value from 0.0 up to but not including 1.0).
although it is a bit inefficient, just do three separate tests: (note that Math.random() will produce a number greater than or equal to 0.0 and less than 1.0)

Code Sample: Java-Control/Demos/If2.java


public class If2 { public static void main(String[] args) { double d = Math.random(); System.out.print("The number " + d); if (d < 1.0/3.0) System.out.println(" is low"); if (d >= 1.0/3.0 && d < 2.0/3.0) System.out.println(" is middle"); if (d >= 2.0/3.0) System.out.println(" is high"); } }

Exercise: Game01: A Guessing Game


Duration: 15 to 20 minutes.

Write a program called Game that will ask the user to guess a number, and compare their guess to a stored integer value between 1 and 100.
1. Use a property called answer to store the expected answer 2. For now, just hard-code the stored value, we will create a random value later (your code will be easier to debug if you know the correct answer) 3. Create a method called play() that holds the logic for the guessing 4. Create a main method, have it create a new instance of Game and call play() 5. Use the KeyboardReader class to ask for a number between 1 and 100, read the result, and tell the user if they are too low, correct, or too high Where is the solution?

Exercise: Payroll-Control01: Modified Payroll


Duration: 15 to 20 minutes. 1. Modify your payroll program to check that the pay rate and department values the user enters is greater than or equal to 0 2. The Employee class should protect itself from bad data, so modify setPayRate and setDept to check the incoming data (and ignore it if it is less than 0) 3. Test your program to see what happens with negative input values 4. The code using Employee should avoiding sending it bad data, so also change main to check for pay rate and department values (print an error message for any negative entry, ane replace it with a value of 0 - later we will find a way to ask the user for a new value instead) Where is the solution?

Two Mutually Exclusive Branches


Syntax

if ... else statement

if (condition) statement; or block else statement; or block


does "one thing" if a condition is true, and a different thing if it is false it is never the case that both things are done the "one thing" may be a single statement or a block of statements in curly braces a statement executed in a branch may be any statement, including another if or if ... else statement.

This program tells you that you are a winner on average once out of every four tries:

Code Sample: Java-Control/Demos/IfElse1.java

public class IfElse1 { public static void main(String[] args) { double d = Math.random(); if (d < .25) System.out.println("You are a winner!"); else System.out.println("Sorry, try again!"); } }

Nested if ... else Statements - Comparing a Number of Mutually Exclusive Options


Nested if ... else statements
the else clause can contain any type of statement, including another if or if ... else you can test individual values or ranges of values once an if condition is true, the rest of the branches will be skipped you could also use a sequence of if statements without the else clauses (but this doesn't by itself force the branches to be mutually exclusive)

Here is the low/middle/high example rewritten using if ... else

Code Sample: Java-Control/Demos/IfElse2.java


public class IfElse2 { public static void main(String[] args) { double d = Math.random(); System.out.print("The number " + d); if (d < 1.0/3.0) System.out.println(" is low"); else if (d < 2.0/3.0) System.out.println(" is middle"); else System.out.println(" is high"); } }

note that we only need one test for the middle value - if we reach that point in the code, d must be greater than 1.0/3.0 similarly, we do not any test at all for the high third the original version worked because there was no chance that more than one message would print - that approach is slightly less efficient because all three tests will always be made, where in the if ... else version comparing stops once a match has been made.

Exercise: Game02: A Revised Guessing Game


Duration: 15 to 20 minutes. 1. Revise your number guessing program to use if . . . else logic (you can test for too low and too high, and put the message for correct in the final else branch) 2. Once you have done that, here is a way to generate a random answer between 1 and 100: 1. at the top:

import java.util.*;
2. then, in a constructor, use:

3. Random r = new Random(); answer = r.nextInt(100) + 1;


4. the nextInt(int n) method generates a number greater than or equal to 0 and less than n, so r.nextInt(100) would range from 0 through 99; we need to add 1 to raise both ends of the range 5. you might want to print the expected correct answer to aid debugging

Note that until we cover looping, there will be no way to truly "play" the game, since we have no way to preserve the value between runs
Where is the solution?

Comparing a Number of Mutually Exclusive Options - The switch Statement

switch statement
a switch expression (usually a variable) is compared against a number of possible values used when the options are each a single, constant, value that is exactly comparable (called a case) the switch expression must be a byte, char, short, or int cases may only be byte, char, short, or int values, in addition, their magnitude must be within the range of the switch expression data type cannot be used with floating-point datatypes or long cannot compare an option that is a range of values, unless it can be stated as a list of possible values, each treated as a separate case cases are listed under the switch control statement, within curly braces, using the case keyword once a match is found, all executable statements below that point are executed, including those belonging to later cases - this allows stacking of multiple cases that use the same code the break; statement is used to jump out of the switch block, thus skipping executable steps that are not desired the default case keyword catches all cases not matched above note that, technically speaking, the cases are labeled lines; the switch jumps to the first label whose value matches the switch expression

Syntax

Usage switch ( expression ) { case constant1: statements; break; case constant2: statements; break; . . . case constant3: case constant4MeansTheSameAs3: statements; break; . . . [default: statements;] }

switch Statement Examples

Example - code that tests a character variable against several possible cases

Code Sample: Java-Control/Demos/Switch1.java

import util.KeyboardReader; public class Switch1 { public static void main(String[] args) { int c = 'X'; c = KeyboardReader.getPromptedChar("Enter a letter a - d: "); switch (c) { case 'a': case 'A': System.out.println("A is for Aardvark"); break; case 'b': case 'B': System.out.println("B is for Baboon"); break; case 'c': case 'C': System.out.println("C is for Cat"); break; case 'd': case 'D': System.out.println("D is for Dog"); break; default: System.out.println("Not a valid choice"); } } } Points to note:
stacking of cases for uppercase and lowercase letters allows both possibilities break; statements used to separate code for different cases default: clause used to catch all other cases not explicitly handled

Another example - taking advantage of the "fall-though" behavior without a break statement

Code Sample: Java-Control/Demos/Christmas.java


import util.KeyboardReader; public class Christmas { public static void main(String[] args) { int day = KeyboardReader.getPromptedInt("What day of Christmas? "); System.out.println( "On the " + day + " day of Christmas, my true love gave to me:"); switch (day) { case 12: System.out.println("Twelve drummers drumming,"); case 11: System.out.println("Eleven pipers piping,"); case 10: System.out.println("Ten lords a-leaping,"); case 9: System.out.println("Nine ladies dancing,"); case 8: System.out.println("Eight maids a-milking,"); case 7: System.out.println("Seven swans a-swimming,"); case 6: System.out.println("Six geese a-laying,");

case case case case case } } }

5: 4: 3: 2: 1:

System.out.println("Five golden rings,"); System.out.println("Four calling birds,"); System.out.println("Three French hens,"); System.out.println("Two turtle doves, and a "); System.out.println("Partridge in a pear tree!");

Exercise: Game03: Multiple Levels


Duration: 15 to 30 minutes.

What if we want to offer gamers multiple levels of difficulty in our game? We could make the range multiplier a property of the Game class, and set a value into it with a constructor, after asking the user what level they'd like to play.
1. Add a range property to the Game class (an int) 2. Add a new constuctor that accepts a level parameter; use a char 3. In the new constructor, create another new KeyboardReader (we will come up with a better solution later, where both main and play can share one KeyboardReader) 4. use a switch to process the incoming level: uppercase or lowercase B means Beginner, set the range to 10 I means Intermediate, set the range to 100 A means Advanced, set the range to 1000 any other value results in beginner - after all, if they can't answer a simple question correctly, how could we expect them to handle a higher level game? you could put the default option stacked with the 'B' cases to accomplish this better yet, make it the first of that group, so that you can print an error message and then fall through to the 'B' logic

5. Modify the default constructor to call this new constructor, passing 'I' for intermediate 6. In the main method, ask the user for the level and call the new constructor with their response 7. Use range as the parameter when you call the Random object's nextInt method Where is the solution?

Comparing Objects

When comparing two objects, the == operator compares the references, to see if they are the same object (i.e., occupying the same spot in memory)
and != tests to see if they are two different objects (even if they happen to have the same internal values)

The Object class defines an equals(Object) method intended to compare the contents of the objects
the code written in the Object class simply compares the references using == this method is overridden for most API classes to do an appropriate comparison for example, with String objects, the method compares the actual characters up to the end of the string for classes you create, you would override this method to do whatever comparisons you deem appropriate

Code Sample: Java-Control/Demos/Rectangle.java


public class Rectangle { private int height; private int width;

public Rectangle(int height, int width) { this.height = height; this.width = width; } public boolean equals(Object other) { if (other instanceof Rectangle) { Rectangle otherRect = (Rectangle) other; return this.height == otherRect.height && this.width == otherRect.width; } else return false; } }
Code Explanation

The equals method compares another object to this object. This example is necessarily somewhat complicated. It involves a few concepts we haven't covered yet, including inheritance. Because the equals method inherited from Object takes a parameter which is an Object, we need to keep that that type for the parameter (technically, we don't need to do it by the rules of Java inheritance, but because other tools in the API are coded to pass an Object to this method). But, that means that someone could call this method and pass in something else, like a String. So, the first thing we need to do is test that the parameter was actually a Rectangle. If so, we can work with it - if not, there is no way it could be equal, so we return false. We will cover instanceof later, but, for now, we can assume it does what it implies - test that the object we received was an instance of Rectangle. Even after that test, in order to treat it as a Rectangle, we need to do a typecast to explicitly store it into a Rectangle variable (and again, we will cover object typecasting later). Once we have it in a Rectangle variable, we can check its height and width properties.

As an aside, note that private data in one instance of a class is visible to other instances of the same class - it is only other classes that cannot see the private elements.

Code Sample: Java-Control/Demos/ObjectEquivalenceIdentity.java


class ObjectEquivalenceIdentity { public static void main(String[] args) { Rectangle r1 = new Rectangle(10, 20); Rectangle r2 = new Rectangle(10, 20); if (r1 == r2) System.out.println("Same object"); else System.out.println("Different objects"); if (r1.equals(r2)) System.out.println("Equal"); else System.out.println("Not equal"); } }
Code Explanation

Since all the important work is done in Rectangle, all we need to do here is instantiate two and compare them using both == and the equals method to see the differing results. The output should be: Different objects Equal

Testing Strings for Equivalence

Example - write a brief program which has a word stored as a string of text. Print a message asking for a word, read it, then test if they are the same or not.
you can preset the message assuming that they are incorrect, then change it if they are correct

Code Sample: Java-Control/Demos/StringEquals.java


import util.KeyboardReader; public class StringEquals { public static void main(String[] args) { String s = "Hello"; String t = KeyboardReader.getPromptedString("Enter a string: "); String message = "That is incorrect"; if (s.equals(t)) message = "That is correct"; System.out.println(message); } }
try this, then change equals(t) to equalsIgnoreCase(t)

Conditional Expression

Syntax

Java uses the same conditional expression as C and C++

condition ? expressionIfTrue : expressionIfFalse This performs a conditional test in an expression, resulting in the first value if the condition is true, the second if the condition is false Note: due to operator precedence issues, it is often best to enclose the entire expression in parentheses Example

Code Sample: Java-Control/Demos/Conditional.java

public class Conditional { public static void main(String[] args) { int i = -6; String s; s = "i is " + ((i >= 0) ? "positive" : "negative"); System.out.println(s); } } Note that the parentheses around the test are not necessary by the operator precedence rules, but may help make the code clearer The parentheses around the entire conditional expression are necessary; without them, precedence rules would concatenate the boolean result onto the initial string, and then the ? operator would be flagged as an error, since the value to its left would not be a boolean.

while and do . . . while Loops


Syntax

Again, the loops in Java are pretty much the same as in C - with the exception that the conditional expressions must evaluate to boolean values while loops while (condition) statement; or
Syntax

while (condition){ block of statements }

the loop continues as long as the expression evaluates to true the condition is evaluated before the start of each pass it is possible that the body of the loop never executes at all (if the condition is false the first time)

Syntax

do ... while loops do statement; while (condition); or


Syntax

do { block of statements } while (condition);

the condition is evaluated after the end of each pass the body of the loop will always execute at least once, even if the condition is false the first time

for Loops
A for loop uses a counter to progress through a series of values
a value is initialized, tested each time through, and then modified (usually incremented) at the end of each pass, before it is tested again the for loop does not do anything that cannot be done with a while loop, but it puts everything that controls the looping at the top of the block

Syntax

for (initialize; condition; change) statement; or


Syntax

for (initialize; condition; change) { block of statements } for loops often use a variable with block-level scope (existing only for the duration of the loop), created in the control portion of the loop int j; for (j = 0; j < 12; j++ ) System.out.print("j = " + j); for (int j = 0; j < 12; j++ ) System.out.print("j = " + j); A for loop may use multiple control variables by using the sequence operator, the comma ( , ) for (int j = 0, k = 12; j <= 12; j++, k-- ) System.out.println(j + " " + k); Note: if you use a block-scope variable (such as above) for the first counter, the additional ones will be block scope as well, and also will be the same type of data - i.e., the variable k above also exists only for the duration of the block. There is no way to declare two counters of different types at block-level scope..

ForEach Loops

Java 5 introduced a new type of loop, the for-each loop. When you have an array or collection class instance, you can loop through it using a simplified syntax
Syntax

for (type variable : arrayOrCollection) { body of loop } The looping variable is not a counter - it will contain each element of the array or collection in turn (the actual value, not an index to it, so its type should be the same as the type of items in the array or collection). You can read the : character as if it was the word "from". We will cover this type of loop in more depth in the Arrays section. For some reason, the looping variable must be declared within the parentheses controlling the loop - you cannot use a preexisting variable.

Code Sample: Java-Control/Demos/Loops1.java


public class Loops1 { public static void main(String[] args) { int i = 1; System.out.println("While loop:"); while (i <= 512) { System.out.println("i is " + i); i *= 2; } System.out.println("i is now " + i); System.out.println("Do while loop:"); do { i = i - 300; System.out.println("i is now " + i); } while (i > 0); System.out.println("For loop:"); for (i = 0; i < 12; i++) System.out.print(" " + i); System.out.println(); System.out.println("For loop that declares a counter:"); for (int j = 0; j < 12; j++) System.out.print(" " + j); System.out.println(); System.out.println("ForEach loop:"); String[] names = { "Jane", "John", "Bill" }; for (String oneName : names) System.out.println(oneName.toUpperCase()); }

Exercise: Payroll-Control02: Payroll With a Loop


Duration: 20 to 40 minutes. 1. Revise your payroll program to use only one Employee variable 2. Use a loop to repeatedly create a new instance to store in it, populate it from the keyboard and display it on the screen (you can ask after each one if the user wants to enter another, or just use a loop that has a fixed number of iterations) 3. Also, change the logic for reading the salary and department values from the keyboard to use do . . . while loops that will continue to loop as long as the user enters invalid values Where is the solution?

Exercise: Game04: Guessing Game with a Loop


Duration: 10 to 20 minutes.

(Optional - if time permits)


1. Revise the number guessing program to force the user to guess until they are correct (loop-wise, to keep guessing as long as they are incorrect). 2. Then add more logic to ask if they want to play again, read a Y or N as their answer, and loop as long as they enter a Y Where is the solution?

Additional Loop Control: break and continue


Breaking Out of a Loop

The break statement will end a loop early


execution jumps to the first statement following the loop the following example prints random digits until a random value is less than 0.1

Code Sample: Java-Control/Demos/Break.java


public class Break { public static void main(String[] args) { for ( ; ; ) { // creates an infinite loop // no initialization, no test, no increment double x = Math.random(); if (x < 0.1) break; System.out.print((int) (x * 10) + " "); } System.out.println("Done!"); } }
Code Explanation

This code loops, generating and printing a random number for each iteration. If the number is less than 0.1, we break out before printing it.

Code Sample: Java-Control/Demos/BreakNot.java


Code Explanation

This code avoids the break, by creating and testing the random number in the control part of the loop. As part of the iteration condition, if the number is less than 0.1, the loop simply ends "normally".

Continuing a Loop

If you need to stop the current iteration of the loop, but continue the looping process, you can use the continue statement
normally based on a condition of some sort execution skips to the end of this pass, but continues looping it is usually a better practice to reverse the logic of the condition, and place the remainder of the loop under control of the if statement

Example - a program to enter 10 non-negative numbers

Code Sample: Java-Control/Demos/Continuer.java


import util.*; public class Continuer { public static void main(String[] args) throws IOException { int count = 0; do { int num = KeyboardReader.getPromptedInt("Enter an integer: "); if (num < 0) continue; count++; System.out.println("Number " + count + " is " + num); } while (count < 10); System.out.println("Thank you"); } /* // a better way public static void main(String[] args) throws IOException { int count = 0; do { int num = KeyboardReader.getPromptedInt("Enter an integer: "); if (num >= 0) { count++; System.out.println("Number " + count + " is " + num); } } while (count < 10); System.out.println("Thank you"); } */

} A better way to handle the loop is shown in the commented out version of main - try removing the comment marks and commenting out the original method But, continue is easier to use in nested loops, because you can label the level that will be continued

break and continue in Nested Loops

In normal usage, break and continue only affect the current loop; a break in a nested loop would break out of the inner loop, not the outer one But, you can label a loop, and break or continue at that level
a label is a unique identifier followed by a colon character

Try the following example as is, then reverse the commenting on the break lines

Code Sample: Java-Control/Demos/BreakOuter.java


public class BreakOuter { public static void main(String[] args) { outer: for (int r = 0; r < 10; r++) { for (int c = 0; c < 20; c++) { double x = Math.random(); //if (x < 0.02) break; if (x < 0.02) break outer; System.out.print((int) (x * 10) + " "); } System.out.println(); } System.out.println("Done!"); } }

Classpath, Code Libraries, and Jar files


By now, you may have noticed that every demo and solution folder contains its own copy of util and KeyboardReader. Not only is it inefficient, but it means that we would have to locate and update each copy if we wanted to change KeyboardReader. A better solution would be to have one master copy somewhere that all of our exercises could access.

Using CLASSPATH

Java has a CLASSPATH concept that enables you to specify multiple locations for .class files, at both compile-time and runtime.
by default, Java uses rt.jar in the current Java installation's lib directory, and assumes that the classpath is the current directory (the working directory in an IDE) if you create a classpath, the default one disappears, so any classpath that you create must include the current directory using a period (.) character

To use an external library, you would need to create a classpath in one of two ways:

1. you can create a system or user environment variable, with multiple directories and/or .jar files, separated by the same delimiter used by your PATH (a semicolon in Windows) 2. you could use the -classpath option in java and javac (-cp is a shorthand version of that)

Here is an example of a pair of commands to compile and run using an external library stored in a jar file. Note that we need the jar file at both compile-time and runtime. The -cp option in both commands replaces the system classpath with one specifically for that command. javac -cp c:\Webucator\Java102\ClassFiles\utilities.jar;. *.java java -cp c:\Webucator\Java102\ClassFiles\utilities.jar;. Payroll Many Integrated Developments (IDEs) have a means to specify project properties; usually an item like "Build Path" will have options to specify external jar files (as well as choose from various libraries supplied with the environment).

Creating a jar File (a Library)


If you wish to create your own library of useful classes, you can bundle one or more classes and/or directories of classes in a jar file
you can also add other resources such as image files the root level of the file structure should match the root of the package structure, for example, to put KeyboardReader in a jar file, we would want to start at the directory where util is visible, and jar that

A jar file contains files in a zipped directory structure

The following command will create a jar file called utilities.jar for all files in the util package (just KeyboardReader, in this case) jar -cvf utilities.jar util\*.class
the options are create, verbose, and use a list of files supplied at the end of the command

Exercise: Creating and Using an External Library


Duration: 5 to 10 minutes. 1. Run the command shown above to create utilities.jar 2. Move utilities.jar to the ClassFiles directory in your filesystem 3. If you remove the util directory from Payroll-Control01, you will not be able to compile or run Payroll as we have been doing 4. But, you should be able to compile and run by specifiying a classpath option as in the commands shown above 5. You can also temporarily modify the classpath for the duration of your command prompt window as follows (note that you may need to modify the line below to match your setup):

set CLASSPATH=%CLASSPATH %;c:\Webucator\Java102\ClassFiles\utilities.jar

Compiling to a Different Directory


You can supply a destination directory to the Java compiler, in order to keep your source and compiled files separate:

Syntax

javac -d destination FileList The destination directory can be a relative path from the current directory, or an absolute path. It must already exist, but an subdirectories necessary for package structures will be created.

Comparisons And Flow Control Structures Conclusion


In this section we have learned about boolean-valued expressions, and used them to control branches and loops. We also learned how to create and use jar file libraries.
To continue to learn Java go to the top of this page and click on the next lesson in this Java Tutorial's Table of Contents. Last updated on 2009-02-26

All material in this Comparisons And Flow Control Structures is copyright 2011 Webucator. The purpose of this website is to help you learn Java on your own and use of the website implies your agreement to our Java Tutorial Terms of Service.

Use of http://www.learn-java-tutorial.com (Website) implies agreement to the following:


Copyright Information
All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified. None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website


This content may not be printed or saved. It is for online use only.

Linking to Website
frame

You may link to any of the pages on Website; however, you may not include the content in a or iframe without written permission from Webucator, Inc.

Warranties
Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or

receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm

You might also like