Home  >  Blog  >   Selenium

Java Tutorial for Selenium WebDriver

Rating: 4.7
  
 
5402
  1. Share:
Selenium Articles

The following blog on Java tutorial for Selenium WebDriver makes you learn basic Java concepts needed to write a test case in Selenium WebDriver. In this article, we will be covering below Java concepts with examples. Here, we will try to cover all Java concepts with respect to Selenium WebDriver to understand and use those concepts while working with Selenium WebDriver.

The basic Java concepts are as follows:

Java Selenium Tutorial - Table of Contents

If you want to enrich your career and become a professional in Selenium with Java, then enroll in "Selenium With Java Training". This course will help you to achieve excellence in this domain.

Classes and Objects in Java

Classes and Objects are the basic and important concepts in Java programming. It becomes easy to understand these concepts once they are visualized and related to real life.

What is an Object?

In the real world, an object is defined as a thing which we can see, touch, and feel. It has both state and behavior. For example, a dog is an object which has a state (breed, color, age, and size) and behavior (eat, run, sleep etc.).

Similarly in an object-oriented language like Java, object is called as a class instance that performs a group of activities. It implements its state in the form of variables and behavior in the form of methods.  From the above example, we can define an object (dog) as a collection of variables (breed, color, age and size) and methods (eat, run and sleep).

What is a Class?

A class can be defined as a guide to creating objects. Objects created from a single class always share a similar state and behavior.  The major difference between an object and a class is that an object is created during the run time whereas a class is created during the program.

Creation of Class

A class can be created using the keyword class followed by a name. The body of the class is delimited by curly brackets ({ }). A class can have one variable or a group of variables. 

  • Declaring a class
  • Declaring class member variables
  • Initializing class object
  • Methods of a class.

Data Types and Variables

Knowledge of data types and variables helps to easily understand programming in Java for Selenium. 

What is a Data Type?

A data type is an indicator of the type of data that a variable holds. There are data types such as boolean, integer, character, double, floating-point, alphanumeric, short, and long. But in Java tutorial for Selenium, we use only basic data types such as integer, boolean, character, and double.

What is a Variable?

A variable is something that varies or changes. A simple program can be written using data and instructions. Data is a fixed or a constant value that does not change during the execution of a program.  A programmer can use variables rather than giving the data directly and during the compile time, the variables are replaced with the data entered by the programmer. 

Technically, a variable can be defined as a memory location or space reserved to store information of different data types such as integer, character, float, boolean and double. Each variable has a different memory allocation based on the data type. For example, a variable of integer data type occupies four bytes of memory whereas a character occupies only two bytes of memory. 

Variable Declaration

A variable declaration can be done using the syntax – 

Datatype VariableName;

When a variable is declared, the compiler allocates some space or memory depending upon the data type and fetches the stored value from the memory location using the variable name. A variable name can be of your choice but it must be simple and easy to use. The given variable name is called as an Identifier of that variable.

Variable Initialization

The syntax for variable initialization is as follows:

VariableName = Value;

Once a variable is declared, you can store a value before it is used for any kind of operations. An assignment operator ‘=’ symbol is used for initializing a variable.

Examples of different data types

The following are some examples of different data types which are used in Java for Selenium.

1. Boolean

Only 1-bit of memory is allocated for boolean and can store only boolean values such as “true” and “false”.  A boolean variable can be declared using the keyword boolean as shown below,

boolean VariableName;

2. Integer

You can store only numeric values or number using the integer data type. A 32-bit of memory is allocated for integer and can store the values ranging from -2,147,483,648 to 2,147,483,648. A decimal number cannot be store in a variable of an integer data type. An integer variable can be declared using the keyword int as shown below,

int VariableName;

3. Double

You can store decimal numbers using the double data type. A 64-bit of memory is allocated for double and a double variable can be declared using the keyword double as shown below,

double VariableName;

4. Character

Alphabets and special characters are stored using the character data type. A 16-bit of memory is allocated for character and a character variable can be declared using the keyword char as shown below, 

char VariableName;

Note: single quotation marks (‘ ‘) must be used to initialize a character variable. 

The following are some important rules to be followed while naming a variable,

  • Alphabets (A-Z and a-z) are used for naming a variable.
  • Special characters such as “_” (underscore) and “$” (dollar sign) are allowed.
  • A variable name cannot be started with a number. But, it can include numerical digits.
  • A variable name must not be one of the pre-defined keywords such as static, void, main, this etc.

MindMajix Youtube Channel

Operators

Operators are defined as special symbols which are used to perform specific operations such as arithmetic operations, logical operations and so on. These operations can be performed on one, two or three operands (participants in an operation). The operators are used to manipulate primitive data types (int, char, double and boolean). The general expression of operators is – 

Operand1 operator oeprand2 operator operand3……….so on

Based upon the operands, the operators are classified into –

  • Unary: Unary operators take only one operand. These operators appear as either pre-fix or post-fix to the operands.
  • Binary: Binary operators take two operands. These operators appear between the operands.
  • Ternary: Ternary operators take three operands and they also appear between the operands. 

Types of Operators

  1. Assignment
  2. Arithmetic
  3. Relational
  4. Logical and 
  5. Conditional.

1. Assignment Operator

The assignment operator is the most commonly used operator and it is denoted by the symbol “=”. It is used to assign the value on right to the variable on left. The assignment operator has the following syntax:

variable = value or expression;

2. Arithmetic Operators

Arithmetic operators are used to performing basic arithmetic operations such as addition, subtraction, multiplication, division etc. There are eight arithmetic operators in Java. The following table shows the details of each arithmetic operator. We have taken variables ‘a’, ‘b’, and ‘c’ for reference.

OperationSymbolPurposeSyntax
Addition+adds two numbers or concatenate two stringsa = b + c;
Subtraction-subtracts right side operand (c) from left side operand (b)a = b – c;
Multiplication*multiplies two numbersa = b * c;
Division/divides left side operand by right side operand and returns quotienta = b / c;
Modulus%divides left side operand by right side operand and returns remaindera = b % c;
Increment++increases the value by 1b ++;
Decrement--decreases the values by 1c --;
Negation-Unary operator that returns negative value-b;

3. Relational Operators

Relational operators are used to comparing to operands or objects. These operators return boolean values of either true or false when used in an expression. There are six relational operators in Java. The following table shows the details of each relational operator. We have taken variables ‘a’ and ‘b’ for reference. 

OperationSymbolPurposeSyntax
Greater than
>
Checks if the value on left side is greater than value on right sidea > b;
Less than<Checks if the value on left side is less than right sidea < b;
Equals to=Checks if left and right values are equala == b;
Greater than Equals to>==Checks if the value on left side is greater than or equal to that on right sidea >= b;
Less than or Equals to<==Checks if the value on left side is less than or equal to that on right sidea <= b;
Not equals to!=Checks if left and right side values are not equala != b;

4. Logical Operators

Logical operators are used to perform logical operations which return boolean values (true or false). The operands in logical expression must be of boolean data type. There are three commonly used logical operators. The following table shows the details of each logical operator. We have taken variables ‘a’ and ‘b’ for reference. 

5. Conditional Operator

The conditional operator is the only ternary operator and it is similar to if-else statement in Decision Making. This operator decides the value to be assigned to the variable based on the expression. The syntax for conditional operator is,

Variable = (expression) ? value 1; value 2;

If the boolean expression returns true value, then value 1 is assigned to the variable, else value 2 is assigned.

[ Check out Process of Debugging in Selenium ]

Decision Making

Decision-making is the most important facility which a programming language has to provide. There are two major decision-making statements in Java.

  1. If statement
  2. Switch statement.

1. If Statement

It is one of the control flow statements.  The code associated with if statement is executed only when the condition written in if part is true. The keyword then is not used in Java and it is written as { }. The following is the syntax for if statement in Java,

if (boolean expression) {
Statements;
}

You can add else statement and again if statement depending upon the choices to be made as shown below,

if (boolean expression) {
Statement 1;
} else {
Statement 2;
}

You can add multiple else-if statements as shown below, 

if (boolean expression 1) {
Statement 1;
} else if (boolean expression 2) {
Statement 2;
} else if (boolean expression 3) {
Statement 3;
} else {
Statement 4;
}

2. Switch Statement

Switch statement is used to replace multiple if-else-if statements in a program. It provides a simple way to execute different parts of code based upon single expression which has a constant value. The syntax is as shown below:

switch (expression) {
case value1:
Statement 1;
Break;
Case value2:
Statement 2;
Break;
Default :
Default statement;
Break;
}

The following are some rules to be followed for switch statements – 

  • The expression must be of data types int, char or double.
  • Each case must end with colon ( : ) and case value must be unique.
  • Every case must have break which is an exit point.
  • The default case is an optional case. It is used to perform a task when no case statement is true.

[ Related Article: XPATH Usage in Selenium ]

Arrays

An array is defined as a collection of similar things or values of similar data types. It holds multiple values in a single variable.  The syntax for the declaration of an array is,

ArrayType [ ] ArrayName = new ArrayType [size of an array];
  • ArrayType – It indicates the data type of values to be stored in an array. All values must be of similar data type. A compile error occurs when different data type values are entered other than the declared data type.
  • ArrayName – It indicates the name of an array. You can choose any name but it must be simple and logical.
  • new – new is a keyword used to create a new array and it allocates memory for an array.
  • Size of an array – It indicates the size of an array. It must be declared at the time of creation and remains constant throughout the program. An array always starts with a zero i.e. if the size of an array is 5 then the array has indices of 0, 1, 2, 3 and 4. 

There are two types of array-based upon the size – 

  • One-dimensional array: The values are stored only in a single dimension, either in a row or column.
  • Multi-dimensional array: The values are stored in rows and columns.

Loops

Loops are used to write a piece of code that is needed to be executed multiple times. The following are the major loops available in Java,

  1. For loop
  2. While loop
  3. Do-while loop

1. For Loop

The syntax of the for loop is:

For (Variable Initialization; Boolean Expression; Increment/Decrement)
{
Statements;
}

There are three important arguments or components in the syntax of the for loop. 

  • Variable initialization: It indicates the start value of the for loop and only integer data type is allowed.
  • Boolean expression: It indicates the condition to be tested for the executing the code. The code is executed only when the Boolean expression returns true value. 
  • Increment/Decrement: When the code in the loop is executed, the control goes to this part and changes the value of the variable. It increases the value in case of ++ and decreases in case of --.

2. While Loop

The syntax for the while loop is:

While (boolean expression) {
Statements;
}

When the boolean expression returns true value then only the code is executed. The only difference between for loop and while loop is, for loop repeats the code until specific number of times whereas, while loop executes the code for an unknown number of times.

Do-while Loop

The syntax for the do-while loop is,

Do {
Statements;
} while (boolean expression); 

The do-while loop is similar to that of the while loop. But the only difference is, the do-while loop executes the code at least one time irrespective of the return value of a boolean expression.

[ Learn How to Run Test Cases in Selenium ]

Constructors

A Constructor is defined as a piece of code which is used to initialize an object. In Java, whenever an object is created the compiler calls the default constructor. A constructor will have the same name of that class and does not return any value. The following is the syntax for creating a constructor,

class ClassName
{
new ClassName()
{
Statements;
}
}
ClassName obj = new ClassName ();

In the above syntax, when an object obj has created the compiler invokes the constructor ClassName () and assigns initial values to its members. 

Methods vs Constructors

Though methods and constructors look similar, they are different as:

MethodsConstructors
Methods can be abstract, static and final.Constructors cannot be abstract, static and final.
Performs task by executing the code.Initializes the object of a class.
Methods have return types such as int, char, double etc.A constructor does not return any value.
Methods have different names.A constructor must have a same class name.

Need for Constructors

Constructors are needed to maintain the privacy of the data and variables of a class. Sometimes, accessing the class variables to the main program is not secure. At that point, the variables in a class can be turned into private and a constructor can be created. Then, the main method can access the constructor variables without touching the class variables. 

Types of Constructors

There are three types of constructors in Java.

  1. Default constructor
  2. Parameterized constructor and 
  3. No-arg constructor.

1. Default Constructor: If no constructor is mentioned, the compiler creates a default constructor for a class. This default constructor is inserted during the compilation of the program and found in .class file. 

2. Parameterized Constructor: A constructor with parameters or arguments is called as a parameterized constructor.

3. No-arg Constructor: A constructor without any arguments or parameters is called a No-arg constructor. The syntax is similar to that of a default constructor but unlike default constructor, you can write body to a no-arg constructor.

[ Check out Top Selenium WebDriver Commands ]

String Class

A string is defined as a sequence of characters and it is not a data type. It is the most usable class in Java for Selenium WebDriver. The objects of the String class cannot be altered once they are created. There are two ways to create a string. 

String literal

The syntax is

String StringName = “abcdefghij”;

Using New Keyword

The syntax is 

String StringName = new String (“abcdefghij”);

Note: A double quotation (“ “) must be used to initialize values to the String object i.e. StringName in above syntax.

The characters initialized for string object are stored in an array with default index of zero. 

String Methods

The following are some of the string methods in Java for Selenium:

MethodReturn valueUsage
length()Returns the number of characters in a stringString s = “mindmajix”;
int I = s.length ();// returns 9
charAt(int i)Returns  the character at ith placechar c = s.charAt(5); // returns ‘a’
substring(int i)Returns the part of string starting from index i to end of the stringString sub= s.substring(4);// returns “majix”
substring(int i, int j)Returns the part of the string from i to j-1 indexString sub = s.substring(2, 6);// returns “ndma”
concat(String str)Returns the string concatenated with specified stringString s1 = “mindmajix”;
String s2 = “ technologies”;
String str = s1.concat(s2); //returns “mindmajixtechnologies”
indexOf (String str)Returns the index of the first occurrence of specified stringint i= s1.indexOf(“majix”); returns 4
indexOf (String str, int i)Returns the index of first occurrence of specified string starting from index iint j= s2.indexOf(‘e’,2);//returns 10 
lastindexOf(string str)Returns the index of the last occurrence of specified string int i= s2.lastindexOf(‘o’); //returns 8
toLowerCase()Returns the string in lower caseString s3=”MINDMAJIX”;
String s4= s3.toLowerCase(); // returns “mindmajix”
toUpperCase()Returns the string in upper caseString s5= s2.toUpperCase();// returns “TECHNOLOGIES”
trim()Returns the copy of string without whitespaces at both ends. It does not change spaces in middleString s6= “  mindmajix technologies  “;
String s7= s6.trim();// returns “mindmajix technologies”
replace( char oldchar, char newchar )Returns a new string by replacing oldchar with newcharString s8= “bindbajix”;
String s9= s8.replace(‘b’, ‘m’);//returns “mindmajix”
compareTo(String str)Returns a value based on a comparison of strings in lexical order. 
  • Negative value if string 1 is higher than string 2
  • Positive value if string 1 is less then string 2
  • Zero if string 1 is equal to string 2
String s10= “mindmajix 1”;
String s11= “mindmajix 2”;
int i = s10.compareTo(s11);
//returns  a negative value
compareToIgnoreCase(string str)Returns same value as of compareTo (), but ignores the case considerations.String s12 =”Mindmajix”;
String s13= “mindmajix”;
int i= s12.compareToIgnoreCase(s13);//returns 0

[ Learn How to Install Debugbar Tool in Selenium ]

Access Modifiers in Java

As the name implies, access modifiers in Java are used to control the scope of classes, variables, methods or constructors. It is not necessary that all modifiers will be applicable for all; few are for classes whereas few are for methods or variables. Moreover, there will be few which are applicable to both.

Once program has access to a class, it also gives the program, accessibility of that class’ members. There are four types of access modifiers used in Java:

  • Default – No keyword required
  • Public
  • Private
  • Protected.

Other modifiers used with class are: static, final and strictfp.

If a class is public, that means it is visible to all other classes. But, if it has no modifier, that means it is a default class and only visible in its own package. 

In Selenium, we mainly use public, private and protected access modifiers to create our automation scripts. So, let us understand them in detail what they are and how we can use them in our scripts.

1. Public

The public access modifier is described with the keyword public. It has the greatest scope amongst all other access modifiers. No restriction is set on the scope of public data members. When classes, methods, or data members are defined as public, then they are reachable from everywhere (Not only inside the package, also from outside the package.) Below is an example for the same:

Example:

package pack1; 
 
public class printstring 
{ 
   public void print() 
      { 
          System.out.println("Learn Java for Selenium"); 
      } 
} 
 
package pack2; 
 
import pack1.*; 
class demo 
{ 
    public static void main(String args[]) 
      { 
          printstring obj = new printstring; 
          obj.print(); 
      } 
}

Output:

Learn Java for Selenium

In the above example, we have demo class accessing printstring class’ print() method. If printstring class wasn’t declared as public, then program will end up with a compile-time error.

Whenever we access any class method or variable, compiler will first check class’ accessibility. So if we have any class which is not public but its methods and variable are declared as public, in that case, we won’t be able to access those variables or methods as class is not set as public even though variables/methods are declared public. In that case, compiler will give error.

[ Check out How to Setup and Configure Selenium Webdriver with Eclipse ]

2. Private

The private access modifier is described with the keyword private.  Private means it is only reachable within the same class. If methods or any data members are declared as private, then they are only accessible in the same class. They are not accessible from the other classes of the same or different package.  Private modifier is mostly used for methods or variables. 

Example:

package pack1; 
  
class printstring  
{ 
   private void print() 
    { 
        System.out.println("Learn Java for Selenium"); 
    } 
} 
  
class demo 
{ 
   public static void main(String args[]) 
      { 
          printstring  obj = new printstring (); 
          //let’s try to access private method of another class 
          obj.print(); 
      } 
}

Output:

error: print() has private access in printstring
        obj.print();

In above example, demo class is trying to access private method print of printstring class. As it cannot be accessible from the class of same or different package, program will give an error.

3. Protected

The protected access modifier is described with the keyword protected. If methods or variables are declared as protected, then they can be reachable from any class residing in the same package and subclasses of that class in different packages.

Example:

package pack1; 
public class printstring 
{ 
   protected void print() 
    { 
        System.out.println("Learn Java for Selenium"); 
    } 
} 
 
package pack2; 
import pack1.*; 
  
//Class demo is subclass of printstring 
class demo extends printstring 
{ 
   public static void main(String args[]) 
   {   
       demo obj = new demo();   
       obj.print();   
   }   
      
}

Output:

Learn Java for Selenium

In the above example, there are two packages, pack1 and pack2. Class printstring is declared as public in pack1 so that it is accessible in pack2. Method print in class printstring is protected. So, print() method can be accessible from all the classes of pack1 and any subclasses of printstring class. Class demo in pack2 is inheriting class printstring in pack1. Hence, protected method print() is accessible from the object of demo class. 

Let us summarize all access modifiers by putting into a table.

Access ModifierSame classSame package subclassSame package non-subclassDifferent package subclassDifferent package non-subclass
PrivateYNNNN
DefaultYYYNN
ProtectedYYYYN
PublicYYYYY

Exception Handling in Java

Exception handling is a powerful mechanism of Java to take care of the runtime errors without interrupting normal flow of the program. 

What is an Exception?

An exception is an abnormal or unwanted condition which occurs during the program execution and disrupts the flow of program.

The core advantage of exception handling is to maintain the flow of the program. Let us understand this by one example:

Consider a program of 10 expressions like shown below:

Expr 1;  
Expr 2;  
Expr 3;  
Expr 4;  
Expr 5;
Expr 6;   //exception occurs  
Expr 7;  
Expr 8;  
Expr 9;  
Expr 10; 

Now, if there is an exception occurring at expression 6, the rest of the code after that will not be executed. In this case, expr7 to 10 will be ignored. Now, if we include exception handling in our code, rest of the expressions will be executed. 

Exception vs Error

Exception:

An exception occurs in the program which can be resolved and handled in program code. There are 2 types of exceptions available:

Checked Exception: Checked exceptions are verified at compile time only. They must be handled by programmer in code. If not, then we will be getting compiler error. Some of the checked exceptions are SQLException, FileNotFoundException, IOException, etc.  

Unchecked Exception: Unchecked exceptions are not checked by compiler while compiling the code.  They are checked at runtime only.

For example, NullPointerException ,ArithmeticException, ArrayIndexOutOfBoundsException, etc.  In Selenium, we will be handling unchecked exceptions like StaleElementReferenceException,  TimeoutException, NoSuchWindowException, NoSuchElementException, etc.

Error:

Error cannot be resolved by a programmer. They are irrecoverable. Error is also one type of unchecked exception. They occur due to some scarcity of system resources. For Example: JVM Error, Stack overflow, hardware error, etc.

Exception Keywords in Java

Below 5 keywords are used to handle exceptions in Java.

  • try: The “try” keyword is the indicator of a block where we need to put our exception code. The “try” block cannot be used alone. It must be accompanied with a catch or finally.
  • catch: The “catch” block cannot be used standalone. It must be used along with “try” block. It is used to handle the exception. Multiple catch blocks are possible in Java to handle multiple types of exceptions. 
  • finally: The “finally” block is used to execute the cleanup code in the program. It will be executed irrespective of whether the exception is handled or not. There should be only one “finally” block even if code is having multiple try...catch block.
  • throw: The “throw” keyword is entered to throw a manual exception. 
  • throws: The "throws" keyword is used to declare exceptions. It is not used to throw an exception. It indicates the possibility of exception in the method. It must always be used with method signature. 

Exception Handling Example

Let us go through different examples of Exception Handing in Java.

1. try…catch block

In this example, we can see that after handling exception, control is being passed to the next statement written after try…catch block.

public class DemoException{  
public static void main(String args[]){  
try
{  
   int d=10/0;  
}
 catch (ArithmeticException e)
 {
    System.out.println("Catch block"+ e);
 }  
 System.out.println("rest of the code");  
}  
}  

Output:

Catch block Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code

2. try…catch…finally block

As discussed, we can have one try block followed by multiple catch blocks to handle multiple types of exceptions. The “finally” block is executed even if exception rises or not.

public class DemoException {
    public static void main(String[] args) {
         try
          {
           int a[]={4,8,9};
           System.out.println(a[2]);
           //a[3]=1;// if this line is uncommented then this statement will raise exception of type ArrayIndexOutobouncException. In this case control will got to that block which is handling this exception
           int x=10;
           System.out.println(x/0);
          } 
          catch(ArithmeticException e1)
          {
           System.out.println("number cannot divided by zero"+e1);
          }
          catch(ArrayIndexOutOfBoundsException e2)
          {
           System.out.println("array index out of bound exception"+e2);
          }
          catch(Exception e)
          {
             System.out.println(e);// when any matching exception is not handled then control will come to this block.
          }
          finally
          {
              System.out.println("in finally block"); //this will be executed even if exception is handled or not.
          }
        System.out.println("After try catch finally block");
    }
}

Output:

9
number cannot divided by zerojava.lang.ArithmeticException: / by zero
in finally block
After try catch block

3. throw

The “throw” keyword is entered in code to throw an exception manually by a programmer. In below code, we are throwing an arithmetic exception by giving our own message to display.

public class throwDemo{
public static void main(String[] args) {
        throw new ArithmeticException("throwing  arithmetic exception"); 
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: throwing  arithmetic exception
at throwDemo.main(throwDemo.java:4)

4. throws

The “throws” keyword is used with method signature to mention that this method might throw an exception. To avoid dealing with try and catch block, we can simply write throws expression to avoid any compile time error. 

public class ThrowsExceptionDemo {
    public static void main(String[] args) throws FileNotFoundException {
        openF("G: est.txt");
    }
    public static void openF(String fname) throws FileNotFoundException{
        FileInputStream f= new FileInputStream(fname);
    }
}

Decision Making in Java

Decision-making statements are statements which decide what to execute and when. They are similar to decision making in real time. Control flow statements control the flow of a program’s execution. Here, flow of execution will be based on state of a program. We have 3 decision-making statements available in Java.

1. Simple if Statement

Simple if statement is the basis of decision-making statements in Java. It decides if certain amount of code should be executed based on the condition. 

Syntax:

if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false

Example:

class ifTest
{
    public static void main(String args[])
    {
        int x = 5;
        if (x > 10)
            System.out.println("Inside If");
        System.out.println("After if statement");
    }
} 

Output:

After if statement

2. if…else Statement

In “if…else” statement, if condition is true, then statements in “if” block will be executed but if it comes out as false then “else” block will be executed. 

Syntax: 

if (condition) { 
Statemen 1; //if condition becomes true then this will be executed
}
else {
 Statement 2; //this will be executed irrespective of condition becomes true or false
}

Example:

class ifelseTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 9; 
        if (x > 10) 
            System.out.println("i is greater than 10"); 
        else
            System.out.println("i is less than 10"); 
        System.out.println("After if else statement"); 
    } 
}

Output:

i is less than 10
After if else statement

3. Nested if statement

“Nested if” statement is “if” inside an “if” block. It is same as normal “if…else” statement, but they are written inside another “if…else” statement. 

Syntax:

if (condition1) { 
Statemen 1; //executed when condition1 is true
if (condition2) { 
Statement 2; //executed when condition2 is true
}
else {
 Statement 3; //executed when condition2 is false
}
}

Example:

class nestedifTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 25; 
        if (x > 10) 
        {
            if (x%2==0)
            System.out.println("i is greater than 10 and even number"); 
            else
            System.out.println("i is greater than 10 and odd number"); 
        }
        else
        {
            System.out.println("i is less than 10");
        }
        System.out.println("After nested if statement"); 
    } 
} 

Output:

i is greater than 10 and odd number 
After nested if statement

4. if...else if…else statement

“if…else if” statements will be used when we need to compare the value with more than 2 conditions. They are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last “else” statement will be executed.

Syntax:

if (condition2) { 
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
  Statement 2; // if condition2 becomes true then this will be executed
}
.
.
else {
 Statement 3; //executed when no matching condition found
}

Example:

class ifelseifTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 2; 
        if (x > 10) 
        {
            System.out.println("i is greater than 10"); 
        }   
        else if (x <10)
            System.out.println("i is less than 10"); 
        }
        else
        {
            System.out.println("i is 10");
        }
        System.out.println("After if else if ladder statement"); 
    } 
}

Output:

i is less than 10 
After if else if ladder statement

Looping Statements in Java

Looping statements are the statements which execute a block of code repeatedly until some condition meets the criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.

1. While Loop

While loops are the simplest kind of loop. It checks and evaluates the condition and if it is true, then executes the body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a Boolean expression. If int or string is used instead, compile will give the error.

Syntax:

while (condition)
{
   statement1;
}

Example:

class whileLoopTest 
{ 
    public static void main(String args[]) 
    { 
        int j = 1; 
        while (j <= 10) 
        { 
            System.out.println(j); 
            j = j+2; 
        } 
    } 
} 

Output:

1
3
5
7
9

2. Do…while

Do…while works same as while loop. It has only one difference that in do…while, condition is checked after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of loop will be executed at least once before checking the condition

Syntax:

do
{
statement1;
}
while(condition);

Example: here 

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

Output:

10

3. For Loop

It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is easy to debug structure in Java.

Syntax:

for (initialization; condition; increment/decrement)
{
    statement;
}

Example:

class forLoopTest 
{ 
    public static void main(String args[]) 
    { 
        for (int j = 1; j <= 5; j++) 
            System.out.println(j); 
    } 
} 

Output:

1
2
3
4
5

Branching Statements in Java

Branching statements jump from one state to another and transfer the execution flow. There are 3 branching statements in Java.

1. Break

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in loop to stop the execution and comes out of loop. When there are nested loops, then break will terminate the innermost loop.

Example:

class breakTest 
{ 
    public static void main(String args[]) 
    { 
        for (int j = 0; j < 5; j++) 
        { 
            // come out of loop when i is 4. 
            if (j == 4) 
                break; 
            System.out.println(j); 
        } 
        System.out.println("After loop"); 
    } 
} 

Output:

0
1
2
3
4
After loop

2. Continue

Continue statement works same as break but the difference is it only comes out of loop for that iteration and continues to execute the code for next iterations. So, it only bypasses the current iteration.

Example:

class continueTest 
{ 
    public static void main(String args[]) 
    { 
        for (int j = 0; j < 10; j++) 
        { 
            // If the number is odd then bypass and continue with next value
            if (j%2 != 0) 
                continue; 
            // only even numbers will be printed
            System.out.print(j + " "); 
        } 
    } 
} 

Output:

0 2 4 6 8

3. Return

Return statement is used to transfer the control back to calling method. Compiler will always bypass any sentences after “return” statement. So, it must be at the end of any method. They can also return a value to the calling method.

Example: Here method getwebURL() returns the current URL to the caller method.

public String getwebURL()
{
    String vURL= null;
    try {
        vURL= driver.getCurrentUrl();
    }
    catch(Exception e)  {
        System.out.println("Exception occured while getting the current url : "+e.getStackTrace());
    }
    return vURL;
}

Conclusion

So, these are the basic code constructs of Java which we can utilize while writing scripts in Selenium web driver.

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Selenium Training Mar 23 to Apr 07View Details
Selenium Training Mar 26 to Apr 10View Details
Selenium Training Mar 30 to Apr 14View Details
Selenium Training Apr 02 to Apr 17View Details
Last updated: 04 Apr 2023
About Author

Soujanya is a Senior Writer at Mindmajix with tons of content creation experience in the areas of cloud computing, BI, Perl Scripting. She also creates content on Salesforce, Microstrategy, and Cobit. Connect with her via LinkedIn and Twitter.

read more
Recommended Courses

1 / 15