Java Flow Control code and rules

Let’s start with

If then else

all pretty straight forward:

int intValue = 100;
String result = "";

if (intValue == 100)
    result = "A";
else if (intValue == 50)
    result = "B";
else if (intValue == 20)
    result = "C";
else result = "F";

Some little things with if then else:


//If must contain code

boolean booleanValue = false;
int intValue = 0;
String stringValue = "Hello";

//This won't compile because there is no if body
if (booleanValue)
else
   System.out.println("false value");

if ((intValue=intValue+10) >= 10);  //This is invalid as we have no body

//This is fine
if (stringValue.equals("Hello"))
    intValue = 100;

if (stringValue.equals("Hello"))
    intValue = 100;
    stringValue = "Hello World";    //This line is not part of the if statement

if (stringValue.equals("Hello"))
    intValue = 100;
    stringValue = "Hello World";    //This line is not part of the if statement
else stringValue = "goodbye";      //This block of code will not compile as we are missing the curlies

if (stringValue.equals("Hello"))
    intValue = 100;
else 
    intValue = 200;
    System.out.println("the stringValue is not equal to Hello");
//The above will compile, but the last statement will always execute - not what we want.
//The curlies resolves this for us:

if (stringValue.equals("Hello")) {
    intValue = 100;
    stringValue = "Hello World";    //This line is NOW part of the if statement
} else {
    stringValue = "goodbye";      
}

if (stringValue.equals("Hello")) {
    intValue = 100;
} else { 
    intValue = 200;
    System.out.println("the stringValue is not equal to Hello");
}

However, this is an interesting example:

if (stringValue.equals("Hello"))   //Lets assume it does
    for (int i = 0; i < 10; i++)
        System.out.println(i);      //because this belongs to the for loop, it is part of the if body

//Output from the above:
0
1
2
3
... 
10

//Comparisons..

//Always remember, comparing strings should be done with .equals() not ==

if (booleanValue = true)
    System.out.println("the booleanValue is true");
else
    System.out.println("the booleanValue is false");

//This will output booleanValue is true because the assignment was successful

Switch

Simple example:


int intValue = 200;

switch (intValue) {
    case 100: System.out.println("it is 100!");
       break;
    case 200: System.out.println("it is 200!");
       break;
    case 300: System.out.println("it is 300!");
       break;
    default: System.out.println("it is not 100, 200, or 300!");
       break;
}

Comparing Switch to if then else

String month = "Jan";

//If statment

if (month.equals("Dec") || month.equals("Jan") || month.equals("Feb") )
    System.out.println("Winter");
else if (month.equals("Mar") || month.equals("Apr") || month.equals("May"))
    System.out.println("Spring");
else if (month.equals("Jun") || month.equals("Jul") || month.equals("Aug"))
    System.out.println("Summer");
else if (month.equals("Sep") || month.equals("Oct") || month.equals("Nov"))
    System.out.println("Autumn");
else 
    System.out.println("n/a");

//Case statement

switch(month) {
    case "Dec":
    case "Jan":
    case "Feb": System.out.println("Winter");
       break;
    case "Mar":
    case "Apr":
    case "May": System.out.println("Spring");
       break;
    case "Jun":
    case "Jul":
    case "Aug": System.out.println("Summer");
       break;
    case "Sep":
    case "Oct":
    case "Nov": System.out.println("Autumn");
       break;
    default: System.out.println("n/a");

Switch can only be used with some data types, byte, short, int, char and String.


int intValue = 100;
switch (intValue*10) {
    //...                         This is fine as you are comparing a int value.
}

double doubleValue = 100.00
switch (doubleValue) {
   //...                          Cannot be used in a switch - if will fail to compile
}

//More stuff

int iv2 = 10, iv3 = 30;

switch (intValue) {
   case iv2+iv3: System.out.println(intValue);  //fails as these are not constants
      break;
   case 10*30: System.out.println(intValue);    //all fine!!!
      break;
   case 10.0: System.out.println("ooh it is a double????");  //no can do, remember
      break;
}

//finals

final int iv2 = 10, final int iv3 = 20, final int iv4;

iv4 = 100;

switch (intValue) {
   case iv2: System.out.println(iv2);           //this is fine
      break;
   case iv2+iv4: System.out.println(intValue);  //fails as iv4 is not considered constant as it was only declared.
      break;
   case 10*30: System.out.println(intValue);    //all fine!!!
      break;
}

String strValue = "XX";

switch(strValue) {
    case "XY": System.out.println("XY");
        break;
    case null: System.out.println("a null");    //Nulls are not allowed!!!
}

For loop

Simple example of a for loop:

int counter = 10;
for (int i = 0; i < counter; i++)
{
     System.out.println(i);
}

Output being:
0
1
2
3
4
5
6
7
8
9

You can break the for statement into initialisation, condition, and update. There can be many of each in a for loop:


int counter = 10;

for (int i = 100, j = 0;          //Initialisation of multiple variables
        j <= i && counter <100;   //Multiple conditions
        i--, j++, counter += 10)  //Multiple updates
{
      System.out.println(i+","+j+","+counter);
}

With the output being:

100,0,10
99,1,20
98,2,30
97,3,40
96,4,50
95,5,60
94,6,70
93,7,80
92,8,90

You can also call methods from the update section.

Nested loops, these allow you to traverse multi-dimensional arrays.


int multiArray[][] = new int[5][4];

//So if we wanted to initialise this with the value -1, we could traverse it with a nested loop.

for (int i = 0; i < multiArray.length; i++)
{
     for (int j = 0; j < multiArray[i].length; j++)
     {
          multiArray[i][j] = -1;
     }
}

The Enhanced for loop

We have already seen this with ArrayLists. A simple example:


ArrayList<String> exampleAL = new ArrayList<String>();

exampleAL.add("value 1");
exampleAL.add("value 2");

//Using a for loop would look like this

for (Iterator<String> i = exampleAL.iterator(); i.hasNext();)
      System.out.println(i.next());

// And as a enhanced for loop

for (String value : exampleAL)
      System.out.println(value);

//Nested ArrayList and enhanced for loops
//We still have exampleAL

ArrayList<String> exampleAL2 = new ArrayList<String>();

exampleAL2.add("1 value");
exampleAL2.add("2 value");

ArrayList<ArrayList<String>> exampleNestedAL = new ArrayList<ArrayList<String>>();

exampleNestedAL.add(exampleAL);
exampleNestedAL.add(exampleAL2);

for (ArrayList<String> al : exampleNestedAL)
      for (String value : al)
          System.out.println(value);

//Within a enhanced for loop you can modify reference object but not primitives.

StringBuilder sbArr[] = {
      new StringBuilder("Value 1"),
      new StringBuilder("Value 2")
};

for (StringBuilder value : sbArr)
     System.out.println(value);   //Will print Value1 and Value2

for (StringBuilder value : sbArr)
     value.append(" appended");

for (StringBuilder value : sbArr)
     System.out.println(value);   //Will print "Value1 appended" and "Value2 appended"

//However, you cannot add, e.g.

for (StringBuilder value : sbArr)
     value = new StringBuilder("new value");

for (StringBuilder value : sbArr)
     System.out.println(value);   //Will print "Value1 appended" and "Value2 appended"

//Another example of the nest loop

for (String v1 : exampleAL)
    for (String v2 : example AL2)
          System.out.println(v1+" : "+v2);

/* output being:
Value 1 : 1 Value
Value 1 : 2 Value
Value 2 : 1 Value
Value 2 : 2 Value
*/

You cannot use enhanced for loop to:

  • Initialise arrays
  • delete or remove elements from a collection
  • Allows for the creation of only one loop variable
  • Don’t use it to initialise, modify, or filter arrays
  • While and do loops

    A simple while loop example

    final int ten = 10;
    boolean finish = false;
    int counter = 0;
    while (!finish) {
        if (counter < ten)
        {
            System.out.println(counter+1);
            counter++;
        }
        else finish = true;
    }
    
    //Remember to define your boolean correctly, if it were true it would not enter the first iteration
    
    

    do while loop

    The do while loop always completes the first iteration before evaluating the condition. If we take the example above:

    int counter = 0;
    boolean finished = false;
    do
    {
         if (counter < 10)
         {
              System.out.println(counter);
              counter++;
         }
         else finished = true;
    } while (!finished)
    
    

    In this instance if counter >= 10 or finished were true, the loop would output the value of counter. A nice example of this is:

    
    int counter=100;
    do
    {
       counter++;                   //increments the counter by 1, line below also increments the counter to evaluate the condition
    } while (++counter > 200)       //this evaluates to false so does not continue with the loop
    System.out.println(counter);   //prints 202
    
    counter=100
    while(++counter > 200)        //evaluates to false, but incremented the counter in the process
    {
        counter++;
    }
    System.out.println(counter);  //print 201
    

    You should try and use the while loops when you don’t know the iterations, where as the for loop should be used when you do know.

    In loops you can break and continue. Break breaks out of the current loop, however in a nested loop it only breaks out of the loop it belongs to. For example, if the break is on the inner loop it will break out of that but the outer loop will continue.

    The continue will continue process in the current loop, but will skip any process on that iteration where the continue is issued.

    Labels….

    Simple examples of break and continue referencing a label:

    String[] values = {"value 1","value 2"};
    exampleLabel:
    for (String v : values)
    {
         if (v.equals("value 1"))
            break exampleLabel;              //This exits the loop to the end of the exampleLabel block
         System.out.println(v);
    }
    
    //Another example
    exampleLabel:
    for (String v : values)
    {
         for (String v1 : values)
         {
            if (v1.equals("value 1"))
               break exampleLabel;           //This exits the loop to the end of the exampleLabel block, so exits both loops
            System.out.println(v1);
         }
    }
    
    exampleLabel2:
    for (String v : values)
    {
         for (String v1 : values)
         {
            if (v1.equals("value 1"))
               continue exampleLabel2;           //This resumes the loop from the label exampleLabel block
            System.out.println(v1);              //Outputs value 1 value 1
         }
    }
    
    //The following will not compile
    exampleLabel:
    int t = 100;
    
    //However this will
    exampleLabel: {
        int t = 100;
    }
    

    Rules of labels are:

  • you can label a code block using {}
  • you can label all loops
  • you can label if’s and switch’s
  • you can label expressions
  • you can label assignments
  • you can label return statements
  • you can label try blocks
  • you can label throws
  • reference: http://www.manning.com/gupta/

    Advertisements

    Tags: , ,

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s


    %d bloggers like this: