Showing posts with label Core Java - Control Statement. Show all posts
Showing posts with label Core Java - Control Statement. Show all posts
It is used in any looping statement. It is also used to continue the execution of the current looping statement and it skips the other statement written in the current block after the continue statement.

If continue will be written in while / do-while block then control will be transferred to the conditional statement.

Syntax for continue keyword :
continue ;   or   continue < label > ;

< label > : It indicates that which loop execution will be continued in the current nesting block.

ab:                                                       // Here ab is a label for " for " loop.
for ( int i = 0 ; i < = 10 ; i ++ ) { }


ab1 :
for ( int i = 0 ; i < = 10 ; i ++ ) { 
ab2 :
for ( int j = 0 ; j < = 10 ; j ++ ) { 
ab3 :
for ( int k = 0 ; k < = 10 ; k ++ ) { 
continue ;                            // Continue the current block k and control transferred to k++.
continue ab3 ;                      // Continue the current block k and control transferred to k++.
continue ab2 ;                     //  Continue the current block j and control transferred to j++.
continue ab1 ;                    //   Continue the current block i and control transferred to i++.
}

Use of continue with label 

Let suppose we have multiple array with some value and we want to find some value i.e 34 is available or not  then we need to go for nested loop.  If we found 34 in any one array and then we need to find other values is the same array, then we can continue with next array and hence we can use here continue with label.
break statement is used to control the transfer out the block without executing the statements written after break statement . It is used either with switch or looping statement.

Syntax of break statement :
break ;  or   break  < label > ;

< label > : It is used with looping statement and with break it indicates which loop execution will be terminated in the current nesting block.

Some of the Invalid statement of the break statement gives compilation error as " unreachable statement "

for ( int i = 0 ; i < = 10 ; i ++ ) {
System.out.println ( " Before break ") ;
break ;
System.out.println (" After break " );   // Compilation error " unreachable statement "
}

while(true) {
break;
System.out.println("After break") ;   // Compilation error " unreachable statement "
}

In the above code compiler is very sure that statement written after break statement will never execute and hence give compilation error as " unreachable statement ".

Above code with some modification which doesn't give any compilation error.

for ( int i = 0 ; i < = 10 ; i ++ ) {
if ( i == 1 )
break ;
System.out.println (" After break " );   
}

In the above code if statement is used and break is used with it, which indicates that there may be chance of executing statements written after break , when if condition will be false. 

while(true) {
int  i = 10 ;
if ( i == 1 )
break;
System.out.println("After break") ;  
i-- ;
}

Above code will not give any error but execute infinitely because " i " is a local variable and it always allocate memory when loop execute. So its value never fall down from 10 .

Use of break with label 

Label can be used with any looping statement i.e for and while loop.for ex-

ab:                                                       // Here ab is a label for " for " loop.
for ( int i = 0 ; i < = 10 ; i ++ ) { }

ab1 :
for ( int i = 0 ; i < = 10 ; i ++ ) { 
ab2 :
for ( int j = 0 ; j < = 10 ; j ++ ) { 
ab3 :
for ( int k = 0 ; k < = 10 ; k ++ ) { 
break ;                                          // Terminate the current block.
break ab3 ;                                  //  Terminate the k block.
break ab2 ;                                 //  Terminate the j block.
break ab1 ;                                //  Terminate the i block.
}

Note: Let suppose we have multiple array with some value and we want to find some value i.e 34 is available or not  then we need to go for nested loop.  If we found 34 in any one array then no need to execute loop further so we can use break with label statement to transfer the control out of all the loop. 
" while " statement is also used as the looping statement in any programming languages. It only works with the condition and we can use updation statement inside the block otherwise it will go for infinite loop if the condition is true.

Syntax of while statement is :
while ( condition ) { } 

Some of the invalid code with the use of while statement


while ( true ) { }
System.out.println (" Error ") ;

Here compiler give compilation error saying " unreachable statement "  because it will go for infinite loop and never execute the statements after while block.

while ( false ){ System.out.println (" Error ") ; }

Here compiler give  " unreachable statement " compilation error and condition is false so block statement will never execute.

while (  ) { } 

The above syntax is incorrect because there must be some condition to be checked while executing while block.

" do-while " looping statement 

" do - while " is same as " while " but the only difference is that in do-while the statement will execute at least once and rest execution will depend upon the condition.

Syntax of do-while statement :
do {
// statement 
< updation > }
while ( condition ) ;

Here it will execute statement of do block even if while condition is false. 
Any looping statement is comprises of there stages i.e
1> Initialization                   2> Conditional                     3> Updation

Initialization : It is the first step while executing any loop and it will be executed once while running the loop.if we declare the variable in the initialization part then the memory will be allocated once and reused many time while looping.

Conditional : It is the 2nd step in looping statement and it will be executed multiple time till the condition false.

Updation : It is the last step which is used after executing loop each time and increment and decrements operators are used for the updation.

Syntax of " for " statement :
for ( initialization ; condition ; updation ) { } 

Note: Any variable declared inside the for block will be treated as local variable and the scope will be within that block only. If we try to print out side the block it will give compilation error " cannot find symbol ".

Why error is like  " cannot find symbol " ?
It is because the memory for the local variable get deallocated at the end of the looping block and again re allocated while executing the looping block again. for ex-

for ( int i =0 ; i <= 0 ; i++ )  {
int   x  = 0 ;                                        // It is a local variable, memory will be created.
}                                                         // After this memory will be de-allocated.
System.out.println("X ="+x) ;      // Give compilation error "cannot find symbol".


Note : We cannot declare multiple variable of different type in the initialization part but it can be of same type. for ex-

for ( int i =0 ,float f = 20.34f ; i < 0 ; i++ ) {} // Invalid 

for ( int i =0 , j = 10, x= 20, ch= 'A'  ; i < 0 ; i++ , x-- , ch *=2 ) {} // valid 

But declaring multiple variable of different type can be achieved by declaring all the different typed variable before the looping statement . for ex-

int  i  ;
float  f1  ;
char  ch  ;
String s ;
for ( i =0 , f1 = 10.2f , ch= 'A', s="java" ; i < 0 ; i++ , f1+=100 , ch *=2,s+=ch ) {}


Some of the situation where you will get compilation error :-

final boolean b = true ;
for ( ; b ; ) { }

Here any statement written after for loop will be unreachable because final boolean variable cannot be modified because of constant property and hence compiler will be sure about infinite loop and give the compilation error as " unreachable statement ".


for ( ; true ; ) { }  // Here also true true indicates that it will be a infinite loop and 
                                statement after for loop will be unreachable.


for ( ;  ; ) { }   // Here also condition is by default true means compilation error as
                         " unreachable ".


for ( ; false ; ) { } // Block statement will never execute because of false condition so 
                               compilation error as " unreachable ".


Same situation as above with little modification to avoid compilation error :-

boolean b = true ;
for ( ; b ; ) { }            // No compilation error as b can be modified as false within for block.

for ( ; true ; ) { break; } // Here compiler is sure about infinite loop but still loop can be                                                terminated at any point of time by the use of break statement
                                        and
 hence control will be at the statement after for block. 



Same situation looks like infinite but in real it is a finite statement:-

int  x  =  56789 ;
for ( ; x > 0 ; x++ ) { } 

It looks like infinite loop but in java there is a concept of wrapping around that means after reaching the maximum value if int type it will wrap to tits minimum value(65535) i.e negative value and hence condition will be false at that time.


for ( int i=10 ; i > 10 ; i-- ) ;  // This statement is same as for ( int i=10 ; i > 10 ; i-- ) { }

The above statement is terminated with semi-colon that means it will execute till the condition get false.

for (int i=10 ; i > 10 ; i--); {
System.out.println ("Not a part of for loop");  
}

Here in the above code don't think that print statement is a part of for loop because ' for' loop is terminated with semi-colon that means it will self executed till condition get false and this print will execute only once as not a part of ' for ' loop.



Like this there are many condition give will make you surprised so keep experimenting with your code.
In programming languages switch is a type of conditional control statement. It has one switch statement and many cases with one default statement. Depending upon the switch value it matches with the cases value and execute the matching cases and if any break statement is used with the case statement then control will be out of the switch block and if there is no break statement then it will execute rest all of the cases as well. If non of the cases matches then it will execute the default block . Use of break in switch is optional.

Syntax for switch statement is
switch ( value ) {
case < val > :  statements ;
case < val > : statement ;
..............
default : statement ;
}


The type of the value / variable specified as the argument of the switch should be of int type or its compatible type int ,  byte , short , char but should not be wider type of int type like long. 


String cannot be used with switch but from java 7 we can be able to string value as well and from java 5 we can be able to use enum value as well.

Note : Be careful that no two cases defined in a switch block is same in any way.
for ex -

int   x  =  65 ;
switch ( x ) {
case 65 : System.out.println (" 65 ") ;
case 'A': System.out.println (" A " ) ;
default: System.out.println ("default block ") ;

In the above code both 65 and A represent the same value i.e 65 so it will give a compilation error saying " duplicate case label " .


Note: The type of the case value should be assignment compatible with the switch value. All the cases value must be in rage of the variable used switch variable.

for ex-

byte  x  =  65 ;
switch ( x ) {
case 65 : System.out.println (" 65 ") ;
case 129: System.out.println (" Not in range of byte " ) ;
default: System.out.println ("default block ") ;


In the above code  switch variable is of type byte and one of the case value is 129 which is not in range of byte value. So it will give compilation error saying " possible loss of precision " .



Note : We can use case a variable as a case value but it should be a constant .

for ex-

byte  y  =  65 ;
final int  x  = 65;
switch ( x ) {
case 65 : System.out.println (" 65 ") ;
default: System.out.println ("default block ") ;

Here in the above code there are two variable holding same value but y is non-constant used as switch value and x is a constant used in the case value. In java in case of constants, compiler will place the direct value instead of using variable.
If we use any variable containing non-constant value and we used as a case value then it will give compilation error saying " constant expression required " .

Important points regarding switch statement 

1> Default statesmen is optional to use but if used then there should be only one default statement. And it can be used any where in the switch block i.e between the cases, before all the cases or it may be after all the cases.

2> JVM will first search for the matching case value and if found any such case then execution will start form that point only and if break is used in that case then after executing statements control will be transferred out of the switch statement.

3> If no matching case found and if default statement available then execution will start form that default block. 

4> For terminating the execution of case statements at any point while executing matched case statements  use break statement. 
As we know that " if " is a conditional control statement and maximum it will execute once depending upon the condition check. If the condition is true then it will execute once and if false then will not execute at even for a single time.
It is classified into three type i.e
1> if statement (only if)
2> if-else statement
3> if-else-if statement or nested if-else statement

" if " statement  

As mentioned above it is a conditional statement and can able to execute the code maximum for one time only. Condition used with " if " statement must return boolean value because the code written inside the if statement will be executed either on true or  false condition only. If block can have no statement, one statement or multiple statement as per user requirement.
Syntax for if statement :

if ( condition ){                                             if ( condition )
// statements                                                 // statement  ---( Part of if )
}                                                                    // statement   ---( Not a part of if )
                                                       
for ex-                                                                      
int  i = 1 ;
if ( i > 0 ) { System.out.println(" Output :" + i ) ; 

In the above code ( i > 0) is true so the code written withing {} will be executed once.

Note: Condition may a direct value i.e true or false, or using relational operator which always return boolean value or may be a method which must return boolean value. 

Lets discuss some conceptual and useful codes using " if " statement. 

if ( 1 > 0 ) 
int   x = 10 ;

Here variable declaration x is a first statement and is a local variable so other statement will never be the part of " if " hence there is no use of initializing and declaring local variable as its first statement because it cannot be used other the if block.

if ( 1 > 0 ) {  int   x = 10 ; }

Above code is same as previous one but with curly bracket {}. This will compile successfully because curly bracket indicates that there may be chance of declaring multiple statement but in case of above code compile is very sure about that statement.

int   var ;                                                   int   var ;
if ( true ) {  var =  90  ;  }                          if ( false ) {  var =  90  ;  }
System.out.println ( var );                        System.out.println ( var );   

When we are initializing any uninitialized variable in the if block then the compiler must be sure that in all the condition the variable must be initialized. But here in the 2nd code above var is never be initialized because if will never as condition is false.        

So i discussed few code here like this there are multiple so keep experimenting like this.

" if - else " statement 

It a type of " if " control statement and here else indicate " if- not " that means if " if " block is false then control will go the else block. And both if and else block can have multiple statements and if we are using only single statement for if and else then there is no need to indicating any curly bracket.

Syntax for if statement :

if ( condition ){                                          if ( condition )
       // statements                                           // statement  ( must be a single statement)
}                                                                 else
else {                                                            // statement 
     // statements  
}

" if - else-if " statement ( nested if-else )

if - else - if  is otherwise called as nested if-else block because we can have infinite series of if-else block but condition else must be followed for every else, if your code will have any if without else then it will give compilation error that " else without if ". So must take care of if-else combination while using it.

Syntax for if statement :

if (condition ){ // statements }                                                          
else if (condition) { // statements }
else if (condition ) // statements }
else { // statement }

In the if - else - if statement we have multiple with multiple condition and if any the condition matched then the corresponding block will execute and after executing the control will be transferred to the proceeding statement after nested if-else.

Here is some invalid declaration of if-else statement.

if ( true ) {           if( true )          if ( true )            
else { }                else { }           // statement
}                                                 // statement 
                                                   else { } 

The following above codes will give the compilation error saying " Else without if ".

Here is some of the valid declaration of if-else statement

if ( true ) ;       if ( true )                            if ( true ) { }
else { }               // single statement          else if( true )
                        else 
                           // single statement 



Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic