Switch Case example in Java Selenium

It is also one type of Conditional Statements, which is basically used to write for menu driven programs. When ever there are more number of options to select then we will go for Switch statement i.e., single expression with many possible options. The same thing can be done using if..else statements but it can get very confusing and if..else statement is difficult to change when it becomes highly nested.

Syntax:

switch(expression) {
Case value1: statement1;
	Break;
Case value2: statement2;
	Break;
Case value3:statement3;
	Break;
……..
default: statement;
}

This expression is compared with each case value until the match found. If no case value is matched then default case will get executed. The expression value type may be of type byte, short, int, char. From 1.5v Wrapper classes and enum are allowed to take as conditional expression and from 1.7v Strings are also allowed.

Integer values are checked for equality using == operator and String value invoke equals() for checking equality.

Here is the simple example for switch :-

public class SwitchDemo {
	public static void main(String[] args) {
		int x=2;
		switch (x) {
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;

		default:
			System.out.println("default");
			
		}
	}
} 

Output: two

Break is optional in switch case. If we don’t mention break for the statement after the case, once the match case value found, the statements after next case also executes irrespective of value matches or not.

Let us look this Example:

public class SwitchDemo {
	public static void main(String[] args) {
		int x=2;
		switch (x) {
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			
		case 3:
			System.out.println("three");
			break;
		default:
			System.out.println("default");
			
		}
	}
}

Output:
two
three
This is called fall through in switch. So it is necessary to use break for every case.

Now let us see the example in Selenium using Switch.

public void openBrowser(String browserType) {
		switch (browserType) {
		case "firefox":
			driver = new FirefoxDriver();
			break;
		case "chrome":
			driver = new ChromeDriver();
			break;
		case "IE":
			driver = new InternetExplorerDriver();
			break;
		default:
			System.out.println("browser : " + browserType + " is invalid, Launching Firefox as browser of choice..");
			driver = new FirefoxDriver();
		}
	}

Now, based on the browser type value we pass, the driver will be initiated. We can also use the above script to run selenium tests in multiple browsers using the same switch. We can define it as Parameterized tests that execute based on each parameter we defined for each test in testng.xml file.

Java Tutorials for Selenium: 

Add new comment