3. Operators and Flow Control

About this Tutorial –

Objectives –

This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.

Audience

This training course is aimed at OO developers who need to transition into Java.

Prerequisites

No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The Java course cover these topics and more:

  • Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
  • Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
  • Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques

Exam Preparation

The Java course will help you prepare for these certifications:

  • Oracle Certified Java Associate – Exam 1Z0-803
  • Oracle Certified Java Professional – Exam 1Z0-804

Download Solutions

HTML tutorial


Overview

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Defining and Using Classes

Lab 1: Operators

Lab 1: Operators
  1. Arithmetic Operators
    • Basic binary operators
      • a + b (addition)
      • a – b (subtraction)
      • a * b (multiplication)
      • a / b (division)
      • a % b (modulo, i.e. remainder)
    • Basic unary operators
      • +a (unary plus)
      • -a (unary negation)
      • a++ (postfix increment by 1)
      • ++a (prefix increment by 1)
      • a– (postfix decrement by 1)
      • –a (prefix decrement by 1)
  2. Conditional Operator
    • The conditional operator is like an in-situ if test
      • (condition) ? trueResult : falseResult
    • Example:
      boolean isMale;
      int age;
      ...
      int togo = (isMale) ? (65 - age) : (60 - age);
      System.out.printf("%d years to retirement\n", togo);
  3. Assignment Operators
    • Basic assignment operator
      • a = b (assign b to a)
      • Performs widening conversion implicitly, if needed (see later)
    • Primitive assignment
      • Assign LHS variable a bitwise copy of the RHS value
        int a = 100;
        int b = 200;
        b = 42;
        a = b;
    • Reference assignment:
      • Assign LHS variable a reference to the RHS object
        File file1 = new File("somefile.txt");
        File file2 = new File("anotherfile.txt");
        file1 = file2;
    • Compound assignment operators:
      • a += b (calculate a + b, then assign to a)
      • a -= b (calculate a – b, then assign to a)
      • a *= b (calculate a * b, then assign to a)
      • a /= b (calculate a / b, then assign to a)
      • etc…
    • Example:
      // Use *= compound operator:
      x *= a + b;
      // Equivalent to the following (note the precedence):
      x = x * (a + b);
  4. Aside: Working with Strings
    • String concatenation
      • strResult = str1 + str2
      • strResult = str1 + obj
    • String concatenation
      • str1 += str2
      • str1 += obj
    • Examples
      • What do the following statements do?
        String message = "Hello";
        int a = 5;
        int b = 6;
        System.out.println(message + a + b);
        System.out.println(message + (a + b));
        System.out.println("" + a + b);
        System.out.println(a + b);
  5. Casting
    • Implicit conversions:
      • Java implicitly converts less-precise expns to more-precise expns
      • byte -> short -> int -> long -> float -> double
    • Explicit conversions (aka casting):
      • You can explicitly cast an expression into a compatible other type
      • (type) expression
      • Might result in a loss of precision
  6. Aside: Working with Bytes
    • You can assign an integer literal value to a byte
      • Compiler implicitly casts integer literal value into a byte
        byte age = 21;
        // Equivalent to:
        // byte age = (byte) 21;
    • If you do any arithmetic with bytes, the result is an int
      • Consider the following example:
        byte myAge = 21;
        byte yourAge = 22;
        int totalAge1 = myAge + yourAge; // This works.
        byte totalAge2 = myAge + yourAge; // This doesn't work.
        byte totalAge3 = (byte)(myAge + yourAge); // This works.
  7. Relational Operators
    • There are 6 relational operators (all return boolean):
      • == (equality)
      • != (inequality)
      • > (greater-than)
      • >= (greater-than-or-equal)
      • < (less-than)
      • <= (less-than-or-equal)
    • If you use == or != on primitive types:
      • You are comparing numeric values
      • i.e. do they contain the same value
    • If you use == or != on reference types:
      • You are comparing object references
      • i.e. do they point to the same object
    • To compare the values of objects:
      • Use the equals() method, e.g. str1.equals(str2)
      • The String class also has equalsIgnoreCase()
  8. Logical Operators
    • Short-circuit logical operators:
      • && (logical AND)
      • || (logical OR)
    • Non-short-circuit logical operators:
      • & (logical AND)
      • || (logical OR)
      • ^ (logical XOR)
    • Logical inverse operator:
      • ! (logical NOT)
    • Note:
      • All these operators require boolean operands
  9. Bitwise Operators
    • Bitwise AND and OR binary operators
      • & (bitwise AND)
      • ^ (bitwise exclusive OR)
      • | (bitwise inclusive OR)
    • Bitwise NOT unary operator
      • ~ (bitwise NOT)
    • Bitwise shift operators
      • << (shift bits left)
      • >> (signed right-shift, i.e. shift bits right and preserve top bit)
      • >>> (unsigned right-shift, i.e. shift bits right and set top bit to 0)
  10. Order of Precedence
    • Operators have the following precedence (use parens to override this precedence):
      • Unary: ++ — + – ! ~ (type)
      • Multiplicative: * / %
      • Additive: + –
      • Bitwise shift: << >> >>>
      • Relational: > >= < <= instanceof
      • Equality: == !=
      • Bitwise AND: &
      • Etc…
Lab
  1. Using operators
    • In the student project, write code to manipulate day, month, and year values using operators.
    • Suggestions and requirements:
      • To start off with, declare 3 integers with hard-coded values for the day, month, and year.
        // Declare 3 variables, for a hard-coded date.
        int day = 3, month = 12, year = 2014;
      • Use a conditional operator (?:) to determine if it’s a leap year. A leap year is: (evenly divisible by 4 AND NOT evenly divisible by 100) OR (evenly divisible by 400); Use the remainder operator (%) to help you out here.
        // Is the date a leap year?
        boolean isLeapYear = ((year % 4 == 0) && !(year % 100 == 0)) ||
            (year % 400 == 0);
      • Test whether your “is-leap-year” algorithm works for various years.
        System.out.printf("Is %d a leap year? %s\n", year, isLeapYear ? "yes" : "no");
      • View code file.

Lab 2: Conditional statements

Lab 2: Conditional statements
  1. Using if Tests
    • Basic if tests – Executes body if booleanTest is true.
      if (booleanTest) {
       body
      }
    • View code file.
    • if-else tests – Executes body1 if booleanTest is true,Otherwise, executes body2.
      if (booleanTest) {
       body1
      } else {
       body2
      }
    • View code file.
    • if-else-if tests – Executes body1 if booleanTest1 is true, Or executes body2 if booleanTest2 is true, Or executes body3 if booleanTest3 is true, If all else fails, executes (optional) lastBody.
      if (booleanTest1) {
       body1
      }
      else if (booleanTest2) {
       body2
      }
      else if (test3) {
       body3
      }
      ...
      else {
       lastBody
      }
    • View code file.
    • Notes:
      • Test conditions must be boolean (or Boolean)
      • {} are optional if you want a 1-line statement
  2. Nesting if Tests
    • You can nest if tests inside each other
      • Use {} to ensure correct logic, as needed
      • Use indentation for readability
        int age = ... ;
        String gender = ... ;
        if (age < 18) {  if (gender.equals("Male")) {   System.out.println("boy");  } else {   System.out.println("girl");  } } else {   if (age >= 100) {
           System.out.print("centurion ");
          }
         if ...
        }
      • View code file.
  3. Using switch Tests
    • The switch statement is useful if you want to test a single expression against a finite set of expected values
    • General syntax:
      switch (expression) {
      case constant1:
       branch1Statements;
       break;
      case constant2:
       branch2Statements;
       break;
      ...
      default:
       defaultBranchStatements;
       break;
      }
    • View code file.
    • Expression must be:
      • char, byte, short, int (or wrappers)
      • enum (Java 6 onwards)
      • string (Java 7 onwards)
    • Cases:
      • Must be (different) constants
      • Are evaluated in order, top-down
    • If you omit break:
      • Fall-through occurs
    • The default branch:
      • Is optional
      • Doesn’t have to be at the end!
  4. Using Strings in Switch Statements
    • Java SE 7 lets you use string literals in switch statements
      • Equivalent to calling equals()
      • i.e. case-sensitive
        String country;
        int diallingCode;
        ...
        switch (country.toLowerCase()) {
         case "uk":
          diallingCode = 44;
          break;
         case "usa":
         case "canada":
          diallingCode = 1;
          break;  
         ...
        }
      • View code file.
Lab
  1. Using conditional logic
    • Validate the day, month, and year values. Output a single message saying whether the date is valid or not. If the date is valid, output it in the format dd/mm/yyyy
    • Suggestions and requirements:
      • Write an if-statement to validate the month (it must be 1 – 12).
          // Is the date valid?
          boolean isValid;
          
          if (month < 1 || month > 12) {
           isValid = false;
           
      • View code file.
      • Write an if-statement to validate the year (for the sake of argument, let’s say the year must be 0 – 2099).
          } else if (year < 0 || year > 2099) {
           isValid = false;
           
      • View code file.
      • Write an if-statement to ensure the day is 1 or higher.
          } else if (day < 1) {    isValid = false;    
      • View code file.
      • Write a switch-statement to ensure the day isn't too big. The maximum value is 28, 29, 30, or 31, depending on the month (and if the month is February, whether it's a leap year).
          } else {
          
           int maxDay;
           switch (month) {
            case 2: 
             maxDay = (isLeapYear) ? 29 : 28;
             break;
             
            case 4:
            case 6:
            case 9:
            case 11:
             maxDay = 30;
             break;
             
            default:
             maxDay = 31;
             break;
           }
           
           isValid = (day <= maxDay);   }
      • View code file.

Lab 3: Loops

Lab 3: Loops
  1. Using while Loops
    • The while loop is the most straightforward loop construct
      • Boolean test is evaluated
      • If true, loop body is executed
      • Boolean test is re-evaluated
      • Etc...
        while (booleanTest) {
         loopBody
        }
      • View code file.
    • Note:
      • Loop body will not be executed if test is false initially
    • How would you write a while loop:
      • To display 1 - 5?
      • To display the first 5 odd numbers?
      • To read 5 strings from the console, and output in uppercase?
  2. Using do-while Loops
    • The do-while loop has its test at the end of the loop
      • Loop body is always evaluated at least once
      • Handy for input validation
      • Note the trailing semicolon!
        do {
         loopBody
        } while (booleanTest);
      • View code file.
    • How would you write a do-while loop:
      • To keep reading strings from the console, until the user enters "Oslo", "Bergen", or "Trondheim" (in any case)?
  3. Using for Loops
    • The for loop is the most explicit loop construct
      • Initialization part can declare/initialize variable(s)
      • Test part can incorporate any number of tests
      • Update part can do anything, e.g. update loop variable(s)
      • You can omit any (or all!) parts of the for-loop syntax
        for (init; booleanTest; update) {
         loopBody
        }
    • How would you write a for loop:
      • To display the first 5 odd numbers?
      • To display 100 - 50, in downward steps of 10?
      • To loop indefinitely?
  4. Unconditional Jumps
    • Sometimes it can be convenient to use unconditional jump statements within a loop
      • break - Terminates innermost loop
      • continue - Terminates current iteration of innermost loop, and starts next iteration, If used in a for loop, transfers control to the update part
      • return - Terminates entire method
    • Example:
      for (initialization; test; update) {
       ...
       if (someCondition)
        break;
       ...
       if (someOtherCondition)
        continue;
       ...
      }
    • View code file.
    • You can use break and continue in nested loops
      • By default, they relate to the inner loop
      • To relate to the outer loop, use labels
    • Example:
      myOuterLabel:
      // Outer Loop.
      for (init; booleanTest; update) {
       ...
       // Inner Loop.
       for (init; booleanTest; update) {
        if (someCondition)
         break myOuterLabel;
        ...
        if (someOtherCondition)
         continue myOuterLabel;
        ...
       }
      }
    • View code file.
Lab
  1. Using loops
    • Refactor your application so that it gets a series of dates from the user, rather than having a single hard-coded date.
    • Suggestions and requirements:
      • Write a do-while loop that allows the user to enter a series of different dates. Each time round the loop, ask the user whether he/she wants to continue; if the user says "Yes" or "yes", keep on iterating.
         do {
          // Ask the user whether he/she wants to enter another date.
           System.out.print("\nEnter another date? ");
           response = scanner.next();
          } while (response.toUpperCase().equals("YES"));
          
          System.out.println("The End.");
         }
      • View code file.
      • Inside the loop, ask the user to enter a new day, month, and year. Use the Scanner class to help you here (see chapter 2 for a reminder of Scanner).
           // Get a date from the user.
           System.out.print("Day: ");
           day = scanner.nextInt();
           System.out.print("Month: ");
           month = scanner.nextInt();
           System.out.print("Year: ");
           year = scanner.nextInt();
      • View code file.
      • For each date, validate it as you did in Exercise 2 above.

 

Well done. You have completed the tutorial in the Java course. The next tutorial is

4. Defining and Using Classes


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top