Java Statements Tutorial – Java Control Flow Statements Tutorial For Beginners

Java Statements Tutorial – Java Control Flow Statements Tutorial For Beginners 2018 from Coding compiler. Here you will learn about Java if statement, for statement, while statement, break statement, continue statement and comment statement. Let’s start learning Java programming.

Java Statements Tutorial – Java Control Flow Statements

Here we learn more about Java statements, Java control flow statements.

  1. Java If statement
  2. Java For statement
  3. Java while statement
  4. Java Break statement
  5. Java Continue statement
  6. Java comment statement

Java Tutorial – Java If Statement

A Java if statement is used to execute a block of code based on conditions.

Java If statement

Here is the simplest form of a Java if statement:

If (condition)
  Statement

The condition is a boolean expression. If the condition is true then the statement is executed.

If condition is false, then bypass the statement.

The following code outputs a message integer based on the value of an. It uses an if statement to perform the check.

Public class Main {

 Public static void main(String args[]) {
    int num = 99;
    if (num < 100) {
     System.out.println( “num is less than 100” );

   }
 }
}

Java If Statement Example

The If statement is often used to compare two variables. The following code defines two variables, and it uses the if statement to compare them and print out the message.

Public class Main {

 Public static void main(String args[]) {
    int x, y;

   x = 10;
   y = 20;

   If (x < y){
     System.out.println( “x is less than y” );
   }

   x = x * 2;
   If (x == y){
     System.out.println( “x now equal to y” );
   }

   x = x * 2;
   If (x > y){
     System.out.println( “x now greater than y” );
   }

   If (x == y){
     System.out.println( “===” );
   }
 }
}

The output generated by this program is as follows:

Java If Statement Example – 2

We can also use Boolean values to control the if statement. The boolean value of the variable is sufficient to control the if statement.

Public class Main {
  public static void main(String args[]) {
    boolean b;
   b = false;
   If (b) {
     System.out.println( “This is executed.” );
   } else {
     System.out.println( “This is NOT executed.” );
   }

 }
}

There is no need to write the following if statement:

If (b == true) …

The output generated by this program is as follows:

Java if else statement

The if statement is a conditional branch statement. We can add else statements in the if statement.

Here is the if-else general form of the statement:

If (condition)
  Statement1;
Else
  Statement2;

The else clause is optional. Each statement can be a single statement or a compound statement enclosed in braces (a block). Only one statement can appear directly if or else after. To include more statements, you need to create a block, as in this fragment.

The following example shows how to use a Java if else statement.


Public class Main {
  public static void main(String[] argv) {
    int i = 1;

   If (i > 0) {
     System.out.println( “Here” );
     i -= 1;

   } else
     System.out.println( “There” );
 }
}
 ]]>

Output:

It is good to include curly braces when using statements, even if there is only one statement in each clause.

Java if else ladder statement

The if else ladder statement is used to work under multiple conditions.

The if-else-if trapezoid is as follows:

If (condition)
  Statement
Else if (condition)
  Statement
Else if (condition)
  Statement
.
.
Else
  Statement

Here is a if-else-if program that uses ladder diagrams.


Public class Main {
  public static void main(String args[]) {
    int month = 4;
   String value;
   If (month == 1 )
     Value = “A” ;
    else if (month == 2)
     Value = “B” ;
    else if (month == 3)
     Value = “C” ;
    else if (month == 4)
     Value = “D” ;
    else
     value = “Error” ;

   System.out.println( “value = ” + value);
 }
}

Here is the output produced by the program:

Java nested if statement

Nesting if is a if statement in another if statement or else.

The following code uses a nested if statement to compare values.


Public class Main {
  public static void main(String[] argv) {
    int i = 10;
    int j = 4;
    int k = 200;
    int a = 3;
    int b = 5;
    int c = 0;
    int d =0;
    If (i == 10) {
      if (j < 20){
       a = b;
     }
     If (k > 100){
       c = d;
     }
     Else {
       a = c;
     }
   } else {
     a = d;
   }
   System.out.println( “a = ” + a);
   System.out.println( “b = ” + b);
   System.out.println( “c = ” + c);
   System.out.println( “d = ” + d);
   
 }
}

Java Tutorial – Java For Statement

 

Java for loop statements provide a powerful way to write loop statements.

The simplest form of a for loop is as follows:

for(initialization; condition; iteration)
   statement;

The Java for loop statement has three parts:

  • Initialization sets the loop control variable to the initial value.
  • The condition is a Boolean expression that tests the loop control variable. If the condition is true, the for loop continues to iterate. If condition is false, the loop terminates.
  • The iteration determines the change of the loop control variable at each loop iteration.

Here is a short program that illustrates the for loop. The loop control variable that is initialized to zero initialization. At the beginning of each iteration, conditional testing. If the result of the test is true, execute the statement and then execute the iterative part of the loop. This process continues until the conditional test is .x 10println()false

public class Main {
 public static void main(String args[]) {
   int i;

   for (i = 0; i < 10; i = i + 1)
     System.out.println(“This is i: ” + i);
 }
}

Java For Statement Example

The following code again writes the code logic from above, but the loop reverses:


public class Main {
 public static void main(String args[]) {
   for (int n = 10; n > 0; n–)
     System.out.println(“n:” + n);
 }
}  ]]>

Java For Statement Example – 2

Here is a program that uses a for loop statement to test prime numbers.


public class Main {
 public static void main(String args[]) {
   int num;
   boolean isPrime = true;
   num = 50;
   for (int i = 2; i <= num / 2; i++) {
     if ((num % i) == 0) {
       isPrime = false;
       break;
     }
   }
   if (isPrime)
     System.out.println(“Prime”);
   else
     System.out.println(“Not Prime”);

 }
}

Java For Loop Example – 3

Java allows two or more variables to control the for loop. And you can include multiple statement for loops in the initialization and iteration sections. Each statement is separated from the next statement by a comma. Here is an example:


public class Main {
 public static void main(String args[]) {

   for (int a = 1, b = 4; a < b; a++, b–) {
     System.out.println(“a = ” + a);
     System.out.println(“b = ” + b);

   }
 }
}

Java For Loop Example – 4

forThe three parts can be used for any purpose and part of the for loop can be empty.


public class Main {
 public static void main(String args[]) {
   int i = 0;
   boolean done = false;
   for (; !done;) {
     System.out.println(“i is ” + i);
     if (i == 10)
       done = true;
     i++;

   }
 }
}

Java For Loop Example – 5

for loops can be nested to generate powerful logic. For example, we can use nested for loops to iterate over a two-dimensional array. For example, here is a program for nesting for loops:


public class Main {
 public static void main(String args[]) {
   for (int i = 0; i < 10; i++) {
     for (int j = i; j < 10; j++)
       System.out.print(“.”);
     System.out.println();
   }
 }
}

The output produced by this program is as follows:

Java for each statement

The for each loop iterates over the elements in a sequence without using a loop counter.

The syntax for the for each loop is:

for (type variable_name:array){
      
}

The following code shows how to use for each loop.

public class Main {
 public static void main(String args[]) {
   String[] arr = new String[]{“www.w3cschool.cn”,”a”,”b”,”c”};
   for(String s:arr){
     System.out.println(s);
   }
 }
}

Java For Each Statement Example – 6

The following code uses a for-each style loop to iterate over a two-dimensional array.

public class Main {
 public static void main(String args[]) {
   int sum = 0;
   int nums[][] = new int[3][5];
   for (int i = 0; i < 3; i++){
     for (int j = 0; j < 5; j++){
       nums[i][j] = (i + 1) * (j + 1);
     }
   }
   // use for-each for to display and sum the values
   for (int x[] : nums) {
     for (int y : x) {
       System.out.println(“Value is: ” + y);
       sum += y;
     }
   }
   System.out.println(“Summation: ” + sum);
 }
}

The output of this program is as follows:

Java For Each Statement Example – 7

for-each style loops are very useful when searching for elements in an array.

public class Main {
 public static void main(String args[]) {
   int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
   int val = 5;
   boolean found = false;
   // use for-each style for to search nums for val
   for (int x : nums) {
     if (x == val) {
       found = true;
       break;
     }
   }
   if (found)
     System.out.println(“Value found!”);
 }
}

Java Tutorial – Java While Statement

 

A while loop repeats a statement or block when its control condition is true.

Java while loop

This is its general form:

while(condition) {
  // body of loop
}

  • The condition can be any Boolean expression.
  • As long as the condition is true, the body of the loop will be executed.
  • Braces are unnecessary if only a single statement is repeated.

Here is a while loop, reducing from 10, printing ten lines of “tick”:


public class Main {
 public static void main(String args[]) {
   int n = 10;
   while (n > 0) {
     System.out.println(“n:” + n);
     n–;
   }
 }
}

Java While Loop Example

The following code shows how to use the while loop to calculate the sum.

public class Main {
 public static void main(String[] args) {
   int limit = 20;
   int sum = 0;
   int i = 1;

   while (i <= limit) {
     sum += i++;
   }
   System.out.println(“sum = ” + sum);
 }
}

The above code produces the following results.

Java While Loop Example -2 

If the condition is yes false, while the body of the loop will not be executed. For example, in the following snippet, println()the call to the pair is never executed :


public class Main {
 public static void main(String[] argv) {
   int a = 10, b = 20;
   while (a > b) {
     System.out.println(“This will not be displayed”);
   }
   System.out.println(“You are here”);
 }
}

Java While Loop Example – 3

while the body of the text can be empty. For example, consider the following procedure:


public class Main {
 public static void main(String args[]) {
   int i, j;
   i = 10;
   j = 20;

   // find midpoint between i and j
   while (++i < –j);
   System.out.println(“Midpoint is ” + i);
 }
} 

Java do while statement

To perform the body of a while loop at least once, you can use a do-while loop.

The syntax of a Java do while loop is:

do {
  // body of loop
} while (condition);

Here is an example showing how to use do-while loops.


public class Main {
 public static void main(String args[]) {
   int n = 10;
   do {
     System.out.println(“n:” + n);
     n–;
   } while (n > 0);
 }
}

The loop in the previous program can be written as:

public class Main {
 public static void main(String args[]) {
   int n = 10;
   do {
     System.out.println(“n:” + n);
   } while (–n > 0);
 }
}

The output is the same as the above result:

Java Do While Statement Example – 4

The following program uses do-whilea very simple help system loop and swith statement.

public class Main {

 public static void main(String args[]) throws java.io.IOException {

   char choice;

   do {

     System.out.println(“Help on:”);

     System.out.println(” 1. A”);

     System.out.println(” 2. B”);

     System.out.println(” 3. C”);

     System.out.println(” 4. D”);

     System.out.println(” 5. E”);

     System.out.println(“Choose one:”);

     choice = (char) System.in.read();

   } while (choice < ‘1’ || choice > ‘5’);

   System.out.println(“\n”);

   switch (choice) {

     case ‘1’:

       System.out.println(“A”);

       break;

     case ‘2’:

       System.out.println(“B”);

       break;

     case ‘3’:

       System.out.println(“C”);

       break;

     case ‘4’:

       System.out.println(“D”);

       break;

     case ‘5’:

       System.out.println(“E”);

       break;

   }

 }

}

Java Tutorial – Java Break Statement

 

When a break statement is encountered in a loop, the loop terminates and program control resumes in the next statement after the loop.

Break statement syntax

break;

or

break labelName;

Here’s a simple example:


public class Main {
 public static void main(String args[]) {
   for (int i = 0; i < 100; i++) {
     if (i == 10)
       break; // terminate loop if i is 10
     System.out.println(“i: ” + i);
   }
   System.out.println(“Loop complete.”);
 }
}

Java Break Statement Example

break statements can be looped with. For example, here is whilet he previous program that uses loop coding.


public class Main {
 public static void main(String args[]) {
   int i = 0;
   while (i < 100) {
     if (i == 10)
       break; // terminate loop if i is 10
     System.out.println(“i: ” + i);
     i++;
   }
   System.out.println(“Loop complete.”);
 }
}

Java Break Statement Example – 2

The break statement helps to exit the infinite loop. In the following while loop, the true values are hard-coded, so the while loop is an infinite loop. Then it uses the if statement as 10 when the break statement exits the loop.


public class Main {
 public static void main(String args[]) {
   int i = 0;
   while (true) {
     if (i == 10){
       break; // terminate loop if i is 10
     }
     System.out.println(“i: ” + i);
     i++;
   }
   System.out.println(“Loop complete.”);
 }
}

Java Break Statement Example – 3

When used in a set of nested loops, the break statement only breaks through the innermost loop. E.g:


public class Main {
 public static void main(String args[]) {
   for (int i = 0; i < 5; 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.”);
 }
}

Java Break Statement Example – 4

Terminating the switch statement break only affects its switch statement, not any closed loop.


public class Main {
 public static void main(String args[]) {
   for (int i = 0; i < 6; i++)
     switch (i) {
       case 1:
         System.out.println(“i is one.”);
         for (int j = 0; j < 5; j++) {
           System.out.println(“j is ” + j);
         }
         break;
       case 2:
         System.out.println(“i is two.”);
         break;

       default:
         System.out.println(“i is greater than 3.”);
     }
 }
}

Java Break Statement Example – 5

We can specify a label for the break statement to let the code logic exit to that point. The following code uses tags to make the break statement exit the two layers of the nested for loop.


public class Main {
 public static void main(String args[]) {
   outer: for (int i = 0; i < 10; i++) {
     for (int j = 0; j < 10; j++) {
       if (j + 1 < i) {
         System.out.println();
         break outer;
       }
       System.out.print(” ” + (i * j));
     }
   }
   System.out.println();
 }
}

Java Tutorial – Java continue statement

 

The continue statement forces an early iteration of the loop. In the while and do-while loop, the continue statement transfers control to the conditional statement expression control loop. In the for loop, the control first iterates over the part of the for statement and then into the conditional expression.

Java continue statement

The continue statement syntax

continue;

or

continue labelName;

The following code shows how to use the continue statement.


public class Main {
 public static void main(String[] argv) {
   for (int i = 0; i < 10; i++) {
     System.out.print(i + ” “);
     if (i % 2 == 0)
       continue;
     System.out.println(“”);
   }
 }
}

Java Continue Statement Example

You can specify label to describe a closed loop to continue.


public class Main {
 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();
 }
}

Java Continue Statement Example – 2

The code below shows how to use the label while loop.

public class Main {
 public static void main(String[] args) {
   int i = 0;
   outer: while (true) {
     System.out.println(“Outer while loop”);
     while (true) {
       i++;
       System.out.println(“i = ” + i);
       if (i == 1) {
         System.out.println(“continue”);
         continue;
       }
       if (i == 3) {
         System.out.println(“continue outer”);
         continue outer;
       }
       if (i == 5) {
         System.out.println(“break”);
         break;
       }
       if (i == 7) {
         System.out.println(“break outer”);
         break outer;
       }
     }
   }
 }
}

Java Continue Statement Example – 3

The following code shows how to calculate Primes using the continue statement and the label.

public class Main {
 public static void main(String[] args) {
   int nValues = 50;

   OuterLoop: for (int i = 2; i <= nValues; i++) {
     for (int j = 2; j < i; j++) {
       if (i % j == 0) {
         continue OuterLoop;
       }
     }
     System.out.println(i);
   }
 }
}

Java Continue Statement Example – 4

The following code shows how to use the Labeled continue statement to calculate the factorial number.

public class Main {
 public static void main(String[] args) {
   int limit = 20;
   int factorial = 1;

   OuterLoop: for (int i = 1; i <= limit; i++) {
     factorial = 1;
     for (int j = 2; j <= i; j++) {
       if (i > 10 && i % 2 == 1) {
         continue OuterLoop;
       }
       factorial *= j;
     }
     System.out.println(i + “! is ” + factorial);
   }
 }
}

Java Tutorial – Java Comment Statement

 

The comments in the source code provide information about the source code. This is a good practice to write comments to record the source code.

Three types of annotations are supported in Java.

  1. Single line
  2. Multi-line
  3. Document note

 

Single line comment

The Java single-line comment //ends from the beginning to the end of the line.

public class Main {
 // This is a single line comment.
 public static void main(String[] argv) {
 }

}

Multi-line comments

Java multi-line comments are between /*and */between. The compiler ignores everything from /*to */.

public class Main {
 /* This
    is
    a
    Multiline
    comment.
 */
 public static void main(String[] argv) {
 }

}

Java Doc Comments (Javadoc)

The Javadoc documentation annotation is used to generate an HTML file for the logger. In short, we usually call the Java documentation comment javadoc.

Javadoc comments take up one or more lines of source code. The documentation comment /**begins with and */ends with. Everything from /** to */ is ignored by the compiler.

The following example demonstrates the Javadoc comment:

/**
* Application entry point
*
* @param args array of command-line arguments passed to this method
*/
public static void main(String[] args)
{
// TODO code application logic here
}

This example begins with a Javadoc comment describing the main() method. /**And the */description includes methods, which may include HTML tags such as a <p>, <code>and /</code>, and @paramJavadoc tag (a @ prefix instructions).

The following list identifies several commonly used tags:

  • @author The author who identifies the source code.
  • @deprecated Identify source code entities that should no longer be used.
  • @param One of the parameters that identify the method.
  • @see Provides a see-also reference.
  • @since Identifies the software version that the entity first initiated.
  • @return Identifies the type of value returned by this method.

The following code has more documentation comments

/**
* A simple class for introducing a Java application.
*
* @author yourName
*/
public class HelloWorld {
 /**
  * Application entry point
  *
  * @param args
  *        array of command-line arguments passed to this method
  */
 public static void main(String[] args) {
   System.out.println(“Hello, world!”);
 }
}

We can use the JDK’s javadoc to extract these document comments into a set of HTML files, as follows:

The Javadoc command defaults to public and protected members for public classes and for generating HTML-based documents.

Related Java Tutorials & Interview Questions

Related Java Tutorials & Interview Questions
Introduction to Java Programming 21 Aricent Java Interview Questions
Java Keywords Tutorial For Beginners 53 Accenture Java Interview Questions
Java Data Types Tutorial For Beginners 399 Core Java Interview Questions
Java Operators Tutorial For Beginners 581 Advanced Java Interview Questions
Java Performance Tuning Tips 60 Java Multiple Choice Questions And Answers
Core Java Multiple Choice Questions More Java Tutorials & Interview Questions..

Leave a Reply

Your email address will not be published. Required fields are marked *