Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to use for , while and do-while loop statements in Java code

Introduction :-
Java has mostly three looping statements such as for, while and do-while. All three looping statements help us iterating over a code which we want to perform frequently. In this tutorial I will be providing to you Java tutorial on these looping statements. Learning Java through explanation and code is the most effective mechanism. I will be providing you with few basics of looping statements , syntax and than provide you with Java source code. After we get few fundamentals of Java looping statements , I will explain you the code through images. This will make you understand all the three looping statements clearly at basic level.
The overall looping process involves 3-4 steps. Let us examine each of them one-by-one :
1. initialization :- A counter variable is set to a value and used to loop the body accordingly.
2. execution of loop body :- After initialization and condition fulfillment body gets executed that many times based on condition and iteration.
3. condition :- After initialization a boolean condition is tested with counter variable. If condition comes out to true body of loop gets executed , if condition comes out to be false the loop terminates.
4. iteration :- Iteration is the increment or decrement process set to counter variable so that we can get exact number of loops.
Let us start with the for loop :


1. for loop statements working :-
Let us look at working of for loop in Java. Before going further you should be familiar with the basics of for loop. Let us view the syntax of the for loop :-




A sample for loop code

public class ForDemo {
    public static void main(String[] args) {
        
        for (int i = 0; i <= 10; i++) {
            System.out.println("i = " + i);
        }            
    }
}










1. Code and Diagram explanation :-
In the ForDemo class we have a main method which is the entry point for the execution of our program. Then comes the for loop statement. If examining the example by above four criteria we see that here initialization step is int i = 0; condition is i <= 10; if the condition is true body of for loop gets executed i.e System.out.println("i = " + i); if the condition is false the for loop exits. After execution of body each time iteration or increment of i is done and then condition is again tested. This process continues till condition fails.



2. while loop statements working :-
Let us look at working of while loop in Java. Before going further you should be familiar with the basics of while loop. Let us view the syntax of the while loop :-






A sample while loop code 

public class WhileDemo {
    public static void main(String[] args) {        
        
       int countDown = 10;
       
       while (countDown >= 0) {
          
          System.out.println(countDown);
          countDown--;            
        }
    }
}




1. Code and Diagram explanation :-
In the WhileDemo class we have a main method which is the entry point for the execution of our program. Then comes initialization of countDown variable. It is assigned with value 10. Then comes the while loop statement. Here condition is countDown>= 10; if the condition is true body of while loop gets executed i.e System.out.println(countDown); and countDown gets decrement to 1. If the condition is false the while loop exits. Again condition is tested. This process continues till condition fails.



A sample do-while loop code 

public class DoWhileDemo {
    public static void main(String[] args) {
        int i = 0;
        
        do {            
            System.out.println(i);
            i++;
        } while (i <= 10);
    }





1. Code and Diagram explanation :-
In the DoWhileDemo class we have a main method which is the entry point for the execution of our program. After initialization of variable i = 0;. Then comes the do-while loop and body starts executing printing the value of i. Then there is increment in the i value. Then condition is tested that is i<=10; If the condition is true the do loop body again gets executed.This process continues till condition fails. As condition fails the loop gets exit.

Java Control Statements- if-else and switch statements

Lets begin with a tutorial on Java how to program series next session called as Control Statements. Control statements are decision making statements in Java. They are basically used in Java source code to perform thought process i.e they are control flow statements which control flow of execution of Java code by decision making, looping and branching. Now we can control certain block of code by enabling these control statements in Java. There are various different types of control statements used in Java such as : If else statement, switch statement, while statement, break statement, continue statement, do statement and for statement etc. Let us look each of them in detail below :

The if Statement
In Java if statement is most widely used. The if statement is control statement which helps programmers in decision making. The if statement uses boolean expression in making decision whether a particular statement would execute or not. Lets look at syntax of if statement :


 Syntax : 

 if ( boolean-expression )
 { 
   if-code;
 } 

 rest-of-code; 



The if statement is a type of conditional branching statement. By the conditional branching we mean that branching of flow depends on some conditions. The decision making is done based on true or false. Looking at the above syntax and below diagram we can come to explanation of if statement. If the boolean-expression is true, if-code gets executed. If the boolean-expression is false rest_of_code gets executed.





The if-else statements
It is basically extension of if statement. Lets look at the syntax of the if-else statement.



Syntax :

if(boolean-expression)
{
  if-code;
}
else
{
  else-code;
}

rest-of-code;





If the boolean-expression is true if-code gets executed. If boolean-expression is false else-code gets executed. In this decision making statements generally either of the block gets executed whether its if-code or else-code, after either execution rest-code gets executed.





The Nested if-else statements
The Nested if-else statements are used where we want to make series of decision making. Thus one if-else is nested within another if-else. Therefore nested if-else give us to make a decision within a decision already taken. Lets look at the syntax of nested if-else statements


Syntax :

if(boolean-expression 1)
{
  if(boolean-expression 2)
  {
    statement 1;
  }
  else
  {
     statement 2;
  }
}
else
{
  statement 3;
}
rest-of-code;



Lets analyze about syntax and flowchart. Nested if-else syntax is very much. Generally if you look at the flowchart you will find that there are two if-else statements. You can nest them to n number. For the sake of simplicity we have taken only two if-else. Logic implemented in above syntax is like if boolean-expression 1 is false, statement - 3 gets executed and then program flows to rest of code. But if the boolean-expression 1 is true the controls flow to another expression called as boolean-expression 2. Then the same code follows if boolean-expression 2 is evaluated as false statement - 2 gets executed and then to rest of the code. But if boolean-expression 2 is true, statement - 1 is executed and then follows to rest of code.

Else-if Ladder Statements
Below diagram shows else-if ladder statements. Else-if ladder is generally used when we want to take multiple decision. These multiple decision are in chains of if followed by else-if statements till n number. Lets us look at flowchart and syntax associated with else-if ladder.


Syntax : 

if(boolean-expression 1)
{
  statement-1;
}
else if(boolean-expression 2)
     { 
       statement-2;
     }
     else if(boolean-expression n)
       {
         statement-n;
       }       
          else
          {
          default-statement;    
          }

rest-of-code;









 

Lets analyze the syntax and flowchart of Else-if ladder. The multiple decision making starts from top and flows towards bottom. The ladder works very simple and straight way. Whenever true condition is evaluated the statement below if gets executed and rest-of-code execution follows and whenever false condition is evaluated control flows towards next condition till default statement gets executed followed by rest-of-code.

The Switch Statements
We saw how if-else statement worked when making a multiple decision. But this if-else is limited to use in complex scenarios. Java provides a sensational switching technique when making a multi-way decision. This switch statement evaluates an expression and based on the result of expression chooses a path that matches one of the list values. The list values are called as Cases. The expression value is matched against this cases, and which ever case match the control moves to that switch. Lets look at the syntax and flowchart for the switch statement:


switch(expression)
{
  case value-1:
              block-1
              break;
  case value-2:
              block-2
              break;

  default:
             default-block
             break;
}
                
rest-of-code;



Lets look at how switch statement works in Java. Switch statement first starts with a keyword switch followed by an expression. The Java code for expression must be integer or character expression. The value of expression must be an Integral constant. There are various case labels such as value-1, value-2 etc. These case labels must be evaluable to integral constants. When the switch is executed, value of expression is compared with case labels value starting from top and moving towards bottom. If any of case labels that matches with expression, the block of code that follows case gets executed. After block of code gets executed there is a break statement at the end of block code which breaks the switch statement and transfer control to rest-of-code to execute. If break statement is not written the control starts compairing with next case that follows. At the last default is an optional case which is placed when no case matches with expression. If no expression value matches with case labels value than default case is triggered and code associated with it gets executed.



Operators in Java programming language

Overview of Operator
Java is a very versatile programming language. It is versatile because of many good features. One of the feature it provide is power of Operators. Operators are essential requirement for a good programming language. Java provides a wide set of Operators. These operators help programmer to get the functionality to operate over variables. Generally in Java there are two types of operators:-

1. Unary Operators
They are operators which operate on single operand.
2. Binary Operators
They are operators which operate on two operands.

There are also many classes of Operators some of them are :
1. Arithmetic Operator
2. Comparison Operator
3. Assignment Operator
4. Conditional Operator
5. Bitwise Operator
6. Boolean Operator
Lets have a look to all of the Operators listed above :

Arithmetic Operator
The Java programming language uses arithmetic operators very extensively. Arithmetic operators are used where we have to perform basic mathematical computations. The mathematical computations such as addition, subtraction, division, multiplication etc . Below contains a table which describes Arithmetic Operators, have a look at them carefully.




Comparison Operator
Java provides us with a set of comparison operators which compares value of one variable to value of another variable and based on comparison helps us to build a expression. Generally these sort of operators are been used in the if-else contructs. Generally expression built by these operators are either true or false. It means they will return either true value or false value. This helps in flow of code in if-else constructs. Lets look about them in detail.






Assignment Operator
Java provides us with a set of assignment operators which are normally used to give a value to a variable. After performing mathematical calculations or say conditions from an expressions the returned value is assigned to a variable. Lets look at the below table for its usage :



Conditional Operator
Java provide us with a ternary operator which performs functionality of a if-else constructs. Generally conditional operator uses expression for two variables if condition is true it executes code and if not it executes some other code. Lets have a look how it is use :





Bitwise Operator
Bitwise Operators are quite tricky and complex operators in Java. Generally when a Java application transfer information over a network to a method written in a different programming language we need to do the data conversion. Bitwise operators are used to convert one value to another at bit-level. Lets look at their usage :


Boolean Operator
Generally Boolean Operator are mainly three in number. Lets look into their usage :



Operator Precedence
Generally if a Java expressions contains two or more than two different operators in a statement compiler decides to evaluate which operator first by the concept of operator precedence. Generally Operator Precedence table is followed when evaluating the expression. Let us look at Operator Precedence table:



 
© 2021 Learn Java by Examples Template by Hubberspot