Home Previous Next

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

Overview

Assignment(s):

Code IfCode.java | Adder.java | DoAdder.java | ForAdder.java


Operators

An operator specifies how the operand or operands of an expression are manipulated.

Java has many of the same operators as does C and C++ with similar precedence and associvity.

Operators are usually represented using symbols (+ - * / %).

Operators and operands form the atomic unit of an expression.

Operators take either one operand (unary), two operands (binary) or three operands (ternary).

When multiple operators are used in an expression, then precedence and associativity is used to bind (or group) operands with operators.

Java evaluates expressions unconditionally left-to-right. [This is not true in C or C++.]

Arithmetic Operators

All of the arithmetic operators are binary operators (i.e. they take two operands).

   +   addition
   -   subtraction
   /   division
   *   multiply
   %   modulus (remainder)

The arithmetic operators work with integral and floating-point values except for the modulus (%) operator which works only on integral operands.

If both operands are integral data types, then the result is integral and an integer division occurs (i.e. any reminder is dropped (truncated) from the result). Examples.

    3 / 2  equals  1
    7 / 3  equals  2
   11 / 3  equals  3

An integer division by 0 causes an Exception. Example: The expression 2002 / 0 causes a program to abnormally terminate. Floating-point division by 0 results in the value infinity without an Exception.

If one operand is integral and other is a floating-point, then a floating-point division is executed. The result is the type of the floating-point operand.

If both operands are floating-point, then the type of the result is the type of the "largest" operand. Example.

   float f = 1.9;
   double d = 1.9;

   f / d   results in a  double
   d / f   results in a  double

The + addition operator can be applied to String objects. If only one operand is a String, then the other is converted to a String. The addition operator when applied to String objects performs a concatentation of the value of the left-hand operand with the value of the right-hand operand. The concatenation results in the creation of a third (new) String object that stores the result of the concatentation. [This is Java's only overloaded operator. Java does not support operator overloading.]

Relational Operators

Relational operators are binary operators that are used to compare the value of two expressions.

   ==  equality
   !=  not equal
   >   greater than
   >=  greater than or equal to
   <   less than
   <=  less than or equal to

Relational operators evaluate to boolean values (i.e. true or false).

   int a = 10;
   int b = 15;

   a == b        evaluates to false
   a != b        evaluates to true
   a > b         evaluates to false
   a < b         evaluates to true

If the operands are not the same type, then the value of the type smallest type is promoted to the larger type before the comparison is executed.

Logical Operators

The binary logical operators are use to test if two expressions, when combined, are either true or false. The unary logical operator is used to reverse the outcome of an expression that evaluates to a boolean values.

   &&  and
   ||  or
   !   not (unary)

The operands of logical operators must evaluate to type boolean values.

Java uses short-circuit evaluation (i.e. an EXPR is evaluated only until the truth or falsehood of the entire EXPR can be unambigously determined).

Bit-wise Operators
   ^  exclusive or
   &  and
   |  or
   >> right shift (sign extension)
   << left shift
   ~  one's complement

   Java also has a  >>>  right shift operator (0 extension).
Miscellaneous Operators
   ++  increment (both prefix and postfix)
   --  decrement (both prefix and postfix)
   ?:  conditional
   +   unary plus
   -   unary minus
   ()  typecast
   compound assignment  (e.g. +=, -=, /=, %=, *=, &=, |=, ^=, 
                              <<=, >>=, >>>=)
Java does not the following operators:
   sizeof()
   sequence (i.e. comma)

   Note:  the sequence operator is supported when used with the
          for()  repetition control statement.
The following Java operators will be covered later:
   new
   instanceof
   ()  /* method call */
   []  /* array */
   .   /* dot */
Operator precedence and associativity:

[]   .    ()(method call) left-to-right
!   ~   ++   --   +(unary)   -(unary)  ()(cast)   new right-to-left
*   /   % left-to-right
+   - left-to-right
<<   >>   >>> left-to-right
<   <=   >   >=   instanceof left-to-right
==   != left-to-right
& left-to-right
^ left-to-right
| left-to-right
&& left-to-right
|| left-to-right
?: left-to-right
= compound assignment operators right-to-left

In Java, the order in which EXPRs are evaluated is always a strict left-to-right. Recall, in C and C++, the order of EXPR evaluation is implementation-dependent. Having the order of EXPR evaluation be well-defined helps make Java portable. Here is an example:

   Given the following EXPR:  f() + g()

   In Java, you are guaranteed that  f()  will be called before  g().
   In C, on some systems  f()  may be called first, but on others it
   might be called after  g()  has been invoked.

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


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)


Home Previous Next