text: The following blog on Java tutorial for Selenium WebDriver makes you learn basic Java concepts needed to write a test case in Selenium WebDriver.
  The basic Java concepts are as follows,
  Table of Contents
  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.
  Table of Contents
  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 real world, an object is defined as a thing which we can see, touch and feel. It has both state and behavior. For example, dog is an object which has 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 which 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 guide to create 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.
  Knowledge on data types and variables helps to easily understand programming in Java for Selenium.
  What is a data type?
  A data type is an indicator for 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.
  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;
  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;
  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;
  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,
  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
  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.
  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.
  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
  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.
  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 –
  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];
  There are two types of array based upon the size –
  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.
  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.
  3. 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 while loop. But the only difference is, the do-while loop executes the code atleast one time irrespective of the return value of boolean expression.
  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.
  Though methods and constructors look similar, they are different as,
  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.
  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.
  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,
  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, the accessibility of that class’ members. There are four types of access modifiers used in Java:
  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.
  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 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.
  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.
  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.
  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:
  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.
  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.
  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 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.
  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
  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
  “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
  “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) { <span style="white-space:pre"> </span>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 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.
  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
  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
  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 jump from one state to another and transfer the execution flow. There are 3 branching statements in Java.
  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
  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
  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; }
  So, these are the basic code constructs of Java which we can utilize while writing scripts in Selenium web driver.
  Free Demo for Corporate & Online Trainings.