0% found this document useful (0 votes)
6 views

Learning Selenium With Java

Uploaded by

Jaideep Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Learning Selenium With Java

Uploaded by

Jaideep Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module 1: Basics of Java

1.1 Introduction to Java

Overview of Java and its applications


1. What is Java?
Java is a versatile, object-oriented, and high-performance programming language. It
was developed by Sun Microsystems in the mid-1990s and is now maintained by
Oracle Corporation. One of the key features of Java is its "write once, run anywhere"
philosophy, meaning the code written in Java can run on any device with a Java
Virtual Machine (JVM).

2. Key Features of Java:


a. Platform Independence: Java code can run on any device with a JVM, making
it platform-independent.
b. Object-Oriented: Java follows the principles of object-oriented programming,
emphasising the use of classes and objects.
c. Security: Java provides a secure runtime environment, protecting against
various security threats.
d. Multithreading: Java supports concurrent execution of multiple threads,
enhancing performance.
3. Java Applications:Java is used in various domains and applications, including:
a. Web Development: Java is widely used for building dynamic and robust web
applications using frameworks like Spring and JavaServer Faces (JSF).
b. Mobile Applications: Android apps are primarily developed using Java or
Kotlin, making Java a key player in the mobile app development landscape.
c. Enterprise Applications: Many large-scale, enterprise-level applications are
built using Java technologies due to their scalability and reliability.
d. Desktop Applications: Java Swing and JavaFX are used for creating desktop
applications with graphical user interfaces (GUIs).
e. Big Data Technologies: Java is integral in Big Data technologies like Apache
Hadoop and Apache Spark.
4. Example:
"Hello, World!" Program in Java:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output: Hello, World!


This simple program demonstrates the basic structure of a Java program. The main
method is the entry point, and System.out.println is used to print the message.

In summary, Java is a powerful, versatile programming language with a wide range of


applications, from web development to mobile apps and enterprise-level systems. Its
features and platform independence make it a popular choice for developers worldwide.

Setting up Java Development Kit (JDK)

1. Download JDK:
Visit the official Oracle website or an OpenJDK distribution to download the latest
version of JDK.Follow the installation instructions provided for your operating system
(Windows, macOS, or Linux).
2. Install JDK:
Run the installer and follow the on-screen instructions. During the installation, set the
path for the JDK. This path is used by your operating system to find the Java
executable.
3. Verify JDK Installation:
Open a command prompt (Windows) or terminal (macOS/Linux). Type the following
command and press Enter: java -version You should see information about the
installed Java version.

Setting up Eclipse Integrated Development Environment (IDE)

1. Download Eclipse:
Visit the official Eclipse website and download the Eclipse IDE for Java Developers.
Choose the appropriate version for your operating system.
2. Install Eclipse:
Extract the downloaded Eclipse archive to a location on your computer. Inside the
Eclipse folder, you'll find the Eclipse executable. Run it.
3. Configure Eclipse:
When you first run Eclipse, it will prompt you to select a workspace (a folder where
your projects will be stored). After selecting a workspace, click "Launch" to open
Eclipse.
4. Create a Java Project:In Eclipse, go to "File" -> "New" -> "Java Project." Give your
project a name and click "Finish."
5. Create a Java Class: Right-click on the ‘src’ folder of your project in the "Package
Explorer" on the left. Go to "New" -> "Class." Enter a class name (e.g., HelloWorld)
and check the option to include the public static void main(String[] args) method.
Click "Finish."
6. Write a Simple Java Program: public class HelloWorld { public static void
main(String[] args) { System.out.println("Hello, Eclipse!"); }}
7. Run the Java Program:Right-click on the HelloWorld class file in the "Package
Explorer."Select "Run As" -> "Java Application."Output: Hello, Eclipse! This basic
setup allows you to write, compile, and run Java programs in Eclipse.
1.2 Variables and Data Types

Understanding variables: Declaring and Initializing

1. Understanding Variables:
Variables are like containers used to store data in a program. They have a name
(identifier) and a data type that determines what kind of data they can hold. In Java,
variables must be declared before they can be used.

2. Declaring Variables:
Declaration: It's like telling the computer, "Hey, I'm going to need a spot to store some
data."
Syntax: dataType variableName;

int myNumber;

3. Initializing Variables:
Initialization: Giving an initial value to the variable.
Syntax: variableName = value;

myNumber = 42;

4. Combining Declaration and Initialization:


You can declare and initialize a variable in one step.

int myAge = 25;

5. Example Code:

package myFirstPackage;
public class VariablesExample {
public static void main(String[] args) {
//Declaration
int myNumber;

//Initialization
myNumber = 10;

//Combined Declaration and Initialization


int myAge = 27;

System.out.println("My Number: " + myNumber);


System.out.println("My Age: " + myAge);
}
}

6. Output:
My Number: 10
My Age: 27

Conclusion:
Declaration: Creating a variable's placeholder.
Initialization: Assigning an initial value to the variable.
Combining: You often declare and initialize variables together for simplicity.

Data Types

1. Common Data Types in Java:


a. int: Used to store integer numbers (whole numbers without decimal points).
int myNumber = 10;
b. float: Used to store floating-point numbers (numbers with decimal points). It
requires appending 'f' or 'F' at the end.
float myFloatNumber = 3.14f;
c. double: Similar to float but can store larger decimal numbers with more
precision.double
myDoubleNumber = 3.14159265359;
d. char: Used to store a single character (letter, digit, punctuation, etc.) enclosed
in single quotes.
char myChar = 'A';
e. boolean: Used to store true or false values.
boolean isJavaFun = true;

7. Example Code:

package myFirstPackage;
public class Variables {
public static void main(String[] args) {
int myNumber = 10;
float myFloatNumber = 3.14f;
double myDoubleNumber = 3.1451691529;
char myChar = 'A';
boolean isJavaFun = true;

System.out.println("My Number: " + myNumber);


System.out.println("My Float Number: " + myFloatNumber);
System.out.println("My Double Number: " + myDoubleNumber);
System.out.println("My character: " + myChar);
System.out.println("Is Java Fun? " + isJavaFun);
}
}

8. Output:

My Number: 10
My Float Number: 3.14
My Double Number: 3.1451691529
My character: A
Is Java Fun? true

Type casting in Java

1. What is Type Casting?


Definition: Type casting is the process of converting one data type into another.
Why: It's necessary when you want to assign a value of one data type to a variable of
another data type.
2. Two Types of Type Casting:
a. Implicit Type Casting (Widening):
Definition: Automatically done by the compiler.
Scenario: Assigning a smaller data type to a larger data type.
Example:

int myInt = 10;


double myDouble = myInt; // Implicit casting from int to double

b. Explicit Type Casting (Narrowing):


Definition: Manually done by the programmer.
Scenario: Assigning a larger data type to a smaller data type.
Syntax: dataType variableName = (dataType) value;
Example:double myDouble = 10.5;
int myInt = (int) myDouble; // Explicit casting from double to int
3. Be Careful with Data Loss:
When you perform explicit casting from a larger data type to a smaller one, you may
lose information.
Example:
double myDouble = 10.9;

int myInt = (int) myDouble; // The decimal part is truncated, myInt becomes 10

4. Example Code:

package myFirstPackage;
public class TypeCastingExample {
public static void main(String[] args) {
//Implicit Casting (Widening)
int myInt = 10;
double myDouble = myInt;
System.out.println("Implicit Casting (Widening): " + myDouble);

//Explicit Casting (Narrowing)


double anotherDouble = 15.75;
int anotherInt = (int) anotherDouble;
System.out.println("Explicit Casting (Narrowing): " +
anotherInt);
}
}
5. Output:

Implicit Casting (Widening): 10.0


Explicit Casting (Narrowing): 15

Conclusion:
● Implicit casting is done automatically by the compiler.
● Explicit casting requires manual intervention and may result in data loss if not done
carefully.
● Always be mindful of potential information loss when narrowing data types.

1.3 Control Flow in Java

Introduction to control flow (if-else statements)

1. What is Control Flow?


Definition: Control flow refers to the order in which statements are executed in a
program.
Purpose: It allows us to make decisions and execute different code blocks based on
conditions.

2. if Statement:
Usage: Used to execute a block of code if a specified condition is true.
Syntax:

if (condition) {
// Code to be executed if the condition is true
}

3. else Statement:
Usage: Used with the if statement to execute a block of code if the condition is false.
Syntax:

if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}

4. Example Code:

package myFirstPackage;
public class ControlFlowExample {
public static void main(String[] args) {
int age = 20;
// Example of if statement
if (age >= 18) {
System.out.println("You are an adult");
}

// Example of if else statement


if (age >= 18) {
System.out.println("You are an adult");
} else {
System.out.println("You are a minor");
}
}
}

5. Output:

You are an adult


You are an adult

Conclusion:
● Control flow structures like if and else statements allow you to control the flow of your
program based on conditions.
● The if statement is used for basic conditional execution.
● The if-else statement is used when you want to execute different code blocks based
on whether a condition is true or false.

Looping structures (for, while, do-while)

1. Introduction to Loops:
Definition: Loops are structures in programming that allow a set of instructions to be
repeated multiple times.
Purpose: They help in executing repetitive tasks and avoid code duplication.
2. for Loop:
Usage: Executes a block of code a specific number of times.
Syntax:

for (initialization; condition; update) {


// Code to be repeated
}

Example:

package myFirstPackage;
import java.util.Scanner;
public class ForLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the number for which you want to calculate the factorial
System.out.println("Enter a non-negative integer: ");
int number = scanner.nextInt();

// Check the input is a non-negative integer


if (number < 0) {
System.out.println("Please enter a non-negative number:
");
number = scanner.nextInt();
}

long factorial = 1;

// Calculate the factorial using the for loop


for (int i = 1; i < number; i++) {
factorial *= i;
}

// Print the result


System.out.println("The factorial of " + number + " is " +
factorial);

// Close the scanner


scanner.close();
}
}

Output:

Enter a non-negative integer:


4
The factorial of 4 is 24

3. while Loop:
Usage: Executes a block of code as long as a specified condition is true.
Syntax:

while (condition) {
// Code to be repeated
}

Example:

package myFirstPackage;
public class WhileLoopExample {
public static void main(String[] args) {
// Set the desired outcome - rolling a 6
int targetnumber = 6;

// Initialize variables
int rolls = 0, result = 0;
// Simulate the dice rolling game with while loop
while (result != targetnumber) {
// Roll the six sided die
result = (int) (Math.random() *6) + 1;

// Increment the number of rolls


rolls++;

// Print the result of each roll


System.out.println("Roll " + rolls + ": " + result);
}

// Print the number of rolls needed to achieve the result


System.out.println("It took " + rolls + " rolls to get a " +
targetnumber);
}
}

Output:

Roll 1: 5
Roll 2: 3
Roll 3: 3
Roll 4: 5
Roll 5: 6
It took 5 rolls to get a 6

4. do-while Loop:
Usage: Similar to the while loop but guarantees at least one execution of the block of
code.
Syntax:

do {
// Code to be repeated
} while (condition);

Example:

package myFirstPackage;
import java.util.Scanner;
public class DoWhileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Generate a secret number between 1 and 10 for simplicity


int secretNumber = (int) (Math.random() * 10 + 1);

// Variables to store user input


int userGuess;

// Do While loop for the number guessing game


do {
// Prompt the user for the guess
System.out.println("Guess the Secret number (between 1 to
10): ");
userGuess = scanner.nextInt();

// Check if the user is correct


if(userGuess == secretNumber){
System.out.println("Congratulations!! You guessed
it");
}
else {
System.out.println("Incorrect Guess. Try again.");
}
} while (userGuess != secretNumber);
}
}

Output:

Guess the Secret number (between 1 to 10):


4
Incorrect Guess. Try again.
Guess the Secret number (between 1 to 10):
3
Congratulations!! You guessed it

5. Nested Loops:
Loops can be nested inside each other.

Example:

package myFirstPackage;
public class NestedLoopsExample {
public static void main(String[] args) {
int rows = 6;

// Print the right angled triangle using nested loops


for(int i =1; i <= rows; i++) {
for(int j = 1; j <= i; j++){
System.out.print(j + "");
}
System.out.println();
}
}
}

Output:

1
12
123
1234
12345
123456

Conclusion:
● Loops are essential for repetitive execution of code in Java.
● The for loop is suitable when the number of iterations is known.
● The while loop is used when the condition is known at the beginning.
● The do-while loop guarantees at least one execution.

Break and continue statements

1. Introduction:
Purpose: Break and continue statements are control flow statements in Java that
alter the flow of a loop.
Usage: They provide more control over loop execution based on certain conditions.

2. Break Statement:
Usage: Used to terminate the loop prematurely, skipping the rest of the loop's code.
Scenario: Helpful when a specific condition is met, and you want to exit the loop.
Example:

package myFirstPackage;
import java.util.Iterator;
import java.util.Scanner;
public class BreakExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int[] numbers = {25, 43, 56, 71, 94, 68, 32, 12, 58, 80};

System.out.println("Please enter the number to search: ");


int target = scanner.nextInt();

boolean found = false;


for (int i = 0; i < numbers.length; i++) {
if(numbers[i] == target) {
found = true;
System.out.println("Your number is found at index: "
+ i);
break; // Exit the loop once the target number is
found.
}
}

if (!found) {
System.out.println("Your number is not found.");
}
}
}
Output:

Please enter the number to search:


12
Your number is found at index: 7

3. Continue Statement:
Usage: Skips the rest of the loop's code for the current iteration and moves to the
next iteration.
Scenario: Useful when you want to skip specific iterations based on a condition.
Example:

package myFirstPackage;
import java.util.Iterator;
import java.util.Scanner;
// Program to add all even numbers in a given range.
public class ContinueExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the starting number of the range: ");


int start = scanner.nextInt();

System.out.println("Enter the ending number of the range: ");


int end = scanner.nextInt();

if (start > end) {


System.out.println("Start number is greater than end.");
}
else {
int sum = 0;
for(int i = start; i <= end; i++) {
if(i % 2 != 0) {
continue;
}
sum += i;
}
System.out.println("The sum of all even numbers in range
is: " + sum);
}
}
}

Output:

Enter the starting number of the range:


1
Enter the ending number of the range:
10
The sum of all even numbers in range is: 30

Conclusion:
● Break: Terminates the loop when a specific condition is met.
● Continue: Skips the rest of the code for the current iteration and moves to the next
iteration.
● Use Cases: Useful for adding flexibility to loop structures and handling specific
cases.
● Note: While these statements provide control, they should be used judiciously to
ensure the logic remains clear and understandable
1.4 Introduction to Object-Oriented Programming (OOP)

Understanding the principles of OOP

Importance of OOP in Java

1.5: Classes and Objects

Defining classes and objects in Java

Constructors and methods

Access modifiers (public, private, protected)

1.6: Inheritance

Understanding inheritance and its types

Creating subclasses and superclasses

Overriding methods

1.7: Polymorphism

Exploring polymorphism in Java

Method overloading and overriding

Compile-time vs. runtime polymorphism

Module 2: Core Java

2.1 Introduction to Java Collections Framework

Overview of Java Collections

Importance and use cases of Collections


2.2: ArrayList in Java

Understanding ArrayList

Operations on ArrayList (adding, removing, updating elements)

Iterating through an ArrayList

2.3: HashMap in Java

Introduction to HashMap

Adding, removing, and updating elements in a HashMap

Iterating through a HashMap

Explore other Java Collection classes like LinkedList, HashSet, and


TreeMap.

Understand the differences between List and Set interfaces.

2.4 Exception Handling

Introduction to exceptions in Java

Types of exceptions (checked and unchecked)

Handling exceptions using try, catch, and finally blocks

2.5 Exception Handling - Advanced Concepts

Multiple catch blocks

Using throws and throw keywords

Custom exceptions in Java

2.6 File Handling in Java - Basics


Working with files in Java

Reading and writing text files

Understanding FileReader and FileWriter

2.7 File Handling in Java - Advanced Concepts

Reading and writing binary files

Using BufferedReader and BufferedWriter

Exception handling in file operations

Module 3: Selenium Fundamentals

3.1 Install Java Development Kit (JDK)

Download and install the latest version of JDK.

Set up the environment variables for Java.

3.2 SetUp Eclipse IDE

Download and install the Eclipse IDE.

Configure Eclipse for Java development.

3.3 Setup Selenium WebDriver with Java

Download the Selenium WebDriver Java bindings.

Create a new Java project in Eclipse.

Add Selenium JAR files to your project.

Understand the concept of WebDriver and its role in Selenium.

Familiarise yourself with the structure of a basic Selenium script.


3.4 Navigating with Selenium WebDriver

Learn how to open a browser using WebDriver.

Understand navigation methods like get(), navigate().to(),


navigate().back(), and navigate().forward().

3.5 Locating Elements in Selenium

Explore different methods for locating elements: by ID, by name, by


class name, by tag name, by link text, and by partial link text.

Understand the concept of CSS selectors and XPath for element


identification.

3.6 Interacting with Web Elements

Learn how to interact with various types of web elements, like buttons,
text fields, checkboxes, and radio buttons.

Understand methods like click(), sendKeys(), getText(), and


getAttribute().

3.7 Advanced Interactions and Waits

Explore advanced interactions such as handling dropdowns, working


with checkboxes, and selecting from radio buttons.

Understand the importance of implicit and explicit waits in Selenium.

Module 4 Advance Selenium and Practice

4.1 Synchronisation in Selenium

Understand the importance of synchronisation in Selenium.

Explore implicit waits, explicit waits, and FluentWait.


Learn how to handle synchronisation issues.

4.2 Handling Dropdowns and Frames

Learn how to work with dropdowns using Select class.

Understand switching between frames and handling elements inside


frames.

4.3 Handling Windows and Tabs

Explore handling multiple browser windows and tabs.

Learn techniques for switching between windows and tabs.

Understand how to perform actions in different browser instances.

Practice synchronisation with different scenarios to ensure stability in


your scripts.

Experiment with various types of dropdowns and frames on web pages.

4.4 Introduction to TestNG

Understand the role of TestNG in Java test automation.

Learn how to install and configure TestNG in your project.

Explore TestNG annotations and their significance.

4.5 TestNG Features and Test Suites

Explore TestNG features such as parameterization, grouping, and


dependencies.

Learn how to create and run test suites in TestNG.

4.6 Introduction to JUnit


Understand the basics of JUnit and its role in Java testing.

Learn how to set up JUnit in your project.

Practice creating and running simple tests with both TestNG and JUnit.

Explore the reporting capabilities of TestNG.

4.7 Automation Scripting Basics

Create a simple Selenium script to open a website and perform basic


interactions (e.g., clicking a button or filling a form).

Implement assertions to validate the expected outcomes.

4.8 Advanced Selenium Features

Explore advanced Selenium features like handling cookies, capturing


screenshots, and handling browser navigation history.

Learn about taking screenshots for better debugging.

4.9 Project Integration and Challenges

Integrate Selenium with your existing Java project.

Tackle more complex scenarios, such as handling dynamic elements or


dealing with complex web page structures.

Challenge yourself with a mini-project to reinforce your learning.

Experiment with different locators and strategies for element


identification.

Consider incorporating Page Object Model (POM) for better code


organisation.

You might also like