Loops

Before going through loops or logic performed by logic lets have a look at various operators which will be useful in conditional operations.

Making Comparisons
  1. Java provides 6 relational operators for comparing two data values.
  2. Data values compared can be variables,constants, or expressions with values of Java's primitive data types.
  3. 6 relational operators are
    1. > less than
    2. >=  less than equals to
    3. == equals to
    4. != not equals
    5. <= greater than equals
    6. < greater than
  4. To store the result of operations by these operators we use Boolean type variables
    1. Boolean state=false;
    2. state=x-y<a+b;
    3. value of state is true if x-y<a+b else false
  5. So if we look at the precedence table discussed earlier we find that arithmetic operators precedence is higher than comparison operators so arithmetic operations will always be executed first.
    1. So the expression x-y==a+b will produce result true only if x-y is equal to a+b since the arithmetic expressions will be evaluated first because of higher precedence operators.
    2. If the left and right operands are of different types then the lower one will be typecaste to the higher one.
    3. So while comparing a double and an integer number the integer will be converted to double before comparison.
If Statement
  1. This statement is of the form
    1. if(expression){statement};
    2. The expression is a Boolean expression which if returns true then the code in braces executes.
I am placing a code file here called as calc.java We will be looking at different functions of this at different times I am placing here so you can copy paste the code in advance and look further.We have used this class earlier as well I will continue adding more features to this class.

 public class calc {  
   private final int digit1;  
   private final int digit2;  
   public calc(int digit1,int digit2)  
   {  
     this.digit1=digit1;  
     this.digit2=digit2;  
   }  
   public void checkEven()  
   {  
     if(this.digit1!=0)  
     {  
       if(this.digit1%2==0)  
       {  
         System.out.println("Digit 1 is even");  
       }  
     }  
     else  
     {  
       System.out.println("Digit 1 is 0");  
     }  
     if(this.digit2!=0)  
     {  
       if(this.digit2%2==0)  
       {  
         System.out.println("Digit 2 is even");  
       }  
     }  
     else  
     {  
       System.out.println("Digit 2 is 0");  
     }  
   }  
   public void luck()  
   {  
     int number=0;  
     number=1+(int)(100*Math.random());  
     if(number%2==0)  
     {  
       System.out.println("You have got an even number ,"+number);  
     }  
     else  
     {  
      System.out.println("You have got an odd number ,"+number);    
     }  
   }  
   public void greatorThan()  
   {  
     int result=this.digit1>this.digit2?this.digit1:this.digit2;  
     System.out.println(result+" is Greator");  
   }  
   public void lessThan()  
   {  
     int result=this.digit1<this.digit2?this.digit1:this.digit2;  
     System.out.println(result+" is Lesser");  
   }  
   public int sumlimit(int limit)  
   {  
     int sum=0;  
     for(int i=0;i<=limit;i++)  
     {  
       sum+=i;  
     }  
     return sum;  
   }  
   public void squares()  
   {  
     for(int i=0,j=0;i<=10;i++,j++)  
     {  
       System.out.println(i*j);  
     }  
   }  
   public void factorial(long limit)  
   {  
     for(long i=1L;i<=limit;i++)  
     {  
       long number=i;  
       long factorial=1L;  
       for(long j=number;j>1;j--)  
       {  
         factorial=factorial*j;  
       }  
       System.out.println("Factorial of "+number+"is "+factorial);  
     }  
   }  
   public void primes(int limit)  
   {  
     boolean isPrime;  
     for(int i=2;i<=limit;i++)  
     {  
       isPrime=true;  
       for(int j=2;j<i;j++)  
       {  
         if(i%j==0)  
         {  
           isPrime=false;  
           break;  
         }  
       }  
       if(isPrime)  
       {  
         System.out.println("Caught Prime : "+i);  
       }  
     }  
   }  
   public void checkMonth(int numOfDays)  
   {  
     if(numOfDays==30)  
     {  
       System.out.println("Month is April, June, September, or November");  
     }  
     else if(numOfDays==31)  
     {  
       System.out.println("Month is January, March, May, July, August, October, or December.");  
     }  
     else if(numOfDays==28 && numOfDays==29)  
     {  
       System.out.println("Month is Feburary.");  
     }  
     else  
     {  
       assert false:"No Month Found with "+numOfDays+" days";  
     }  
   }  
   public static void main(String[] args)  
   {   
     //check Even  
     calc c10=new calc(25,30);  
     c10.checkEven();  
     //Luck  
     calc c6=new calc(25,30);  
     c6.luck();  
     //Greator Than  
     calc c7=new calc(25,30);  
     c7.greatorThan();  
     c7.lessThan();  
     //Sum Limit  
     calc c8=new calc(25,30);  
     int sum=c8.sumlimit(20);  
     System.out.println("Sum = " + sum);  
     //squares  
     calc c9=new calc(25,30);  
     c9.squares();  
     c9.factorial(20L);  
     c9.primes(50);  
     c9.checkMonth(12);  
   }  
 }  

So the function we are going to look here is checkEven and in the function a check is made if digit one is zero and then its checked if its even ,if it is we show a confirmation.Similar operations are done with second number.

Statement Blocks
  1.  We have seen in example code that we have placed the code after the if statement in curly Braces.We can use statement in the above example as 
    1. if(this.digit1%==0)
      System.out.println("Digit 1 is even")
      if(this.digit2%==0)
      System.out.println("Digit 2 is even")
  2. This is valid but will execute only one statement after "if".
  3. To execute multiple statements we create a statement block which rests in curley braces.
 The Else Clause
  1. We can extend if statement with an else clause.
  2. Else provides with a choice to execute a set of statements when all if conditions are false.
  3. This provides a choice between 2 courses of action.
We will now look into a function of same class function "Luck".Random method returns value of type double between 0.0 and 1.0.So the largest number we can get is 0.999.We are using this to get a random floating point number between 100 and 1 and converting the same to int thus removing its decimal part.

Nested if Statements
  1. These statements are executed if the parent statement is true and we need another child "if" based on parent if.
  2. A simple example is
    1. if(number!=0)
      {
      if(number%2!=0)
      {
      System.out.println("Number is odd");
      }
      }
  3. We have seen such a case in function "checkEven" discussed earlier.However we will look in another example as follows.
 public class LetterCheck {  
   public static void main(String args[]) {  
     char symbol = 'A';  
     symbol = (char) (128 * Math.random());  
     if (symbol >= 'A') {  
       if (symbol <= 'Z') {  
         System.out.println("You have got a capital Letter " + symbol);  
       } else {  
         if (symbol <= 'a') {  
           if (symbol <= 'z') {  
             System.out.println("You have got a small Letter " + symbol);  
           } else {  
             System.out.println("The code is greater than 'a' but its not a letter");  
           }  
         } else {  
           System.out.println("The code is less than 'a' but its not a letter");  
         }  
       }  
     }  
     else  
     {  
       System.out.println("The code is less than 'A' but its not a letter");  
     }  
   }  
 }  
This program checks for the capital letter or small letter depending upon its ASCII code.It generates a random character with numeric code between 0&127.We have 4 if statements.The first if checks weather symbol is greater than 'A'.The first nested if checks if its less than 'Z'.The next if checks if it is a small letter greater than 'a'.The next if checks if its less than 'z' and so on.

Comparing Enumeration Values
Variables of an enumeration type are compared using ".equals()" method that every enumeration object provides.Let's look into an example

 public enum operation{  
     PLUS(-2147483648,-1),  
     MINUS(-2147483648,-1),  
     TIMES(-2147483648,-1),  
     DIVIDE(-2147483648,-1);  
     private final int num1;  
     private final int num2;  
     operation(int num1,int num2)  
     {  
       this.num1=num1;  
       this.num2=num2;  
     }  
     int calculate()   
     {  
       switch(this)   
       {  
         case PLUS:  
           return this.num1 + this.num2;  
         case MINUS:  
           return this.num1 - this.num2;  
         case TIMES:  
           return this.num1 * this.num2;  
         case DIVIDE:  
           return this.num1 / this.num2;  
         default:  
           throw new AssertionError("Unknown operations " + this);  
       }  
     }  
   }  
File : enumeration.java
 public class enumeration   
 {    
   public static void main(String args[])  
   {  
     int result = operation.DIVIDE.calculate();  
     System.out.println(result);  
     result = operation.PLUS.calculate();  
     System.out.println(result);  
     operator add=operator.PLUS;  
     result=add.calculate(12,12);  
     System.out.println(result);  
     if(add.equals(operator.PLUS))  
     {  
       System.out.println("This symbol represents PLUS");  
     }  
     //Collection based for loop  
     for(operation or:operation.values())  
     {  
       System.out.println(or+" "+or.calculate());  
     }  
   }  
 }  
So in the above example the call to equals method is initiated by add which is the object of class operator of type PLUS.This method compares the value of add and value between parenthesis and results in true if they are equal else false if they are unequal.We will look into remaining code later in chapter.

Logical Operators
  1. These operators are used to combine conditions in an if statement.The situation can be like if 2 if statements are true then do something or if one statement is true other is false then do something.
  2. Of course this can be done by nested if's but with logical operators code looks more neat and executes faster.
  3. There are 5 logical operators that operate on Boolean values.
    1. & logical AND
    2. && conditional AND
    3. || conditional OR
    4. | logical OR
    5. ! logical negation(NOT)
Logical AND operator
  1. We can use & or && in the case where both the logical expressions must be true for the result to be true.
  2. The difference between the two is that in logical & the second statement and first statement both are excuted
  3. In conditional & if the first statement is false the second will not be executed because our condition is both the statements must be true.
    1. if(symbol>='A' & symbol<='Z')
      executes a check on both i.e. symbol greater than A and less than Z
    2. if(symbol>='A' && symbol <='Z')
      will execute (symbol<='Z') only if(symbol>='A') else will discard second part.This makes the program execution faster.
    3. Mostly we will use conditional AND but we may require to use logical AND in following scenario.
      1. if(++value%2=0 & ++count<limit)
        {
          //Do Something
        }
Logical OR operator
  1. The logical OR operator | and || apply when you want a true result if either or both of the operands are true.
  2. The logical or operator omits the execution of right hand operand if the left hand operand is true.
Boolean Not Operations
The third type of logical operator "|" applies to one of the Boolean operand, and the result is inverse of the operand value.
So !flag means if flag is false then perform operations.
We will now look into a code fragment that builds a cricket game and see how these operators work.
 public class zeroCricket   
 {    
   private static int runs=0;  
   public int score()  
   {  
     int run=(int)(6*Math.random());  
     if(run==0 || run==5)  
     {  
       System.out.println("You are Out!");  
       run=0;  
     }  
     else if(run==1)  
     {  
       System.out.println("That's a quick single");  
     }  
     else if(run==2)  
     {  
       System.out.println("You looked for a double and got it");  
     }  
     else if(run==3)  
     {  
       System.out.println("Three more added to the total");  
     }  
     else if(run==4)  
     {  
       System.out.println("Brilliant Grounded Shot That's a four");  
     }  
     else if(run==6)  
     {  
       System.out.println("That's Huge That's a six");  
     }  
     return run;  
   }  
   public static void main(String args[])  
   {  
     zeroCricket zc=new zeroCricket();  
     int run=0;  
     run=zc.score();  
     if(run!=0 && run!=5)  
     {  
       runs=runs+run;  
       System.out.println("You'r total score: "+runs);  
     }  
     else  
     {  
       System.out.println("You'r total score: "+runs);  
       runs=0;  
     }  
   }  
 }  
Each time we execute the above script we score runs we see 2 cases of using || and && in this.
In function score we are using || and in function main and we are using &&.In function score we are checking if either runs equals 0 or 5 then we need to execute a set of statements.
Where as when we need to add score to previous score in main we are using logical and operator.

The conditional Operator

  1. The conditional operator is also called as a ternary operator
  2. It involves 3 operands
  3. Example We need to store greater age between two into our operand.
    1. older=yourAge>myAge?yourAge:myAge
    2. Here older will have your age if the statement is true else it will have my age if statement is false.
  4. "?" is called as ternary operator
  5. The expression here is "yourAge>myAge"
  6. General Defination
    1. logical expression?expression1:expression2
    2. If result of logical expression is true result is expression 1 else result is expression 2
  7. Now we look back into file calc.java and look into function "greatorThan" and "lessthan".These functions use ternary operators to find the greater and lesser numbers of the two.
The switch statement

  1. Switch statement is used to select from multiple choices based on a set of fixed values for a given expression.
  2. The expression must produce a result of an integer type,long or a value of an Enumeration type.
  3. The expression that controls a switch statement can result in a value of type char,byte,short, or int or an enumeration constant.
  4. We define possible switch values as case values also called as case labels which we define using keyword case.
  5. The default value is selected when the value of the switch expression does not correspond to any of the values for the other cases.
  6. The default value should always be placed at end of all values else values below it will never be executed.
  7. A code fragment which showcases switch is as follows.
    Switch(var)
    {
    case 1:
    statement1;
    statement2;
    break;
    case 2:
    statement 3;
    statement 4;
    break;
    default:
    statement 5;
    statement 6;
    break;
    }
  8. Remember to add break after each and every case end else all the cases which follow the selected case will also get executed.
  9. The default case is optional.In case you don't place the same and no case matches nothing will happen.
Variable Scope
  1. The scope of the variable is the part of the program over which the variable name can be referenced.
  2. Variables that are declared within method are called as local variables.
  3. A variable does not exist before its declaration.
  4. It continues to exist until the end of the block in which it is defined.
  5. Class variables have a larger lifetime when they are declared .The variable PI and E in the standard library are examples of these.
  6. There are variables that form a part of class object called instance variables.
Loops
  1. A loop allows you to execute a statement or a block of statements repeatedly.
  2. Has 2 parts a loop control statement and a loop body.
Lets look at the zero cricket example again this time we won't run it each time to get our shot score it will automatically add the same until we are out and show us the total.
 /*  
  * To change this license header, choose License Headers in Project Properties.  
  * To change this template file, choose Tools | Templates  
  * and open the template in the editor.  
  */  
 /**  
  *  
  * @author Gaurav Matta  
  */  
 public class zeroCricket   
 {    
   private static int runs=0;  
   public int score()  
   {  
     int run=(int)(6*Math.random());  
     if(run==0 || run==5)  
     {  
       System.out.println("You are Out!");  
       run=0;  
     }  
     else if(run==1)  
     {  
       System.out.println("That's a quick single");  
     }  
     else if(run==2)  
     {  
       System.out.println("You looked for a double and got it");  
     }  
     else if(run==3)  
     {  
       System.out.println("Three more added to the total");  
     }  
     else if(run==4)  
     {  
       System.out.println("Brilliant Grounded Shot That's a four");  
     }  
     else if(run==6)  
     {  
       System.out.println("That's Huge That's a six");  
     }  
     return run;  
   }  
   public static void main(String args[])  
   {  
     zeroCricket zc=new zeroCricket();  
     int run=0;  
     do  
     {  
       run=zc.score();  
       runs=runs+run;  
     }  
     while(run!=0 && run!=5);  
     System.out.println("You'r total score: "+runs);  
 //    if(run!=0 && run!=5)  
 //    {  
 //      runs=runs+run;  
 //      System.out.println("You'r total score: "+runs);  
 //    }  
 //    else  
 //    {  
 //      System.out.println("You'r total score: "+runs);  
 //      runs=0;  
 //    }  
   }  
 }  
As you can see we have commented out the manual execution and placed it inside a do while loop.We will learn more on this loop in a moment.

Varieties of loops

  1. The numerical For loop
    1. for(initialization;loop_condition;incement_expression)
      {
      }
    2. The first part initialization executes once before the loop starts.
      1. Generally used as a counter start for the number of loop operations.
    3. Execution of the loop continues until the loop condition is true.
    4. When loop_condition is false, the loop ends and the execution continues to the expression which follows the block.
    5. The increment_expression is used to increment the loop counter.
    6. We can even initialize and use variables.Also we can place their increment/decrement  statement within the loop itself.
    7. We can even use floating point values in for loop.
  2. Collection based for loop
    1. for(type identifier;iterable_expression)
      {
      }
    2. Has 2 control statements separated by a colon.
    3. The first element is an identifier of type that you specify and the second is an expression specifying a collection of objects or values of the specified type.
    4. The loop will execute once for each item of the specified type that appears in the collection and you can refer to the current item in the loop body using the identifier that you specified as the first control element.
    5. We can apply this form of for loop to array's as well as collections.
  3. While loop
    1. while(expression)
      {
      //statements
      }
    2. This loop executes as long as the logical expression between the parenthesis is true.
    3. When the expression is false the loop ends.
    4. The expression is tested at the beginning of the loop so if it is initially false the loop body will not be executed at all.
  4. Do While Loop
    1. do{
      //statements
      }while(expression)
    2. This loop is similar to the while loop,except that the controlling expression is tested at the end of the loop
    3. The loop body executes at least once even if the expression is false since the expression is checked in the end.
Numerical For Loop
Collection Based For Loop

While Loop
Do While

Now lets move back a bit to the program calc.java and look into functions sumLimit and Squares.
While "sumLimit" uses a normal for loop to calculate the sum of numbers to a defined limit.The Squares on the other hand multiplies the two numbers which are initialized and incremented in loop it self.
Next we will move to our enumeration example(operation.java and enumeration.java) defined above if we see closely we have a comment called as collection based for loop.In the loop we are looping through all the objects of type "operation" and on each of the object type we are calling method calculate.This is an example of our collection based loop.We are currently running it on our enumeration variable.

Nested Loops
  1. We can nest loops of any kind one inside other to any depth.
  2. Again considering calc.java lets look at the factorial function this time.We are using nested loops in this.In the first loop we are increment limit to which we need factorials and in second loop we have decremented the current number so that we can multiply result with itself to calculate factorial.
The Continue Statement
  1.  This is used in situations when we may want to skip all or part of loop iteration.
  2.  Suppose we need a sum of all even numbers in a limit.
  3. for(int i=1;i<=limit;i++)
    {
    if(i%2!=0)
    {
    continue;
    }
    sum+=i;
    }
  4. When the continue statement is executed the current iteration is skipped.
Labelled Continue Statement
  1. In nested loops this statement enables you to stop executing the inner loop current iteration and continue at beginning of the next iteration of the outer loop that immediately encloses the current loop.
  2. We identify the outer loop with statement label.
  3. A label is simply an identifier that is used to reference to a particular statement.
  4. Example :
  5. outerLoop:
    for(){
    for(){
    for(){
    if(i%2==0){
    continue outerLoop;
    }
    }
    }
    }
  6. This will break from the innermost loop and continue again from the outermost loop.
Break Statement
  1. The break statement in a loop is used to breakout of the loop and continue statements that follow the same.
  2. The loop is not executed any further once the break statement is encountered.
  3. Looking the the Primes function in calc,java we are breaking out of the loop when we encounter at least multiple of the number to be checked for prime.
Indefinite Loops
  1. Indefinite loops are those loops which run forever till we reach a memory constraint or encounter a break at runtime.
  2. For example
    for(int i=2; ;i++){
    }
  3. Since there is no condition in between these loops they run for ever.
  4. We must break these loops in between at a condition.
Labeled Break Statement
  1. This statement enables you to jump immediately to the statement following the end of any enclosing statement block or loop that is identified by the label in the labeled break statement.
  2. We jump out of the current execution to the statement defined by label.
  3. Example:
    Block1:{
    Block2:{
    OuterLoop:
    for(...){
    break Block1;
    while(...){
    }
    }
    }//End of Block2
    }//End of Block1
Assertions


  1. Assertions are used to handle situations which may produce undesired results in our code.
  2. These situations are defined by logical expressions in our code.
  3. An assertion statement is of the form
    assert logical_expression;
  4. "assert" is the keyword that performs assertion on an expression.
  5. If the logical expression is true program runs normally else the program terminates with an error message starting with
    1. java.lang.Assertion.Error
  6.  To show assertions you need to run the code as 
    1. java -enableassertions prog
    2. java -ea prog
  7. We can customize the error in our assertion as
    1. assert false:"No month found with "+ numOfDays;
  8. Looking into calc.java the function "checkMonth" shows an assertion example where if days are not enough we assert a message of "No Month Found".
Enumeration.java and zeroCricket.java output:













Calc.java output:

No comments:

Post a Comment