HomeJava

11 keywords to learn loops and conditional statements in java

11 keywords to learn loops and conditional statements in java
Like Tweet Pin it Share Share Email

In this article you can learn about loops and conditional statements in java with help of 11 keywords. Any programming language has the ability to control the code flow, that is the program can dynamically change its behavior based on some of the conditions it met. These are written with the help of three sets of keywords, which are Conditional statements, Looping Statements and Jumping statements.

Simple example in a diagram:

  • Conditional statements are used to decide if a specific set of statements to be executed or skipped based on the condition written in the program.
  • Looping statements are used to repeat specific set of statements until the condition specified remains true.
  • Jumping statements are used to abruptly exit from a particular statement, these are generally used in conjunction with conditional constructs.

In order to avail the above set of behaviors as part of your Java program, Java has 11 keywords which can be used, and each have a specific syntax to be followed

Following 11  keywords allow you to write loops and conditional statements in java

These are the keywords which will determine the code flow, i.e. if you want to repeat some specific set of statements or if you want certain set of statements to be executed or skipped based on conditions of the business logic that is written in the program.

S.No Keyword Purpose
1 if If keyword is used to execute certain set of statements when a specific condition in a business logic evaluates to a true condition.

for example: you want to find square of a number only if its an even number, so you could place a condition like, if the given number is even then find the square of it.

// sample if condition
if( i % 2 == 0 )
{
i = i * i;
}
2 else If and else keywords are used in conjunction, where you want to have statements to be executed on a true and false condition.

for example: you want to find square of a number only if its an even number and otherwise find cube of the same number, so you can place a condition like, if the given number is even then find the square of it else find cube of it.

//sample if else condition
if(i%2==0)
{
i = i*i; // square of the number
}
else
{
i = i*i*i; // cube of the number
}
3 while while looping keyword is used to repeat certain set of statements continuously unless the condition provided in the while loop results to a false.

for example: you want to print the first 10 numbers, so you could consider like, while the value of variable “i” is less than 10 increment it and print it to console.

//sample while condition
while ( i < 10 )
{
i = i + 1;
System.out.println( "Value of i:" + i);
}
4 for for looping keyword is similar to while statement, but the only difference is, as part of the for loop, you could also associate 2 additional things along with the conditional statement, which are initialising and stepping up or stepping down,

for example: you want to print the first 10 numbers, you could write it like

//sample for loop
for (int i=0;i< 10;i++)
{
System.out.println("Value of i:"+ i);
}

In the above code snippet if you see, there are three sections, first one is for initialising variables executed only once, second section forms the condition whether to continue or to exit the loop, third section  is place where you can have some incremental or decremented statements, if you have observed clearly in while loop we had to add a statement i = i + 1 to increment as part of the repeated steps inside the loop. But now in for loop it is made as part of the for syntax it self.

In addition, the first (int i=0) and second section(i<10)  statements in the for syntax are executed first time. After which both second and third section(i++) are executed every time the steps inside loop are executed till the condition in second section evaluates to false.

5 do do looping keyword is similar to while & for loop, just that all the steps inside the looping construct are executed at least 1 time irrespective of the condition specified, unlike the while & for looping constructs which does not allow to execute the statements even 1 time if the condition is not met.

for example: you want to print the numbers

//sample for do while
int i = 1;
// this loop will execute the statements inside the loop even 
// if the condition does not evaluate to true for the first time.
do
{
    System.out.println("Value of i:" + i) ;
    i++;
} while( i < 1) ;
6 break break is a keyword used to jump from between of a specific set of statements within in a looping construct, ideally the cases when there is condition where you dont want to continue the execution of the remaining statements and also  not to repeat the execution of the statements.

// sample for break statement
for(int i=2;i<10;i++)
{
    System.out.println("I:" + i );
    if( i % 3 == 1) // if the value of i is
    {
       break; // exits from the for loop
    }
    System.out.println("after statement");
}

 

In the above logic, once value of i reaches 4, the condition i % 3 == 1 evaluates to true and the break statement gets executed, the loop does not continue for the remaining iterations of variable “i” which are 5,6,7,8,9. The for loop was supposed to execute for 10 times if the condition and break statements were not specified. This is how break statement helps to break from a looping structure.

7 continue continue is a keyword used to jump to next iteration in the looping structure, skipping the execution of remaining statements present in the loop. When skipped the third section of for loop would still be executed, but when using continue with while or do while, special care to be taken with the variables used in the condition section, which otherwise might result in to an infinite loop. Be cautious about it.

// sample for continue statement
for(int i=2;i<10;i++)
{
    System.out.println("I:" + i );
    if( i % 3 == 1) // if the value of i is
    {
        continue; 
       // skips the steps for this iteration and moves to next 
       // iteration in the loop
    }
    System.out.println("after statement");
}

In the above logic, once value of i reaches 4, the condition i % 3 == 1 evaluates to true and the continue statement gets executed, at this instant the remaining statements present in the for loop for this iteration are skipped and the execution starts from first statement of the for loop for the next iteration. i.e. the iteration continues to execute for 5,6 and again the continue gets triggered when i is at value 7.

8 return  return is a keyword used to return or exit from a function or program, generally used with functions to return values to the calling method.

//the code flow stops based on the condition it is met, 
//that stop of code flow is controlled with return statement here.
public int findIndex(String vals[],String searchString) {
int indexFound = -1;
for(int i=0;i<vals.length;i++)
{
    if(vals[i].equals(searchString))
    {
        indexFound = i;
        //code stops executing remaining part of the function 
        // once below statement is executed.
        return indexFouond;
    }
}
return indexFound;
}

 

9 switch Switch keyword is used when you have multiple conditions to be evaluated and the specific set of statements are evaluated accordingly.

public void printNumber(int num)
{
// a switch case where it checks for 10 different conditions 
// in a single conditional statement. break; is required 
// so that once a case is matched, it executes the statements 
// inside it and continues to execute the statements 
// of the cases below it.
    switch(num)
    {
        case 0:
            System.out.println(" Zero ");
            break;
        case 1:             
            System.out.println(" One ");             break;
        case 2:             
            System.out.println(" Two");             break; 
        case 3:             
            System.out.println(" Three");             break; 
        case 4:             
            System.out.println(" Four");             break; 
        case 5:             
             System.out.println(" Five");             break; 
        case 6:             
             System.out.println(" Six");             break; 
        case 7:             
             System.out.println(" Seven");             break; 
        case 8:             
             System.out.println(" Eight ");             break; 
        case 9:             
              System.out.println(" Nine");             break; 
        default:
           System.out.println("Invalid Number");
    }

}

 

10 default  default is a keyword which is used with switch construct, this is the case when no conditions/cases defined are satisfied as part of the switch, the statements present in the default section are executed as part of the switch construct.

In the above switch example, if you had seen the keyword default, it helps to execute any set of statements that you want to execute when none of the cases are matched.

11 case case is a keyword used with switch construct, different set of conditions are specified as part of the cases in  switch construct.

In the above switch example, each condition is identified by a case, if any case is matched, the statements inside it are executed.

Using the above list of conditional, looping constructs, you can write business logic as per your requirement and attain the results you are looking for, the above things are explained with very simple statements just keep it simple and easy to understand, which otherwise these are very powerful in any programming language. I would recommend you to write more and more complex programs to practise and get better hang on these constructs.

You could practice more and more, give a try to write programs for the ones listed in this post, this could help you to improvise yourself and understand more about the conditional & looping constructs.

Comments (0)

Leave a Reply

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