Java Basics:if, if else and nested if else In Java

 

Control Flow in Java

Java compiler executes the java code from top to bottom. The statements are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of java code. Such statements are called control flow statements.

Java provides three types of control flow statements.

  1. Decision Making statements
  2. Loop statements
  3. Jump statements

Decision-Making statements:

Decision-making statements evaluate the Boolean expression and control the program flow depending upon the condition result. There are two types of decision-making statements in java, I.e., If statement and switch statement.

If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the condition result that is a Boolean value, either true or false. In java, there are four types of if-statements given below.

  1. if statement
  2. if-else statement
  3. else-if statement
  4. Nested if-statement

Let's understand the if-statements one by one.

1. if statement:

This is the most basic statement among all control flow statements in java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

  1. if(<condition>) {  
  2. //block of code  
  3. }  
  4.   
  5. Consider the following example in which we have used the if statement in the java code.  
  6.   
  7. public class Student {  
  8. public static void main(String[] args) {  
  9. int x = 10;  
  10. int y = 12;  
  11. if(x+y > 20) {  
  12. System.out.println("x + y is greater than                               20");  
  13. }  
  14. }  
  15.   
  16.   
  17. }  

Output:

x + y is greater than 20

2. if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, I.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Consider the following example.

  1. public class Student {  
  2. public static void main(String[] args) {  
  3. int x = 10;  
  4. int y = 12;  
  5. if(x+y < 10) {  
  6. System.out.println("x + y is less than      10");  
  7. }   else {  
  8. System.out.println("x + y is greater than 20");  
  9. }  
  10. }  

Output:

x + y is greater than 20

3. lse-if statement

The else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter any block of code. We can also define an else statement at the end of the chain.

Consider the following example.

  1. public class Student {  
  2. public static void main(String[] args) {  
  3. String city = "Delhi";  
  4. if(city == "Meerut") {  
  5. System.out.println("city is meerut");  
  6. }else if (city == "Noida") {  
  7. System.out.println("city is noida");  
  8. }else if(city == "Agra") {  
  9. System.out.println("city is agra");  
  10. }else {  
  11. System.out.println(city);  
  12. }  
  13. }  
  14. }  

Output:

Delhi

4. Nested if-statement

In nested if-statements, the if statement contains multiple if-else statements as a separate block of code. Consider the following example.

  1. public class Student {  
  2. public static void main(String[] args) {  
  3. String address = "Delhi, India";  
  4.   
  5. if(address.endsWith("India")) {  
  6. if(address.contains("Meerut")) {  
  7. System.out.println("Your city is meerut");  
  8. }else if(address.contains("Noida")) {  
  9. System.out.println("Your city is noida");  
  10. }else {  
  11. System.out.println(address.split(",")[0]);  
  12. }  
  13. }else {  
  14. System.out.println("You are not living in india");  
  15. }  
  16. }  
  17. }  

Output:

Delhi

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement enables us to check the variable for the range of values defined for multiple case statements. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program. The syntax to use the switch statement is given below.

  1. switch <variable> {  
  2. Case <option 1>:  
  3. //block of statements  
  4. ..  
  5. ..  
  6. ..  
  7. Case <option n>:  
  8. //block of statements  
  9. Default:  
  10. //block of statements  
  11. }  

Consider the following example to understand the flow of the switch statement.

  1. public class Student implements Cloneable {  
  2. public static void main(String[] args) {  
  3. int num = 2;  
  4. switch (num){  
  5. case 0:  
  6. System.out.println("number is 0");  
  7. break;  
  8. case 1:  
  9. System.out.println("number is 1");  
  10. break;  
  11. default:  
  12. System.out.println(num);  
  13. }  
  14. }  
  15. }  

Output:

2

While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.

  1. for loop
  2. while loop
  3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In java, for loop is similar to C and C ++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. The syntax to use the for loop is given below.

  1. for(<initialization>, <condition>, <increment/decrement>) {  
  2. //block of statements  
  3. }  

The flow chart for the for-loop is given below.

Control Flow in Java

Consider the following example to understand the proper functioning of the for loop in java.

  1. public class Calculattion {  
  2. public static void main(String[] args) {  
  3. // TODO Auto-generated method stub  
  4. int sum = 0;  
  5. for(int j = 1; j<=10; j++) {  
  6. sum = sum + j;  
  7. }  
  8. System.out.println("The sum of first 10 natural numbers is " + sum);  
  9. }  
  10. }  

Output:

The sum of first 10 natural numbers is 55

Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.

  1. for(type var : collection){  
  2. //statements  
  3. }  

Consider the following example to understand the functioning of the for-each loop in java.

  1. public class Calculattion {  
  2. public static void main(String[] args) {  
  3. // TODO Auto-generated method stub  
  4. String[] names = {"Java","C","C++","Python","JavaScript"};  
  5. System.out.println("Printing the content of the array names:\n");  
  6. for(String name:names) {  
  7. System.out.println(name);  
  8. }  
  9. }  
  10. }  

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop

The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

  1. While(<condition>){  
  2. //loop statements  
  3. }  

The flow chart for the while loop is given in the following image.

Control Flow in Java

Consider the following example.

  1. public class Calculattion {  
  2. public static void main(String[] args) {  
  3. // TODO Auto-generated method stub  
  4. int i = 0;  
  5. System.out.println("Printing the list of first 10 even numbers \n");  
  6. while(i<=10) {  
  7. System.out.println(i);  
  8. i = i + 2;  
  9. }  
  10. }  
  11. }  

Output:

Printing the list of first 10 even numbers 

0
2
4
6
8
10

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements. However, it is recommended to use the do-while loop if we don't know the condition in advance, and we need the loop to execute at least once.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.

  1. do   
  2. {  
  3. //statements  
  4. while (<Condition>);  

The flow chart of the do-while loop is given in the following image.

Control Flow in Java

Consider the following example to understand the functioning of the do-while loop in java.

  1. public class Calculattion {  
  2. public static void main(String[] args) {  
  3. // TODO Auto-generated method stub  
  4. int i = 0;  
  5. System.out.println("Printing the list of first 10 even numbers \n");  
  6. do {  
  7. System.out.println(i);  
  8. i = i + 2;  
  9. }while(i<=10);  
  10. }  
  11. }  

Output:

Printing the list of first 10 even numbers 
0
2
4
6
8
10

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are two types of jump statements in java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside the current flow. It is used to break the loop and switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the java program, i.e., it can only be written inside the loop or switch statement.

The break statement example with loop

Consider the following example in which we have used the break statement with the for loop.

  1. public class BreakExample {  
  2.   
  3. public static void main(String[] args) {  
  4. // TODO Auto-generated method stub  
  5. for(int i = 0; i<= 10; i++) {  
  6. System.out.println(i);  
  7. if(i==6) {  
  8. break;  
  9. }  
  10. }  
  11. }  
  12. }  

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

  1. public class Calculattion {  
  2.   
  3. public static void main(String[] args) {  
  4. // TODO Auto-generated method stub  
  5. a:  
  6. for(int i = 0; i<= 10; i++) {  
  7. b:  
  8. for(int j = 0; j<=15;j++) {  
  9. c:  
  10. for (int k = 0; k<=20; k++) {  
  11. System.out.println(k);  
  12. if(k==5) {  
  13. break a;  
  14. }  
  15. }  
  16. }  
  17.   
  18. }  
  19. }  
  20.   
  21.   
  22. }  

Output:

0
1
2
3
4
5

Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in java.

  1. public class ContinueExample {  
  2.   
  3. public static void main(String[] args) {  
  4. // TODO Auto-generated method stub  
  5.   
  6. for(int i = 0; i<= 2; i++) {  
  7.   
  8. for (int j = i; j<=5; j++) {  
  9.   
  10. if(j == 4) {  
  11. continue;  
  12. }  
  13. System.out.println(j);  
  14. }  
  15. }  
  16. }  
  17.   
  18. }  

Output:

0
1
2
3
5
1
2
3
5
2
3
5


Control Flow Statements in Selenium 

Control flow statements, controls the normal flow of execution and executes based on conditions specified by the developer.

There are three types of Control Flow Statements :
Decision Making Statements (Selection Statements)
Looping Statements (Iterative Statements)
Branching Statements (Transfer Statements)

Decision Making Statements:

If , If – else and Switch Statements are Decision making statements. In this article we will look into 'simple If', 'if-else', 'if-else-if' and 'nested if' examples with selenium

1. Simple if Statement:

If statement is the basic of all control flow statements. It enables block of code to be executed based on specified condition.

Syntax:

if(Boolean_exp) {
             Statement 1; //Statements will be executed if Boolean expression is true
}
Statement 2://Statements will be executed always

'Statement1' inside if block will be executed if the Boolean expression (Condition) is true. If the Boolean expression is false then, statements inside if block will not be executed and it executes the rest of code after if block.

Conditional expression of if statement should always be a 'Boolean type' (Either True / False). If we try to give any other type then it will give compile time error as 'Type mismatch: cannot convert to boolean'

Let us look into below simple example:

public class IfExample {
	public static void main(String[] args) {
		int a=10; // declaring and initializing a with 10
		if(a==10) {
		//Will get executed only when the condition is true.
		System.out.println("Inside If block");	
	}
    }
}

<b>Now, let us look an example using if statements in selenium :</b>

<code>
package com.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class IfExampleSelenium {
	@Test
	public void testPageTitle() {
		System.out.println("Launching Firefox browser..");
		WebDriver driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.navigate().to("http://google.com");

		// verifying the page title
		String expPageTitle = "Google";
		boolean flag = false;
		if (driver.getTitle().equalsIgnoreCase(expPageTitle)) {
			flag = true;
			// This method will return True when the page title matches with specified string
			System.out.println("Yeah... Page title matched");
		}
		Assert.assertTrue(flag, "Page title is not matching with expected");
	}
}

In the above example, we are verifying page title. Here statements in the if block will be executed ONLY when 'driver.getTitle()' is 'Google'. In if block we are assigning 'flag' value with 'True', hence the Assert statement will be executed

2. If – else Statement:

Syntax:

if(Boolean_exp) {
         Statement1;
}
else {
statement2:
}

In if – else statement, if the specified condition is true, then statements in if block will be executed , if it is false, then statements in else block will be executed.If the condition in if is true then else block will never get executed

Let us look into a simple Example:

public class IfElseExample {
	public static void main(String[] args) {
		int a, b;
		a = 10;
		b = 20;
		if (a > b) {
			//Below statement will be executed ONLY when 'a' is greater than b
			System.out.println("a is greater than b");
		} else {
			//Below statement will be executed ONLY when 'b' is greater than 'a' or Equal to 'a'
			System.out.println("b is greater than a");
		}
	}
}

Let us now look into example with selenium using If Else. Earlier we have validated Page title using if block, in the same way, we have used 'driver.getTitle()' and check if it matches with expected title. If it is true, statements in if block will be executed. If it is NOT, statements in else block will be executed

if(driver.getTitle().equalsIgnoreCase("some expected text"))
    //Pass
    System.out.println("Page title contains expected text ");
else
    //Fail
    System.out.println("Page title doesn't contains expected text");

When there is only a single statement in if block or else block, then we no need to define curly braces and the statement inside if block should not be declarative statement.

Let us look into the below Example:

public class IfElseExample {
	public static void main(String[] args) {
		int test=10;
		if(test==10)
			int test1=20; // compile time error - as statement here is a declarative statement
	}
}

3. If else if Statement:

When ever there are more than two conditions, then we will go for if else if statement.

Syntax:

If(Boolean_exp1){
Statement1:
}
else if(Boolean_exp2){
statement2:
}
else{
statement3:
}

If the Boolean_exp1 is true, then the code inside if block will get executed, if it is false, then it will check for 'else if' condition i.e, Boolean_exp2 will be evaluated and now if it is true, then code inside else if block will be executed , if it is also false, then it will check if there are any other else if block available , if 'yes', it will check for all the 'else if' conditions and if they all are False, then else part will be executed.

Let us look at below example:

public class IfElseIfExample {
	public static void main(String[] args) {
		int age;
		System.out.println("Enter age");
		//Ask the user to enter the age
		Scanner in = newScanner(System.in);
		age=in.nextInt();
		if(age<13)
			System.out.println("child");
		else if(age>13 && age<19)
			System.out.println("teenager");
		else
			System.out.println("adult");
	}
}
4. Nested If Statement:

Nested if statement is nothing but if- else statement with another if or if else statement .
Syntax: if(Boolean_exp){// outer if
If(Boolean_exp1){// inner if
statement1;
}// inner if closed
else{
statement2;
}// inner else closed
}// outer if closed
else{
statement3;
}// outer else closed

Statement1 will be executed when both outer if and inner if condition is evaluated to true. Statement 2 will be executed when outer if condition is evaluated to true and inner if condition as false. and Statement3 will be executed when outer if condition is evaluated to false.

Whenever the outer if condition is evaluated to false, inner if condition will never be checked.

Example:
public class NestedIfDemo {
public static void main(String[] args) {
int a=55;
int b=50, c=60;
if(a>b){
if(a>c) {
System.out.println("a is big");
}
else{
System.out.println("c is big");
}
}
else if(b>c){
System.out.println("b is big");
}
else{
System.out.println("c is big");
}
System.out.println("out side outer if and else");
}
}

Nested if statements are basically used whenever we want to check a condition based on the result of another condition.

Let us look into below example with nested if using selenium :

@Test
	public void testNestedIfExample() {

		System.out.println("Launching Firefox browser..");
		WebDriver driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.navigate().to("http://facebook.com");
		By locator = By.name("firstname");
		if (driver.findElements(locator).size() > 0) {
			if (driver.findElement(locator).isDisplayed()) {
				driver.findElement(locator).sendKeys("Hello");
			}
		}

	}

Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Selenium-Java Contents

Java OOPS:Constructors in Java – A complete study!!