You are on page 1of 42

HELPING HANDS

JAVA FOR SELENIUM

2017
COPYRIGHT NOTICE
Copyright © 2017 Helping Hands
All rights reserved. These materials are confidential and proprietary to Helping hands and no part of these materials should be reproduced, published in any form by any
means, electronic or mechanical including photocopy or any information storage or retrieval system nor should the materials be disclosed to third parties without the
express written authorization of Helping Hands. 1
Installations needed to learn JAVA

1.Install Java. Go to
http://www.oracle.com/technetwork/java/javase/downloads/index.html
for Java EE Developers
After installing
• Go to MyComputer properties -> advanced tab -> environment variables
• Set JAVA_HOME =C:\Program Files\Java\jdk1.8.0_66
• Set PATH C:\Program Files\Java\jdk1.8.0_66\bin
Java 1.8.0_66
For steps to install visit
https://www.whatismybrowser.com/guides/how-to-install-java/windows
2. Eclipse: mars 2 Eclipse IDE for Java EE Developers
2. Selenium 2.53.1
3. Apache POI 3.11

2
Installations needed to learn JAVA

2. Eclipse:
Go to https://eclipse.org/downloads/packages/release/Mars/2
mars 2 Eclipse IDE for Java EE Developers
3. Selenium 2.53.1
Go to http://www.seleniumhq.org/download/
Install Java client
4. Apache POI 3.11
Go to https://poi.apache.org/download.html
Download jar file to computer.

You can add a jar in Eclipse by right-clicking on the Project → Build Path →
Configure Build Path. Under Libraries tab, click Add Jars or Add External
JARs and give the Jar.

3
Installations needed to learn JAVA

Download and install firepath and firebug

• Go to firebug add-on Installation page using URL -


> https://addons.mozilla.org/en-us/firefox/addon/firebug/. It show firebug
add-on Installation button "Add to Firefox" as bellow.
• Go to Fire path add on Installation page using URL -
> https://addons.mozilla.org/en-us/firefox/addon/firepath/
• Stepwise installation for firebug and firepath
http://www.software-testing-tutorials-automation.com/2015/07/steps-to-
install-firebug-and-firepath.html

4
Introduction to JAVA

• Java is a general-purpose computer programming language


developed by Sun Microsystems.

• It is concurrent, class-based, object-oriented


and specifically designed to have as few
implementation dependencies as possible.

• The latest release of the Java Standard Edition is Java SE 8.

5
Why JAVA Suitable for Selenium?

Java language is suitable for Test automation in Selenium because

It has huge support and community.

It has great frameworks you will need and infrastructure.

It has great capabilities (classes, interfaces, types etc.) to build and


manipulate the levels of abstractions to build your solid framework.

6
Features in JAVA

7
Features in JAVA
Simple :
• Java is Easy to write and more readable and eye catching.
• Java has a concise, cohesive set of features that makes it easy to learn and use.
• Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :
• Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable :
• Java programs can execute in any environment for which there is a Java run-time
system.(JVM)
• Java programs can be run on any platform (Linux,Window,Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
• Java programming is object-oriented programming language.
• Like C++ java provides most of the object oriented features.
• Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :
• Java encourages error-free programming by being strictly typed and performing run-time
checks.

8
Features in JAVA

Multithreaded :
• Java provides integrated support for multithreaded programming.
Architecture-neutral :
• Java is not tied to a specific machine or operating system architecture.
• Machine Independent i.e Java is independent of hardware .
Interpreted :
• Java supports cross-platform code through the use of Java bytecode.
• Bytecode can be interpreted on any platform by JVM.
High performance :
• Bytecodes are highly optimized.
• JVM can executed them much faster .
Distributed :
• Java was designed with the distributed environment.
• Java can be transmit,run over internet.
Dynamic :
• Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time.

9
Structure of JAVA program

A Java program consists of different sections. Some of them are mandatory but some are
optional. The optional section can be excluded from the program depending upon the
requirements of the programmer.

• Documentation Section
It includes the comments to tell the program's purpose. It improves the readability of the
program.

• Package Statement
It includes statement that provides a package declaration.

• Import statements
It includes statements used for referring classes and interfaces that are declared in other
packages.

• Class Section
It describes information about user defines classes present in the program. Every Java program
consists of at least one class definition. This class definition declares the main method. It is from
where the execution of program actually starts.

10
Structure of JAVA program

/* Java Program Structure Example 2 */ //documentation section


package examples; //package section
import java.util.Scanner; //import section
public class Welcome //class section
{
public static void main(String args[])
{
//TODO Auto-generated method stub //Comments // for single line comment
String name; // Multiline comment /*-------*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter your Name :");
name = scan.nextLine();
System.out.println("Hello " +name+ ", this is codescracker");
scan.close();
}
}

11
Structure of JAVA program

• Every java program should have class definition block


class ClassName
{
body
}
• While saving a java program the file name should be same as class name
• Inside class body we can develop any java script Main method is mandatory to start
the execution
• Java file is compiled using a command javac.
• Compiler generates .class file if there are no errors
• By default .class file will be saved in same location where java file is saved
• Every statement in java must be terminated by ;
• The java class can be executed by using a cmd java ClassName
• When ever a class is executed java starts the execution by running main method
• Java executes all the statements sequentially of main method
• Java throws error if main method is not defined .

12
Data types in JAVA
Java support 8 different types of datatypes under 4 families
• Integer : 1.Byte 2.Short 3.Int 4.Long
• Real: float ,Double
• Char: char
• Boolean: boolean

Length of datatypes
• 1byte - 8 bits =(-2^7 to (2^7-1)= -128 to +127
• short - 2 bytes=16bits=(-2^15 to +(2^15-1))
• Int -4 bytes = 32 bits=(-2^31 to (2^31-1))
• Long -8 bytes=64 bits=(-2^63 to (2^63-1))
• Float -4 bytes
• Double - 8 bytes
• Char – 2 bytes
• Boolean -1 byte

Default values for datatypes:


• Integer =0,char=space ,boolean = false,real=0.0

13
Data types in JAVA

Strings :
We can store String data in 3 ways
1.charArray
Char name[]={‘o’,’n’,’e’,’f’,’o’,’r’,’c’,’e’}
2.String class object
String name =“oneforce”;
or
String name= new String(“oneforce”);
name = name.concat(“jayanagar”);

3.String Buffer class


StringBuffer sb =new StringBuffer(“oneforce”);
Sb.append(“jayanagar”);

14
Data types in JAVA

Strings Vs StringBuffer VsStringBuilder

String StringBuffer StringBuilder


Storage Area Constant String Heap Heap
Pool

Modifiable No (immutable) Yes( mutable ) Yes( mutable )

Thread Safe Yes Yes No


Performance Fast Very Slow Fast

15
Types of variables in JAVA

Variable is name of reserved area allocated in memory. In other words, it is a


name of memory location. It is a combination of "vary + able" that means its
value can be changed.

There are three types of variables in java:


• local variable
• instance variable
• static variable

16
Types of variables in JAVA
Local variables are declared in a method or block. When a method is entered, an area
is pushed onto the call stack. This area contains slots for each local variable and
parameter. When the method is called, the parameter slots are initialized to the
parameter values. When the method exits, this area is popped off the stack and the
memory becomes available for the next called method. Parameters are essentially
local variables which are initialized from the actual parameters. Local variables are
not visible outside the method.

Instance variables are declared in a class, but outside a method. They are also
called member or field variables. When an object is allocated in the heap, there is a
slot in it for each instance variable value. Therefore an instance variable is created
when an object is created and destroyed when the object is destroyed. Visible in all
methods and constructors of the defining class, should generally be declared
private, but may be given greater visibility.

Class/static variables are declared with the static keyword in a class, but outside a
method. There is only one copy per class, regardless of how many objects are
created from it. They are stored in static memory. It is rare to use static variables
other than declared final and used as either public or private constants

17
Types of variables in JAVA
public class VariableTypes {
static String ClassName ="Eight"; // Static/class Variables
int marks; // instance variable
void percentobtained(int marks){
double percentage; // Local Variable
percentage = (double)marks/100;
System.out.println("Percentage Obtaied "+percentage);
}
public static void main(String[] args) {
VariableTypes v1 = new VariableTypes();
VariableTypes v2 = new VariableTypes();
v1.marks = 89;
v1.percentobtained(v1.marks);
v1.ClassName = " Nine";
v2.marks = 98;
v1.percentobtained(v2.marks);
v2.ClassName = "Tenth";
System.out.println("Class Name of V1 "+v1.ClassName);
System.out.println("Class Name of V2 "+v2.ClassName);
System.out.println("Marks of V1 "+v1.marks);
System.out.println("Marks of V2 "+v2.marks);
}
}
18
Conditional statements & Loops in JAVA
JAVA IF AND IF-ELSE CONDITIONAL STATEMENT
• An if statement tells the program that it must carry out a specific piece of
code if a condition test evaluates to true.
• If an else statement is present another section of code will bee executes if
the condition test evaluates to false.
SYNTAX :

if ( condition ) // The condition is a boolean expression


statement; // Executes if condition is true
// No enclosing block is required when only one statement
[ else {
statement; // Executes if condition is false
statement; // Enclosing block is necessary when more than one
statement
}
]

19
Conditional statements & Loops in JAVA
JAVA WHILE AND DO-WHILE LOOP
• while will perform a logical test, and if this results in a true condition
execute subsequent statements bounded by {} brackets.
• do while will first execute statements bounded by {} brackets and than
perform a logical test. If the logical test results in a true condition execute the
statements bounded by {} brackets again.
SYNTAX :
// The while syntax
while ( condition ){
statement; // Statements executes as long as condition is true
statement;
}
// This is the do-while syntax
do {
statement; // do-while loop always executes
statement; // its statement body at least once.
statement; // Statements executes as long as condition is true
} while ( condition );
20
Conditional statements & Loops in JAVA
JAVA FOR LOOP.
• A for loop is divided into three parts, an initialization part, a conditional
part and an increment part
• You should sett all initial values in the initialization part of the loop.
• A true from the condition part will execute subsequent statements bounded
by {} brackets. A false from the condition part will end the loop.
• For each loop the increment part will be executed.
...
for ( initialization; condition; incrementor )
statement;
// Initialization are limited to the scope of the for statement
// The condition is a boolean expression (if true the body is executed)
// Following each execution of the body, the incrementor expressions are
evaluated. ...

21
Conditional statements & Loops in JAVA
package examples;
import java.util.Scanner;
public class ConditionalLoop {
public static void main(String[] args) {
String name="default";
String[] StudentNm = new String[100];
int i=0,n = 0;
while (name.startsWith("Z") == false) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your Name not starting with Z:");
name = scan.nextLine();
System.out.println();
if (name.startsWith("A"))
System.out.println("Name is Starting with A");
else
System.out.println("Name is not starting with A");
StudentNm[i] = name;
i++;
n=i;
}
for (i=0;i<=n-1;i++){
System.out.println("Name ="+StudentNm[i]);
}
}
22
Arrays in JAVA
An array is a container object that holds a fixed number of values of a single
type. The length of an array is established when the array is created. After
creation, its length is fixed.

Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the preceding illustration, numbering begins
with 0. The 9th element, for example, would therefore be accessed at index 8.

23
Arrays in JAVA
public class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 5 integers
anArray = new int[5];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
System.out.println("Element at index 0: "+ anArray[0]);
System.out.println("Element at index 1: "+ anArray[1]);
System.out.println("Element at index 2: "+ anArray[2]);
System.out.println("Element at index 3: "+ anArray[3]);
System.out.println("Element at index 4: "+ anArray[4]);
}
} 24
Exception Handling in JAVA
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Exception Handling is a mechanism to


handle runtime errors such as ClassNotFound,
IO, SQL, Remote etc.

25
Types of Exception in JAVA
Types of Exceptions

1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions
e.g.IOException, SQLException etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.

26
Exception handling in JAVA
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
• try
• catch
• finally
• throw
• throws

Java try block


Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
Java try block must be followed by either catch or finally block.

Syntax of java try-catch


try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw exception
}finally{}

27
Why Exception handling in JAVA?

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.


public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output :

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Testtrycatch1.main(Testtrycatch1.java:3)

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).

28
Why Exception handling in JAVA?

Solution by exception handling

Let's see the solution of above problem by java try-catch block.


public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

29
Why Exception handling in JAVA?

30
Collections and map in JAVA?

31
Collections and map in JAVA?

• A collection represents a group of objects, known as its


elements. The JDK provides implementations of more specific
subinterfaces like Set and List.

• A map is an object that maps keys to values. A map cannot


contain duplicate keys; each key can map to at most one value.

32
Lists in JAVA?

The List is the base interface for all list types, and
the ArrayList and LinkedList classes are two common List’s
implementations.

• ArrayList: An implementation that stores elements in a


backing array. The array’s size will be automatically
expanded if there isn’t enough room when adding new
elements into the list. In Java ArrayList class, manipulation is
slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
• LinkedList: An implementation that stores elements in a
doubly-linked list data structure. In Java LinkedList class,
manipulation is fast because no shifting needs to be occurred.
33
Array List in JAVA?

public class ArrayLst {


public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
list.add(2, "Chaitali");
//Traversing list through Iterator
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
34
}
Linked List in JAVA?

public class lnklst {


public static void main(String[] args) {
LinkedList<String> list=new LinkedList<String>();
//Creating LinkedList
list.add("Ravi");//Adding object in LinkedList
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
list.add(2, "Chaitali");
//Traversing Linkedlist through Iterator
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
35
Sets in JAVA?

Set is an unordered collection, it doesn’t maintain any order.


All the elements of a Set should be unique if you try to insert the
duplicate element in Set it would replace the existing value.

36
HashSet in JAVA?

public class Hashset1 {


public static void main(String[] args) {
HashSet<String> list=new HashSet<String>(); //Creating Hashset
list.add("Ravi");//Adding object in Hashset
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
list.add("Chaitali");
//Traversing Hashset through Iterator
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
} 37
TreeSet in JAVA?

public class treeset1 {


public static void main(String[] args) {
TreeSet<String> list=new TreeSet<String>();//Creating Treeset
list.add("Ravi");//Adding object in Treeset
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
list.add("Chaitali");
//Traversing Treeset through Iterator
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
38
Map in JAVA?

A map contains values on the basis of key i.e. key and value pair.
Each key and value pair is known as an entry. Map contains only
unique keys.

Map is useful if you have to search, update or delete elements on


the basis of key.

39
HashMap in JAVA?

public class Hashmap1 {


public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(102,"Ravi");
map.put(103,"Vijay");
map.put(101,"Ravi");
map.put(null,"Ajay");
map.put(104,"Chaitali");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

40
TreeMap in JAVA?

public class Treemap1 {


public static void main(String[] args) {
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(102,"Ravi");
map.put(103,"Vijay");
map.put(101,"Ravi");
map.put(100,null);
map.put(104,"Chaitali");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

41
HELPING HANDS

Thank You

COPYRIGHT NOTICE
Copyright © 2017 Helping Hands
All rights reserved. These materials are confidential and proprietary to Helping hands and no part of these materials should be reproduced, published in any form by any
means, electronic or mechanical including photocopy or any information storage or retrieval system nor should the materials be disclosed to third parties without the
express written authorization of Helping Hands. 42

You might also like