www.000webhost.com
Core Java test2



Continue/ Next Page
Previous Page

Flow control in Java

Core Java

Flow Control in Java :-


There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

FlowControl_basic

Sequential Flow Control :-



A program is a sequence of instructions. Sequential flow is the most common and straight-forward, where programming statements are executed in the order that they are written - from top to bottom in a sequential manner.


Conditional Flow Control :-



There are a few types of conditionals, if-then, if-then-else, nested-if (if-elseif-elseif-...-else), switch-case, and conditional expression.

COntrolFlowInJava
	if (price >= 50)
	   System.out.println("Discount 5%");   // Only one statement, can omit { } but NOT recommended

	else {                           // More than one statements, need { }
	   System.out.println("No Discount");
	   System.out.println("Get some more stuff for Discount !");
	}

swtich-case-default :-



"switch-case" is an alternative to the "nested-if". In a switch-case statement, a break statement is needed for each of the cases. If break is missing, execution will flow through the following case.
You can use an int, byte, short, or char variable as the case-selector, but NOT long, float, double and boolean. (JDK 1.7 supports String as the case-selector)


Conditional Operator (? :) :-



A conditional operator is a ternary (3-operand) operator, in the form of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and returns the value of trueExpr or falseExpr.

Examples on Conditional Operator in java

//Syntex -
//booleanExpr ? trueExpr : falseExpr

	public class ConditionalOperator {

	   public static void main(String args[]){
	      int a , b;
	      a = 10;
	      b = (a == 1) ? 20: 30;
	      System.out.println( "Value of b is : " +  b );

	      b = (a == 10) ? 20: 30;
	      System.out.println( "Value of b is : " + b );
	   }
	}

		OutPut :-
		Value of b is : 30
		Value of b is : 20

Loop Flow Control :-



loops: for, while-do, and do-while.

LoopsAndFlowInJava

The difference between while-do and do-while lies in the order of the body and condition. In while-do, the condition is tested first. The body will be executed if the condition is true and the process repeats. In do-while, the body is executed and then the condition is tested. Take note that the body of do-while will be executed at least once vs. possibly zero for while-do. Similarly, the for-loop's body could possibly not executed.


Example of While loop in Java

//	Syntex
//		while(condition)
//  		{
//  			statements;
//  		}

	public class table{
		  public static void main(String[] args){
		  int n = 2;
		  int i = 1;
		  System.out.println("The table of "+n+" = ");
		 	 while(i<=10)
			  {
				  int t = n * i;
				  System.out.println(t);
				  i++;
			  }
		 }
	}


Example of Do-While loop in Java


	public class DoWhileExample {

	   public static void main(String args[]){
	      int x = 10;

	      do{
	         System.out.print("value of x : " + x );
	         x++;
	         System.out.print("\n");
	      }while( x < 20 );
	   }
	}


Example of for loop in Java


	public class ForLoopExample {

	   public static void main(String args[]) {

	      for(int x = 10; x < 20; x = x+1) {
	         System.out.print("value of x : " + x );
	         System.out.print("\n");
	      }
	   }
	}

	Output is :-
	value of x : 10
	value of x : 11
	value of x : 12
	value of x : 13
	value of x : 14
	value of x : 15
	value of x : 16
	value of x : 17
	value of x : 18
	value of x : 19


Example of for-each loop in Java

It shall be read as "for each element in the array...". The loop executes once for each element in the array, with the element's value copied into the declared variable. The for-each loop is handy to transverse all the elements of an array or a collection. It requires fewer lines of codes, eliminates the loop counter and the array index, and is easier to read.
However, for array of primitive types (e.g., array of ints), it can read the elements only, and cannot modify the array's contents.
This is because each element's value is copied into the loop's variable (pass-by-value), instead of working on its original copy.


	public class ForEachLoopExample
	{
	   		public static void main(String args[]){
	      	int [] numbers = {10, 20, 30, 40, 50};

	      	for(int x : numbers ){
	        System.out.print( x );
	        System.out.print(",");
	      	}

	      	System.out.print("\n");
	      	String [] names ={"java", "essential", "Live", "now"};
		    for( String name : names )
		    {
		        System.out.print( name );
		        System.out.print(",");
			}
		}
	}

	Output :-
	10,20,30,40,50,
	java,essential,Live,now,


break and continue in Java



These are use for Interrupting loop flow - The statements break and continue in Java alter the normal control flow of compound statements.



Break leaves a loop, continue jumps to the next iteration.


Example of "break" and "continue" in Java :-




non-prime numbers in java : Example


	// List all non-prime numbers between 2 and an upperbound
	public class NonPrimeListExample {
	   public static void main(String[] args) {
	      int upperbound = 100;
	      for (int number = 2; number <= upperbound; ++number) {
	         // Not a prime, if there is a factor between 2 and sqrt(number)
	         int maxFactor = (int)Math.sqrt(number);
	         for (int factor = 2; factor <= maxFactor; ++factor) {
	            if (number % factor == 0) {   // Factor?
	               System.out.println(number + " is NOT a prime");
	               break;   // A factor found, no need to search for more factors
	            }
	         }
	      }
	   }
	}


Prime numbers in Java : Example


// List all prime numbers between 2 and an upperbound
public class PrimeList {
   public static void main(String[] args) {
      int upperbound = 100;
      for (int number = 2; number <= upperbound; ++number) {
         // Not prime, if there is a factor between 2 and sqrt of number
         int maxFactor = (int)Math.sqrt(number);
         boolean isPrime = true;
         int factor = 2;
         while (isPrime && factor <= maxFactor) {
            if (number % factor == 0) {   // Factor of number?
                isPrime = false;
            }
            ++factor;
         }
         if (isPrime) System.out.println(number + " is a prime");
      }
   }
}


Example of break and continue in java


public class MysterySeries {
   public static void main(String[] args) {
      int number = 1;
      while(true) {
         ++number;
         if ((number % 3) == 0) continue;
         if (number == 133) break;
         if ((number % 2) == 0) {
            number += 3;
         } else {
            number -= 3;
         }
         System.out.print(number + " ");
      }
   }
}


Example of Labeled break in Java


public class TestLabeledBreak {
   public static void main(String[] args) {
      int[][] testArray = {
         {1, 2, 3, 4},
         {4, 3, 1, 4},
         {9, 2, 3, 4}
      };

      int magicNumber = 8;
      boolean found = false;
      mainLoop:
      for (int i = 0; i < testArray.length; ++i) {
         for (int j = 0; j < testArray[i].length; ++j) {
            if (testArray[i][j] == magicNumber) {
               found = true;
               break mainLoop;
            }
         }
      }
      System.out.println("Magic number " + (found ? "found" : "NOT found"));
   }
}

For method overloading and Overriding please referer OOP concept


Continue/ Next Page
Previous Page




Click here to access OOp's Concept

feel free to ask any of your doubts