Home Previous Next

CSC110AB::Lecture Note::Week 06
Assignments | Handouts | Resources | Email Thurman {Twitter::@compufoo Facebook::CSzero}
GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates

Overview

Assignment(s):

Code Adder.java | DoAdder.java | ForAdder.java | Xor.java | SquareNumbers.java | Elevator.java | Alfred.java


The while Statement

The while statement supports iteration (i.e. it is a repetition control statement). Iteration is the process of repeating an operation zero or more times. Repetition control statements are called loops.

The while statement repeatedly executes a simple statement or block (i.e. compound statement) until a boolean EXPR becomes false. Each loop iteration is called a cycle.

   while (EXPR)    // typically, you don't want a semicolon 
      statement;

   EXPR is the "conditional" test used to determine whether the loop 
   should continue for another cycle, and  statement  is to be repeated.
   If multiple  statements  need to be executed, then use a compound 
   statement (or block).

   EXPR is evaluated only at the beginning of a loop cycle.

   Pseudo-code for a while loop:
      
      top-of-loop
         evaluate the EXPR
         if  EXPR  is "true"     // true is a keyword
            execute statement
            go to top-of-loop
         else
            go to end-of-loop  (i.e. terminate the loop)
      end-of-loop
      statement
      ...

   //Example:  loop until  n  becomes greater than 9999
   Random r = new Random();
   int n = -1;
   while (n <= 9999)
      n = r.nextInt();

   //Example:  print out the numbers 1 through 5
   int i = 1;
   while (i <= 5) {
      System.out.print(i + "  ");
      i = i + 1;
   }
	System.out.println();
Sentinel Values

One way to terminate (end or stop) a loop is when a particular data value is entered (e.g. the user enters a -1 or an end-of-file (EOF) is encountered), a special value that is used to end the loop is called a sentinel value.

Sentinel values should be defined as manifest (symbolic) constants.

   static final int EXIT_VALUE = -1;
   int n = EXIT_VALUE + 1;

   while (n != EXIT_VALUE) {
      System.out.print("Enter a number: "); System.out.flush();
      n = SomeConsoleClass.getInt();
   }

Note: By convention, manifest constants are named using all upper-case letters, digits and underscores.

The break statement has the effect of immediately terminating the innermost enclosing loop. Example.

   while (true) {
      prompt user and read in a value
      if (value is invalid) 
         break;
      process the data value
   }
Infinite Loops

When you use a loop in a program, it is important to make sure that the condition used to control the loop will eventually become false, so that the loop can end. A loop that never finishes is called an infinite loop.

To stop an infinite loop, a special command sequence must be typed on the keyboard to interrupt the program and forcibly cause it to quit. This command differs from machine to machine.

Sometimes infinite loops are used by design; therefore, existenance of an infinite loop does not necessarily imply a program defect. For example, a web server program uses an infinite loop.

   //Example:  infinite loops that do nothing 
   while (true) 
      ;

   int i = 99;
   while (i != 0) ;  //null statement executed

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


The do-while Statement

The do while statement supports iteration (i.e. it is a repetition control statement). Iteration is the process of repeating an operation.

The do while statement repeatedly executes a simple statement or block (i.e. compound statement) until a conditional EXPR becomes false. Each loop iteration is called a cycle.

The syntax for a do-while statement.

   do 
      statement;
   while (EXPR);  //semicolon must follow the while statement

   EXPR is the "conditional" test used to determine whether the loop 
   should continue for another cycle, and  statement  is to be repeated.
   If multiple  statements  need to be executed, then use a compound 
   statement (or block).  A compound statement is almost always used.

   The EXPR must evaluate to a boolean value.

   EXPR is evaluated only at the end of a loop cycle.  

   Pseudo-code for a do-while loop:
      
      top-of-loop
         execute statement
         evaluate the EXPR
         if  EXPR  is  true      // true is a keyword of the language
            go to top-of-loop
         else
            go to end-of-loop  (i.e. terminate the loop)
      end-of-loop
      statement
      ...

   //Example:  print out the numbers 1 through 3
   int i = 1;
   do {
      System.out.println(i + "  ");
      i = i + 1;
   } while (i <= 3);


   Could the previous loop be rewritten:

      int i = 1;
      do System.out.println(i++ + "  "); while (i <= 3);

   How about:
      int i = 1;
      do System.out.println(i + "  "); while(i++ <= 3);

When you know for sure that a loop must cycle at least once, then a do-while is a good loop construct to use. Example.

   set item counter to 0
   do {
      prompt user for data
      get data from user
      if (data equals sentinel value)
         break;
      if (data is junk)
         continue;  //get more data from the user
      process the data
      increment the item counter
   } while (1);
   print the item counter
Comment on Style

The do-while can be difficult to read; therefore, to help it "stick" out, I suggest the following.

Review DoAdder.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


The for Statement

The for statement supports iteration (i.e. it is a repetition control statement). Iteration is the process of repeating an operation.

The for statement repeatedly executes a simple statement or block (i.e. compound statement) until a conditional EXPR becomes false. Each loop iteration is called a cycle.

Syntax for the for statement.

   for ([initialization-step]; [conditional-step]; [increment-step])
      statement;

   The optional "initialization-step" is executed once before the loop 
   is ever executed (and before the "conditional-step" is evaluated
   for the first time).

   The optional "conditional-step" is an EXPR that is evaluated at
   the top of the loop.  If it is true, then the body of the
   for  statement is executed; otherwise, flow control jumps to
   the first executable statement after the  for  loop body.  If
   no conditional-step is specified, then  it is taken as
   permanently true.

   After the body of a  for  loop has been executed, the optional
   "increment-step" is executed.

   After the increment-step is executed; the conditional-step
   is re-evaluated.

   Example:

      //print the numbers 1 through 3

      int i;
      for (i = 1; i <= 3; i = i + 1)
         System.out.println(i);

If the body of the for contains multiple statements, then a compound statement is needed.

All three steps for a for loop are EXPRs. Most commonly, the initialization-step and the increment-step are assignments or functions calls, and the conditional-step is a relational EXPR.

The for is frequently used when there are simple initialization and increment steps because it keeps the loop control statements close together and visible at the top of the loop.

The initialization and increment steps often take advantage of the sequence operator. Example.

   for (i = 0, j = 99; i < n; i = i + 1, j = j - 1)
      do_something;
Review Elevator.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


The break Statement

The break statement is a jump control statement that is used inside of repetition control statements and the switch selection control statement.

The break statement causes an immediate exit from the innermost enclosing switch or loop statement.

The break statement allows a loop to be exited from some point other than at the top or bottom of the loop.

Structured programming purist are not overly fond of the break statement.

   int foo = 100;
   while (true) {
      ...
      if (0 == foo)
         break;  // jump to statement A
      ...
   }
   /*A*/ foo = 100;

You must be careful when you use the break.

   while (...) {
      ...
      if (...) {
         ...
         if (...) 
            break;  // the programmer wanted to break from the
                    // body of the enclosing  if  statement,
                    // but instead the  break  will cause the
                    // flow control of the program to jump to
                    // the 1st executable statement after the
                    // body of the  while  statement, which in
                    // this example is  statement2
         ...
      }
      statement1;
   }
   statement2;

Java does support labeled break statements. Labeled break statements are useful for breaking from nested loops.

   FOO: while (true) {
      ...
      while (true) {
         ...
         break FOO;  // jumps to statement /*A*/
         ...
      }
      ...
   }

   /*A*/ some_statement;   // statement label is FOO

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


The continue Statement

The continue statement is a jump control statement that is used inside of repetition control statements.

The continue statement causes the next iteration of the enclosing loop statement to begin. In the while and do, this means that the test part is executed immediately; in the for control passes to the step-EXPR.

The continue statement is often used when the part of the loop that follows is complicated, so that reversing a test and indenting another level would nest the program too deeply.

Structured programming purist are not overly fond of the continue statement.

   while (boolean_control_EXPR) {
      ...
      if (...)
         continue;   // jump to the boolean_control_EXPR
                     // the remaining part of the loop body
                     // section  A  is skipped
      /*A*/ ...
   }

Java does have labeled continue statements.

   FOO: while (boolean_control_EXPR) {
      ...
      while (another_boolean_control_EXPR) {
         ...
         if (...)
            continue FOO;  // jump to the boolean_control_EXPR for
                           // the while statement labeled FOO
                           // sections B and C are skipped
         /*B*/ ...
      }
      /*C*/ ...
   }

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


The goto Statement

Java does have a goto statement. goto is not a keyword of the language, but it is a reserved word. The word is reserved because it may be added to Java in the future.

The goto statement is frequently found in code that is generated by other programs.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


class String

A string is a sequence of zero or more characters. String objects, once created, cannot be modified (i.e. they are immutable).

Frequently used String methods are:

It is important to remember that when you are testing two String objects for equality, then you must use the equals() method.

   String s1 = new String("hello");
   String s2 = new String();
   String s3 = new String(s1);
   String s4 = "bye";
   s4 = s1;

   if (s1 == s2)   // evaluates to false in this example
      // tests if  s1  and  s2  reference the same String object

   if (s1.equals(s2))   // evaluates to false in this example
      // tests if the content of the object referenced by  s1
      // equals the content of the object referenced by  s2

   s1.equals(s3)   // evaluates to true in this example
   s1 == s3        // evaluates to false in this example
   s1.equals(s4)   // evaluates to true in this example
   s4.equals(s1)   // evaluates to true in this example
   s1 == s4        // evaluates to true in this example

Docs.Oracle.com::String API

Additional String Related Notes

Here are some more notes concerning some of the String instance methods.

substring()
The substring() method is used to get a sub-string of an instance of a String object.
   public String substring(begin_i, end_i);

   "Hello".substring(0, 2)

      returns a String object with  He  as its content.
startsWith() and endsWith()
The startsWith() and endsWith() return true or false if the this object starts or ends with a particular String value.
   public boolean startsWith(String prefix);
   public boolean endsWith(String suffix);

   "WebAccount.java".startsWith("Web")   returns  true
   "WebAccount.java".startsWith("web")   returns  false
   "WebAccount.java".endsWith("Web")     returns  false
   "WebAccount.java".endsWith(".java")   returns  true
compareTo()
The compareTo() method is used to test String objects for equality. You use it over the equals() method when you need to determine if one string is less than or greater than another string (e.g. you are sorting strings). If compareTo() returns a value less than 0, then this string is lexicographically less than the string received as a parameter; otherwise, a 0 return from compareTo() implies the strings are equal; else, a positive return value indicates that this string is lexicographically greater than the parameter string.
   public int compareTo(String that);

   "hello".compareTo("bye")     returns positive value
   "hello".compareTo("jello")   returns negative value
   "hello".compareTo("hello")   returns zero
[review Stringer.java]

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


Home Previous Next