Join Active NET only to learn full-pledged java

Where you can easily download java e-books such as

CORE JAVA, ADVANCED JAVA(JDBC, Servlets, Jsp and Jstl), J2EE, STRUTS, HIBERNATE and SPRING

ANT and log4j

RMI, JNDI and JMS

HTML, CSS, XML and JAVA SCRIPT

OOAD and DESIGN PATTERNS

and many more......................................

Search the web pages from here

Control Statements


                                                          
              Control Statements


ü      There are two most commonly used statements in any programming language, those are as follows:

·         Sequential statements - These are the statements that are executed one by one.
·         Control statements - These are the statements that are executed  randomly and
                                                    repeatedly.

ü      For example: System.out.println (Madhava);
                            x = y+z;
                            System.out.println(x);

ü      These statements are executed by JVM one by one in a sequential manner. So they are called sequential statements. But this type of sequential execution is useful only to write simple programs. If we want to write better and complex programs, we need better control on the flow of execution. This is possible by using control statements.

ü      A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program.

ü      Java’s program control statements can be put into the following categories:

·         Selection statements
·         Iteration statements
·         Jump statements

Java’s Selection Statements

ü      Java supports two selection statements: if and switch. These statements allow us to control the flow of our program’s execution based upon conditions known only during run time.

if…else statement:

ü      This statement is used to perform a task depending on whether a given condition is true or false. Here is the general form of the if statement:

if (condition)
      statement1;
            else
                 statement2;
      Here, each statement may be a single statement or a compound statement enclosed in
      curly braces (that is, a block). The condition is any expression that returns a boolean
      value.
ü      The if…else works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 is executed. The curly braces are unnecessary if only a single statement is being repeated.

Nested ifs:

ü      If we write one if statement within another if statement then those statements are called nested ifs.

ü      Nested ifs are very common in programming. When we use nested ifs, the main thing to remember is that an else statement always refers to the nearest if statement.

ü      For example:  if(i == 10)
    {
       if(j < 20)
a = b;
                               if(k > 100)  
c = d;                // this if is
                               else a = c;             // associated with this else
                            }
                            else a = d; // this else refers to if(i = = 10)

if-else-if Ladder:

ü      A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.

ü      The general form of if-else-if ladder is as follows:

if(condition)
    statement;
            else if(condition)
                statement;
            else if(condition)
                statement;
              ...
            else
                statement;

Program: Demonstrate if-else-if statements.
class IfElseIf
{
   public static void main(String args[])
   {
     int month = 4; // April
     String season;
                 if(month == 12 || month == 1 || month == 2)
                       season = "Winter";
                 else if(month == 3 || month == 4 || month == 5)
                       season = "Spring";
                 else if(month == 6 || month == 7 || month == 8)
                       season = "Summer";
                 else if(month == 9 || month == 10 || month == 11)
                       season = "Autumn";
                 else
                       season = "Bogus Month";
                 System.out.println("April is in the " + season + ".");
               }
             }

Output: April is in the Spring.

switch statement:

ü      When there are several options and we have to choose only one option from the available ones, we can use switch statement.

ü      The general form of a switch statement:

switch (variable)
{
                case value1: statements 1
                                     break;
                case value2: statements 2
                                     break;
                       …….
                       …….
               case valueN: statements N
                                     break;
               default: // default statement
            }
      Here, variable must be of type byte, short, int, or char. Depending on the value of
      the variable, a particular statement will be executed.

      If the variable value is equal to value1, statements1 will be executed. If the variable
      value is equal to value2, statements2 will be executed and so on.

      If the variable value is not equal to value1,value2,…then none of the  statements will
      be executed. In this case, default clause will be executed.

Program: To display a color name depending on color value
            class SwitchDemo
            {
               public static void main(String args[])
               {
                  char color = g;
                  switch(color)
                  {
                      case r: System.out.println(Red);
                      case g: System.out.println(Green);
                      case b: System.out.println(Blue);
                      case w: System.out.println(White);
                      default : System.out.println(No color);
                   }
                }
             }
Output: C:\Madhava> java Switch
             Green
             Blue
             White
             No color

ü      The output of the program is not expected. We expected that it would  display Green, but it is displaying all colors starting from the Green color. The solution it come out of the switch statement is, after displaying Green, use break statement.

ü      The solution to the previous program is:

Program:  To display a color name depending on color value
      class SwitchDemo
            {
               public static void main(String args[])
               {
                  char color = g;
                  switch(color)
                  {
                      case r: System.out.println(Red);
                                    break;
                      case g: System.out.println(Green);
                                    break;
                      case b: System.out.println(Blue);
                                    break;
                      case w: System.out.println(White);
                                    break;
                      default : System.out.println(No color);
                   }
                }
             }
Output: C:\Madhava> java Switch
              Green

Note: String can not be used with switch statement
          String str = “Madhava”;
          switch(str)  // invalid

Nested switch Statements:

ü      We can use a switch statement within another switch statement. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch.

ü      For example, the following fragment is perfectly valid:

switch(count)
     {
case 1: switch(target)  // nested switch
           {
                         case 0: System.out.println("target is zero");
                                     break;
                         case 1: // no conflicts with outer switch
                                     System.out.println("target is one");
                                     break;
                       }
                       break;
            case 2: // ...
      Here, the case 1: statement in the inner switch does not conflict with the case 1:
      statement in the outer switch. The count variable is only compared with the list of
      cases at the outer level. If count is 1, then target is compared with the inner list
      cases.

Java’s Iteration Statements

ü      Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination condition is met.

while loop:

ü      The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling expression is true.

ü      Here is its general form:
while(condition)
{
    // body of loop
}
      The condition can be any Boolean expression. The body of the loop will be executed
      as long as the conditional expression is true. When condition becomes false, control
      passes to the next line of code immediately following the loop. The curly braces are
      unnecessary if only a single statement is being repeated.

Program: To display numbers from 1 to 10
            class WhileDemo
            {
               public static void main(String args[])
               {
                  int x = 1;
                  while(x<=10)  // while(x<=10); valid in java, but program doesn’t generate output
                  {
                     System.out.println(x);
                     x++;
                  }
               }
             }
Output: C:\Madhava>javac WhileDemo.java
             C:\Madhava>java  WhileDemo
               1
               2
               3
               4
               5
               6
               7
               8
               9
               10

ü      The body of the while (or any other of Java’s loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java.

Program: To display mid point between two numbers
class NoBody
{
  public static void main(String args[])
 {
                int i, j;
                i = 100;
                j = 200;
                // find midpoint between i and j
                while(++i < --j) ; // no body in this loop
                System.out.println("Midpoint is " + i);
              }
            }
Output: Midpoint is 150

ü      Observe that the above program, while loop consists semicolon at the end. Only in this case the program will be executed. If the while loop contains body and semicolon, then that program will be compiled without causing any errors. But the program does not generate any output because the while loop repeatedly checks its condition and it does not enter into the body of the while loop. Because it contains semicolon.
do-while:

ü      As we know, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with.

ü      To do this, Java supplies a loop called: do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

ü      The general form of do-while is:
            do
           {
              // body of loop
           } while (condition);

ü      Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.

Program: To display numbers from 1 to 10
            class DoWhileDemo
            {
               public static void main(String args[])
               {
                  int x = 1;
                   do
                  {
                     System.out.println(x);
                     x++;
                  }while(x<=10) 
               }
             }
Output: C:\Madhava>javac DoWhileDemo.java
             C:\Madhava>java  DoWhileDemo
               1
               2
               3
               4
               5
               6
               7
               8
               9
               10



for loop:

ü      The for loop is same as while and do-while loops, but it is more compact syntactically. The for loop executes a group of statements as long as a condition is true.

ü      The general form of the for statement is:

for(initialization; condition; iteration)
{
   // body
            }
      If only one statement is being repeated, there is no need for the curly braces.

ü      The for loop operates as follows:

  • When the loop first starts, the initialization portion of the loop is executed.
  • It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression.
  • If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable.
  • The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

Program: To display numbers from 1 to 8
            class ForDemo
            {
               public static void main(String args[])
               {
                  for( int i=1; x<=8;x++)
                  {
                     System.out.println(x);
                  }
               }
             }

Output: C:\Madhava>javac ForDemo.java
              C:\Madhava>java  ForDemo
               1
               2
               3
               4
               5
               6
               7
               8
Using the Comma with in for loop:

ü      There will be times when you will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:

Program:
class Sample
{
  public static void main(String args[])
  {
                 int a, b;
                 b = 4;
                 for(a=1; a
                {
                   System.out.println("a = " + a);
                   System.out.println("b = " + b);
                   b--;
                }
              }
            }

ü      As you can see, the loop is controlled by the interaction of two variables. Since the loop is governed by two variables, it would be useful if both could be included in the for statement, itself, instead of b being handled manually.

ü      Fortunately, Java provides a way to accomplish this. To allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

Program: Using the comma.
class Comma
{
  public static void main(String args[])
 {
                int a, b;
                for(a=1, b=4; a, b--)
                {
                    System.out.println("a = " + a);
                    System.out.println("b = " + b);
                }
              }
            }
Output: C:\Madhava> java Comma
  a = 1
  b = 4
  a = 2
              b = 3

Nested for loops:

ü      When we write a for loop within another for loop. Such loops are called nested for loops.

Program: Demonstrate nested for loops
class Nested
{
   public static void main(String args[])
  {
                 int i, j;
                 for(i=0; i<5; i++)
                {
                   for(j=i; j<5; j++)
                      System.out.print("*");
                  System.out.println();
                 }
               }
             }

Output: C:\Madhava>javac Nested.java
               C:\Madhava>java  Nested
               **********
               *********
               ********
               *******
               ******
  
Java’s Jump Statements:

ü      Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.

Using break:

ü      The break statement can be used in three ways:
  • break is used inside a loop to come out of it.
  • break is used inside the switch block to come out of it.
  • break can be used in nested blocks to go to the end of a block

      We have already observed the second use of break statement. Let us see first and last
      one.

 Using break to Exit a Loop:

ü      By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.

ü      When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.

Program1: Using break to exit a loop.
           class BreakLoop
           {
  public static void main(String args[])
  {
    for(int i=0; i<100; i++)
   {
                  if(i == 5)
                     break; // terminate loop if i is 5
                  System.out.println("i: " + i);
               }
               System.out.println("Loop complete.");
             }
            }
Output: i: 0
 i: 1
 i: 2
 i: 3
 i: 4
             Loop complete.

Program2: Using break to exit a while loop.
class BreakLoop2
{
               public static void main(String args[])
              {
                int i = 0;
                while(i < 100)
                {
                   if(i == 5)
                          break; // terminate loop if i is 5
                   System.out.println("i: " + i);
                   i++;
                 }
                  System.out.println("Loop complete.");
               }
             }


Using break inside nested blocks:

ü      When used inside a set of nested loops, the break statement will only break out of the innermost loop.

Program3: Using break with nested loops.
class BreakLoop3
{
               public static void main(String args[])
               {
                  for(int i=0; i<3; i++)
                 {
                     System.out.print("Pass " + i + ": ");
                     for(int j=0; j<100; j++)
                    {
                         if(j == 10)
                                break; // terminate loop if j is 10
                         System.out.print(j + " ");
                    }
                    System.out.println();
                  }
                   System.out.println("Loops complete.");
                }
             }
Output: Pass 0: 0 1 2 3 4 5 6 7 8 9
              Pass 1: 0 1 2 3 4 5 6 7 8 9
              Pass 2: 0 1 2 3 4 5 6 7 8 9
              Loops complete.

Using break as a form of goto:

ü      Java does not have a goto statement, because goto statements lead to confusion for a programmer, especially in case of large programs.

ü      If several goto statements are used, the programmer would be perplexed (confusion) while understanding the flow from where to where the control is jumping.

ü      To handle such situations, Java defines an expanded form of the break statement.

break label;

      Here, label is the name of a label that identifies a block of code.

ü      When this form of break executes, control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block.

 Program4: Using break as a civilized form of goto.
class Break
{
  public static void main(String args[])
 {
               boolean t = true;
               first: {
                   second: {
                          third: {
                                  System.out.println("Before the break.");
                                  if(t)
                                     break second; // break out of second block
                                  System.out.println("This won't execute");
                          }
                          System.out.println("This won't execute");
                  }
                  System.out.println("This is after second block.");
               }
             }
            }
Output: Before the break.
               This is after second block.

ü      Keep in mind that we cannot break to any label which is not defined for an enclosing block. For example, the following program is invalid and will not compile:

Program5: This program contains an error.
class BreakErr
{
               public static void main(String args[])
               {
                   one: for(int i=0; i<3; i++)
                          {
                              System.out.print("Pass " + i + ": ");
                          }
                   for(int j=0; j<100; j++)
                  {
                      if(j == 10)
                          break one; // WRONG
                      System.out.print(j + " ");
                  }
               }
            }
Since the loop labeled one does not enclose the break statement, it is not possible to
transfer control to that block.

Using continue:

ü      continue is used inside a loop to repeat the next iteration of the loop. When continue is executed, subsequent statements in the loop are not executed and control of execution goes back to the next repetition of the loop.

ü      In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.

ü      In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed.

Program1: Demonstrate continue.
class Continue
{
               public static void main(String args[])
              {
                 for(int i=0; i<10; i++)
                 {
                    System.out.print(i + " ");
                    if (i%2 == 0) continue;
                    System.out.println("");
                 }
               }
             }
This code uses the % operator to check if i is even. If it is, the loop continues without
printing a newline. Here is the output from this program:

0 1
2 3
4 5
6 7
8 9

Program2: Using continue with a label.
class ContinueLabel
{
  public static void main(String args[])
 {
                 outer: for (int i=0; i<10; i++)
                 {
                    for(int j=0; j<10; j++)
                    {
                       if(j > i)
                       {
                          System.out.println();
                          continue outer;
                       }
                       System.out.print(" " + (i * j));
                    }
                  }
                  System.out.println();
               }
             }
The continue statement in this example terminates the loop counting j and continues
with the next iteration of the loop counting i.

Here is the output of this program:
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 8

return Statement:

ü      We know that a method is a function written inside a class. It contains a group of statements and performs a task or processing. It means a method is useful to perform certain calculations or processing of data in the program to yield expected results. Methods can accept the data from outside for their processing and they can also return the results.

ü      A method is executed when called from another method. The first method that is executed in a Java program by the JVM is main( ) and hence if we want to execute any other method, we should call it from main( ).

ü      return statement is used to return a value to the caller method. The return statement returns only one value at a time.

ü      When a return statement is encountered, compiler transfers the control of the program to the caller method. The syntax of return statement is as follows:

return (variable name); or return variable name;
      
      Here, parenthesis is optional.

Program: To find out the sum of two variables.
      class ReturnDemo
      {
            public static void main(String args[])
           {
              int res=ReturnDemo.sum(20,10);
              System.out.println("Sum is:"+res);
           }
           static int sum(int x,int y)
           {
               return x+y;
           }
       } 
Output: Sum is: 30
       
Technical Interview Questions and Answers:

1. What are control statements?
Ans: Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution. They are useful to write better and complex programs.

2.  Out of do-while and while – which loop is efficient?
Ans: In a do-while loop, the statements are executed without testing the condition, the first time. From the second time only the condition is observed. This means that the programmer does not have control right from the beginning of its execution.

         In a while loop, the condition is tested first and then only the statements are executed. This means it provides better control right from the beginning. Hence, while loop is more efficient than do-while loop.

3. What is a collection?
Ans: A collection represents a group of elements like integer values or objects. Examples for collections are arrays and java.util classes (Stack, Linked List, Vector, etc.)

4. Why goto statements are not available in Java?
Ans: goto statements lead to confusion for a programmer. Especially, in large program, if several goto statements are used, the programmer would be perplexed (confusion) while understanding the flow from where to where the control is jumping.

5. What is the difference between break and continue?
Ans: The break keyword halts (interrupt) the execution of the current loop and forces control out of the loop. The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.

6. Can a for statement loop indefinitely?
Ans: Yes,  Ex : for(;;);

7. What is the difference between a while statement and a do- while statement?
Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do-while statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do-while statement will always execute the body of a loop at least once.
                                                                               - J Madhava Rao