Wednesday, 5 February 2014

Branching statement: break

The break Statement
We already seen the use of break in switch case. Similarly, break is used in while, do-while and for loops. Break has two forms in java.
   1. unlabelled break
   2. labelled break

unlabelled break
   Example
class BreakEx{
 public static void main(String args[]){
  for(int i=0; i < 10; i++){
   if(i==5) break;
   System.out.println(i);
  }
  System.out.println("I am out of the loop");
 }
}

Output
0
1
2
3
4
I am out of the loop
 
As you in the above program, when variable “i” reached to 5, break is called, and execution comes out of the loop

labelled break
   label is a group of statements, identified by using labelname.

Syntax
    labelName:{
      statement 1
      statement 2
      …....
      statement N
    }

Example
class BreakEx{
 public static void main(String args[]){
  myLoop: {
   for(int i=0; i < 10; i++){
    if(i==5) break myLoop;
    System.out.println(i);
   }
   System.out.println("I am also in label");
  }
  System.out.println("I am out of the loop"); 
 }
}
        
Output
0
1 
2
3
4 
I am out of the loop
 
As you see in the above program label name is myLoop. When variable 'i' value reaches to 5,  execution comes out of the label.




loops                                                 continue statement                                                 Home

Control flow statements : looping : for

The for statement provides a compact way to iterate over a range of values.

Syntax
    for(initialization; condition; update){
        //statements to be executed
    }

for loop execute the statements until the condition evaluates to false.

Initialization section executed only once, at the starting of loop.
Condition section evaluated every time, before executing the loop statements
update section executes immediately after every execution of loop finishes.

Example : Printing numbers from 0 to 9
class ForEx{
 public static void main(String args[]){
  int var1;
  for(var1 = 0; var1 < 10; var1++){
   System.out.println(var1);
  }
 }
}

Output
0
1
2
3
4
5
6
7
8
9
Some points to remember
1. You can declare a variable inside the for loop itself
        for(int i=0; i<10; i++) is a valid construct

2. for( ; ; )
     Above for loop run for infinite times.


loops                                                 break statement                                                 Home

Control flow statements : looping : while, do-while

while
while statement executes a block of statements until a particular condition is true

Syntax
    while (expression) {
      //statements
}

The expression in the while statement must evaluates to a boolean value, other wise compiler will throw error. While statement first evaluates the expression, until the expression evaluates to true, it  executes the code inside the while block, other wise it comes out of the while loop.

Example : Print numbers from 0 to 9 using while loop.
class WhileEx{
 public static void main(String args[]){
  int var1 = 0;
  while(var1 < 10){
   System.out.println(var1);
   var1++;
  }
 }
}


Output
0
1
2
3
4
5
6
7
8
9

do-while
   do-while is also a loop construct like while, but evaluates its expression at the bottom of the loop instead of the top.

    Syntax
    do {
        //statement(s)
    } while (expression);

Example
class DoWhileEx{
 public static void main(String args[]){
  int var1 = 0;
  do{
   System.out.println(var1);
   var1++;
  }while(var1<10);
 }
}
    
Output   
0
1
2
3
4
5
6
7
8
9

Some points to Remember
1. What is the difference between while and do-while ?
 Statements within the do block are always execute at least once even if the expression evaluates to false.

Example
class CompareLoop{
 public static void main(String args[]){
  boolean flag = false;
  
  while(flag)
   System.out.println("I am in while loop");
  do
   System.out.println("I am in do-while loop");
  while(flag);
 }
}
 
Output
I am in do-while loop
         
Observation
Note that do-while executed, even if the expression “flag” is false. And if you have only one statement, then no need to put the line in between blocks{ }

Control flow statements                                                 loops                                                 Home

Control flow statements : Decision Making: switch

The body of a switch statement is known as a switch block. A statement in the switch block can be labelled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

switch works with the byte, short, char, and int primitive data types. It supports enums also

java 7 supporting strings also in switch case evaluation, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.

Integer, Char, Byte, Short are called wrapper classes. Will discuss about these more on coming posts.

Example
class SwitchEx{
 public static void main(String args[]){
  int day = 5;
  
  switch(day){
   case 1:
    System.out.println("Sunday");
    break;
   case 2:
    System.out.println("Monday");
    break;
   case 3:
    System.out.println("Tueday");
    break;
   case 4:
    System.out.println("Wednesday");
    break;
   case 5:
    System.out.println("ThursDay");
    break;
   case 6:
    System.out.println("Friday");
    break;
   case 7:
    System.out.println("Saturday");
    break;
   default:
    System.out.println("You entered wrong day number");
  }
 }
}

Output
ThursDay

Explanation
As you see in the above program, variable “day” set to the value 5. So in the switch case, case 5 is executed. If the day is set to 1, then case 1 will execute and come out of the switch.

You can see in the above program, each case has a break statement associates with it, is it necessary ? Yes of course, if you don't specify the break for case statements, then all the case statement below the evaluated case are executed.

And one more thing is, case statements need not be in proper order. They can be written in any way.

class SwitchEx{
 public static void main(String args[]){
  int day = 5;
  
  switch(day){
   case 2:
    System.out.println("Monday");
   case 3:
    System.out.println("Tueday");
   case 4:
    System.out.println("Wednesday");
   case 5:
    System.out.println("ThursDay");
   case 6:
    System.out.println("Friday");
   case 7:
    System.out.println("Saturday");
   case 1:
    System.out.println("Sunday");
   default:
    System.out.println("You entered wrong day number");
  }
 }
}

Output
ThursDay
Friday
Saturday
Sunday
You entered wrong day number


As you see in the above program, “day” is set to 5, and there is no breaks in the corresponding cases. So case 5, 6,7, 1 and default are executed.

One more thing is in the above program, case 1 came after 7, it is acceptable behaviour in java.

What is the necessity of default here
If no case is evaluated, then default executes, just like else block in if-else if-else ladder.

Example
class SwitchEx{
 public static void main(String args[]){
  int day = 9;
  
  switch(day){
   case 1:
    System.out.println("Sunday");
    break;
   case 2:
    System.out.println("Monday");
    break;
   case 3:
    System.out.println("Tueday");
    break;
   case 4:
    System.out.println("Wednesday");
    break;
   case 5:
    System.out.println("ThursDay");
    break;
   case 6:
    System.out.println("Friday");
    break;
   case 7:
    System.out.println("Saturday");
    break;
   default:
    System.out.println("You entered wrong day number");
  }
 }
}
 
Output
You entered wrong day number

Some points to remember
1. When to use if-else if -else ladder, than switch ?
Switch case won't supports range checks like age>30, year<2000 etc., in those cases better to go for if-else if-else ladder.
Control flow statements                                                 switch statement                                                 Home

Control flow statements : Decision Making: if-then, if-else, if-else if-else

Java provides control flow statements
     for decision making (if, if-else, switch) and
     for looping (for, while, do-while)

Block of statements
In java the statements between { } are called block of statements.
     {
          //block of code
     }

Decision making statements
if statement
“ if ” tell the program execute the section of code when the condition evaluates to true.
     Syntax
          if(condition){
               // Executes if the condition true
          }

Example
class Grades{
 public static void main(String args[]){ 
  int marks = 20;
  if(marks < 35 ){
   System.out.println("You failed in the Exam. Better luck next time");
  }
 }
}
Output
You failed in the Exam. Better luck next time

Some points to remember
1. In java the condition in the if must evaluates to boolean value, other wise compiler will throw error

Example
class Grades{
 public static void main(String args[]){
  int var1;
  if(var1 = 10){
  
  }
 }
}

When you try to compile the above program, you will get the below error
Grades.java:5: error: incompatible types
 if(var1 = 10){
 ^
 required: boolean
 found: int
1 error
    if-else statement
        Syntax:
        if(condition){

        }
        else{

        }

    If the condition true, then if block code executed. other wise else block code executed.

    Example
    class Grades{
     public static void main(String args[]){ 
      int marks = 36;
      
      if(marks < 35)
       System.out.println("You are failed");
      else
       System.out.println("You are passed");
     }
    }
    

    Output
    You are passed
    

    Observation
    In the above program we haven't written the if, else block codes in between { }, since if there is only one statement in between the blocks, we can omit { }.

    if-else if-else
    By using if-else if-else construct, you can choose number of alternatives.

    An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

    class Grades{
     public static void main(String args[]){
      int marks = 69;
      
      if(marks < 35)
       System.out.println("You are failed");
      else if( marks < 50)
       System.out.println("You are passed and got third class");
      else if( marks < 60)
       System.out.println("You are passed and got second class");
      else if( marks < 70)
       System.out.println("You are passed and got first class");
      else
       System.out.println("You are passed and got distinction");
     }
    }
    

    Output
    You are passed and got first class
    


    other Operators                                                 Control flow statements                                                 Home

    Tuesday, 4 February 2014

    Other Operators in Java

    Assignment Operator
       Assignment operator is used to assign a value to a variable.
       Syntax
          type variable = value;

       Example
          int a = 10.
          int b = 20

    Java supports compound assignments
       Compound Assignment
          Syntax:
             variable operator= value

          Example:
             lets say
             int a = 10;
             a+=10 evaluates to a=a+10

    Compound Operator Example Description
    += a+=10 a=a+10
    -= a-=10 a=a-10
    *= a*=10 a=a*10
    /= a/=10 a=a/10
    Example Program
    class CompoundAssignment{
     public static void main(String args[]){
      int var1 = 100;
      int sum=10, sub=10, mul=10, div=1000;
    
      System.out.println("sum+var1 is " + (sum+=var1));
      System.out.println("sub-var1 is " + (sub-=var1));
      System.out.println("mul*var1 is " + (mul*=var1));
      System.out.println("div/var1 is" + (div/=var1));
     }
    }
    
             
    Output
    sum+var1 is 110
    sub-var1 is -90 
    mul*var1 is 1000 
    div/var1 is10
    

    The Type Comparison Operator instanceof
    The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

    Example
    class InstanceOfEx{
     public static void main(String args[]){
      Object obj = new Object();
      System.out.println(obj instanceof Object);
      System.out.println(obj instanceof InstanceOfEx);
     }
    }
    
    Output
    true
    false
    
       

    Don't worry much about this program, you will learn about this while discussing about class and object.

    Ternary operator( ?: )
       Returns one of two expressions depending on a condition.

        Syntax
           test ? expression1 : expression2
              Returns expression1 if the “test” condition evaluates to true other wise returns expression 2.

    Example
    class TernaryEx{
     public static void main(String args[]){
      int a = 100;
      
      int flag = a>10 ? 1 : 0;
      System.out.println(flag);
      
      flag = a>1000 ? 1 : 0;
      System.out.println(flag);
     }
    }
    
    Output
    1
    0
    

    Observation
    See the statement “flag = a>10 ? 1 : 0”, a>10 is true, so 1 is returned and assigned to the flag


    Bit wise operators                                                 Control flow statements                                                 Home