32
Software Quality Assurance (QA) Training JAVA BASICS FOR SELENIUM AUTOMATION Page 1 of 32

Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Software Quality Assurance (QA) Training

JAVA BASICS FOR SELENIUM AUTOMATION

Page 1 of 27

Page 2: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Table of Contents:

Table of ContentsTable of Contents:....................................................................................................................................... 2Revision History:......................................................................................................................................... 31. Java Introduction...............................................................................................................................42. Data Types............................................................................................................................................ 53. Loops...................................................................................................................................................... 74. Arrays..................................................................................................................................................... 85. Functions............................................................................................................................................ 116. Object Oriented Programming (OOP)...................................................................................137. Static & Non-Static Functions....................................................................................................138. Difference between Object and Object References..........................................................159. Inheritance in Java......................................................................................................................... 1610. Abstract Class:.............................................................................................................................2011. Overloading and Overriding Functions:..........................................................................2212. Writing and Reading text files using Java.......................................................................23

Page 2 of 27

Page 3: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Revision History:Description Version DateInitial version created 1.0 4/13/16OOP chapter added 2.0 4/19/16Added missing info in Java Intro and removed low priority info

3.0 4/20/16

Added Concept of Inheritance, Interface Overloadings and Overriding Functions,Example on inheritance,Object Class,Usage of Inheritance in Selenium

4.0 4/22/16

Writing and Reading text files using Java

5.0 8/25/16

Implementing Log4j API 6.0 8/29/16Minor changes in one of the script

7.0 3/9/17

Added another script for Abstract class

8.0 5/10/17

Added OOP concepts 24.0 8/2/2020

Page 3 of 27

Page 4: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

1. Java IntroductionJava is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!. Java is open source (free to download /install) programming language and can develop and execute program on again platform (windows, unix/linux, mac etc) since it is a platform independent.

Java Class: A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Example for Class is Login module.

Java Method: A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Example for Method is Login Test Cases.

JAVA setup on Windows/Mac:

Download/Install Java/JDK https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Java SE Development Kit 8u191Accept license agreementDownload (for Windows): Windows x64 207.22 MB jdk-8u191-windows-x64.exeDownload (for Mac): Mac OS X x64 245.92 MB jdk-8u191-macosx-x64.dmgCopy the downloaded .zip file to relevant location (ex: C:/Selenium/1119) and unzip it.

Now setup Environment Variables with java/jdk paths:

Setup the following environment variables in System and User variables:User variables:JAVA_HOMEC:\Program Files\Java\jdk1.8.0_191

System variables:PathC:\Program Files\Java\jdk1.8.0_191\bin

Run the following commands on command prompt verify whether java/jdk setup done correctly: (you should not see any errors)java -versionjavac -version

Page 4 of 27

Page 5: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Eclipse setup on Windows OS:Install Eclipse: IDE for Java EE Developers 212 MB: Eclipse is an editor to develop java programs. Eclipse is the replacement for notepad or textpad.Check your laptop version (ex: Win7/8/10 32-bit or 64-bit by going to start—computer—right click properties)

32-bit: http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/mars/1/eclipse-java-mars-1-win32.zip

64-bit: NEWhttps://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/mars/1/eclipse-java-mars-1-win32-x86_64.zip&mirror_id=1

OROLDhttp://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/mars/1/eclipse-java-mars-1-win32-x86_64.zip

Unzip eclipse folder (right click on .zip folder, extract here), open the extracted folder, go to eclipse folder, and double click eclipse.exe or right click on eclipse.exe-> create shortcut-> move it to task bar on the bottom of the desktop.

Now double click on eclipse from task bar.

Note/Error: 1) If you see error message "Java was started but returned exit code=13" then uninstall 64 bit

eclipse and install 32 bit ver of eclipse OR following this video to fix this issue: https://www.youtube.com/watch?v=oI_qPnA753Q

2) On Windows 10, though it is 64 bit, please install 32 bit if you have an issue with 64 bit

Eclipse setup on Mac OS:Go to this link https://www.eclipse.org/downloads/packages/Download Eclipse IDE for Java EE DevelopersFollow below video to setup Eclipse on Mac OS.https://www.youtube.com/watch?v=gufMbpxzfWw

Create Workspace, Java project & Class in Eclipse:

Open Eclipse -> Create workspace with the path: ex: C:\Selenium\0917\Java\JavaWS.File -> New -> Java Project (ex: JavaForSelenium) OR File -> New -> Project -> Java -> Java Project. SRC and JRE folders: JRE (java runtime environment) got installed when you install java on your system. Under SRC (source), you will develop all your java programs.

Create a new class (ex: FirstJavaProgram) in SRC folder (right click src->new -> class) with checkbox “public static void main….” You must see 2files: .java file under /src folder and .class under /bin folder.

Comment in java is // (for single line) and /* */ (for multiple lines).

Type below program:

Page 5 of 27

Satyendra Kaith, 05/21/17,
64 bit version got the error message described in this document. 32 version installed.
Page 6: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

public class FirstJavaProgram {

public static void main(String[] args) {

System.out.println("Hello World");

}

}

Run the java program (click run button or right click on .java program->run as -> java application)… you will see “Hello World” under the Console tab in eclipse.Note: To run java program, you can even use Cnt+F11 or Cnt+Alt+F11

Go to source folder and look for bin/.class file: this is the executable file. Which can be executed on any OS since Java is a platform independent.

2. Data Types Create new java class “JavaDataTypes”Update the script like below:

// Java Data Typespublic class JavaDataTypes {

public static void main(String[] args) {int i=10; //(in the memory of “i”, value 10 will be stored

and should be numeric)long y=1234; // (it can also store integers like int but

size of int is 32-bit whereas size of long is 64-bit. If you have very big number (6876787687), then use long instead of int. int and long cannot store decimal like 10.74 etc..)

double z = 123.45; // (it can store integers and decimals .. both)

char c = 's'; // (we can write only one char at a time inside char c)/* Note: Java offers 2 additional non-numeric primitive data types: char (to represent alphanumeric characters and special symbols) and boolean (to represent the truth values true and false) */

boolean b = true; // (this can have only true or false values. Boolean will be used in conditional statements like IF/ELSE).

String s = "hello world"; // String – something which can hold number of characters together – but it’s not a data type, it is an in-built class in java.

System.out.println("Welcome to Java/Selenium");System.out.println(i);

System.out.println(y); System.out.println(z); System.out.println(c);

Page 6 of 27

Page 7: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

System.out.println(b); System.out.println(s);

System.out.println(87); // if I run this, it will just print 87

System.out.println(2>1); // if I run this, this will print true

System.out.println(2>3); // if I run this, this will print false

int a1=300;int b1=200;if (a1>b1){System.out.println ("a1 is the greatest " + a1);} else {System.out.println ("b1 is the greatest " + b1);}

}

}

Run the script now (right click on script-> run as -> java application). You should see following output results:

Welcome to Java/Selenium101234123.45struehello world87truefalseb1 is the greatest 200

Comparison operators are: >, <, >=, <=, ==, !=

Page 7 of 27

Page 8: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Java Advanced Topics:

Concatenation Operator – You can merge/concatenate/combine two Java String fields using the + operator.

In Eclipse create a new class “JavaConcatenationOperator” with “public static void main ….” and type below code:

public class JavaConcatenationOperator {

public static void main(String[] args) {

String s1 = "Selenium";String s2 = "Automation";System.out.println (s1+s2); // you will see

“SeleniumAutomation”

int a1 = 100;int a2 = 200;System.out.println (a1+a2); // you will see 300 System.out.println (s1+s2+(a1+a2)); // you will see

Selenium Automation300

}

}

Run the script now, you should see following results:Selenium Automation 300Selenium Automation 300

3. Loops ****While Loop: The while statement continually executes a block of statements while a particular condition is true. Create a new class “JavaWhileLoop” with “public static void main ….” in Eclipse and write below code:

// Print the numbers from 0-9public class JavaWhileLoop {

public static void main(String[] args) {int i=0; // initialization while (i<10){ // condition

System.out.println(i);

i=i+1; // increment / decrement}

}

Page 8 of 27

Page 9: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

}//Run: It will print numbers from 0 to 9

Disadvantage of While Loop: If we don’t specify the condition (ex: i=i+1), then the loop will stuck infinitely (ex: it will print 0 infinitely) and cannot come out until you stop the execution manually (use terminate button in eclipse next to console tab).

For Loop: The For statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.

Create a new class “JavaForLoop” with “public static void main ….” in Eclipse and write below code:

// Write a java code to Print first 10 numbers (0-9) and sum of 1st hundred numberspublic class JavaForLoop {

public static void main(String[] args) {

for (int i=0; i<10; i++) // i++ means i=i+1{System.out.println(i);

} // this will print numbers from 0 to 9

// Sum of first 100 numbersint sum=0;for (int n=0; n<=100; n++) { sum=sum+n;}

System.out.println("Sum of first 100 numbers is " +sum);

}}

Where will we use For loop in Selenium? When we create data driven test in Selenium/WD/Java, multiple data (ex: username1/pwd1, username1/pwd2 etc) will read from excel sheet using For loop written in Selenium/WD/Java program.

Page 9 of 27

Page 10: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

4. Arrays ****Single / One Dimensional Arrays An Array is a memory location, in which you can store multiple values. 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, the length is fixed.

Create a class (Java1DArray) with “public static void main ….”:

In single dimensional array, table/data will have a single row and column(s) and it contains values:

0 1 2 3 4

 Username

Password Email Zip City

0 Rama Qaqa [email protected] 94086

Sunnyvale

// Read data from above table, put the data in 1D array and print them

public class Java1DArray {

public static void main(String[] args) {String username="rama";String password="qaqa";String email="[email protected]";String zip="94086"; String city="Sunnyvale";String address="141 Saratoga Ave, Cupertino, CA";//Assume above data is in excel spread sheet// Arrays// Read the data from xls and put it inside the arrayString str[]=new String[5]; // since we have 1 row and 5

columnsstr[0]="rama";str[1]="qaqa";str[2]="[email protected]";str[3]="94086";str[4]="Sunnyvale";// Remember: Array holds a fixed number of values of a

single type. //The length of an array is established when the array is created.

// find the length of the array System.out.println(str.length); // this will print 5// Print all the elements of the String arrayfor (int x=0;x<=str.length;x++) {System.out.println(str[x]); // it will print the whole

string array}

}}

Page 10 of 27

Page 11: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Two Dimensional Array ****In Java, a table may be implemented as a 2D array. Each cell of the array is a variable that can hold a value and works like any variable. As with one dimensional arrays, every cell in a 2D array is of the same type. The type can be a primitive type or an object reference type.2D contains multiple rows, columns and it has data started from index 0:

0 1 2 3

 Username Password Email Zip

0 Rama Qaqa [email protected] 940861 Ashok Pa$$w0rd [email protected] 950512 Sneha Lucky [email protected] 94087

Create a new class (Java2DArray) with “public static main…”:

//Test Case: Print all the values in above table using 2D Array:

public class Java2DArray {public static void main(String[] args) {

String x[][]= new String[3][4]; //3 rows and 4 columns

//first rowx[0][0]="Rama";x[0][1]="Qaqa";x[0][2]="[email protected]";x[0][3]="94086";

//2nd rowx[1][0]="Ashok";x[1][1]="Pa$$w0rd";x[1][2]="[email protected]";x[1][3]="95051";

//3rd rowx[2][0]="Sheha";x[2][1]="Lucky";x[2][2]="[email protected]";x[2][3]="94087";

// In Selenium, mostly we read data from 2 dimensional array (see table example above):

// **** It will basically read data from excel and put them into 2D array (but it won't read cell by cell from excel) and then the script will read the data from 2D array instead of reading from excel directly.

Page 11 of 27

Page 12: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

// Print 2D array

// Print rowsSystem.out.println("Rows are "+ x.length); // This will

print Rows are 3

// Print columnsSystem.out.println("Cols are "+ x[0].length);// This will

print Cols are 4

// Now print, each and every value present in 2D arrayint rows=x.length;int cols=x[0].length;

for (int rowNum=0; rowNum<rows; rowNum++){System.out.println("---------------");for (int colNum=0; colNum<cols; colNum++){

System.out.println(x[rowNum][colNum]); // It will print your complete 2D array

}}// Only drawback is, it cannot determine in the beginning

that what length of array should be there.

}

}

Object Array/ Class In a string array, we cannot put integer. At the same time, in Integer we cannot put string. In this case, we need an array where we can put multiple types of data like string, int, char etc.. This can be done by using Object Array / Class.

Object ar[] = new Object[4];ar[0]="Hello";ar[1]=1234;ar[2]="4545";ar[3]=true;ar[4]=23.21;

// In Selenium, we'll use Object Arrays the most.

Page 12 of 27

Page 13: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

5. Functions It’s an independent / small unit of execution. We can call same /reusable function from different programs to avoid the duplication of code. All the functions should be inside the class body. We cannot make a function inside the function.

Create a new class “JavaFunctionsBasics” with public static void….”.Below is the main function. All code should go inside the main function.

//Now prepare a class with below script://Wrong scriptpublic class JavaFunctionsBasics {

public static void main(String[] args) {System.out.println("In Main");}

public static void testMe() { // this is how we have to define the function

System.out.println("In TestMe");}

}

Run the above class/script, it will print only “In Main” i.e main Function.

You will get an error, if you put “testMe” function inside the Main function. You need to make sure functions are created parallel within a class (per above example).If you want to print, “In TestMe” as well, then you have to call “testMe” function. Main function is the one, in which the control will come by default.

//Correct scriptpublic class JavaFunctionsBasics {

public static void main(String[] args) {testMe();System.out.println("In Main");}

public static void testMe() {System.out.println("In TestMe");}

}

How to pass values thru the function?Create a new class “Java_Functions_PassInValues” with “public static void…..”.public class Java_Functions_PassInValues {

public static void main(String[] args) {sumAll(3,4,5);}public static void sumAll (int a, int b, int c) {int sum=a+b+c;System.out.println(sum);

}} // Run: this will print 12

Page 13 of 27

Page 14: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

Practical usage of Functions in Selenium public static boolean doLogin (String username, String password) {

// selenium code in java for login here...return true: // success , fail }

6. Object Oriented Programming (OOP) ****OOP stands for Object-Oriented Programming.Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.Object-oriented programming has several advantages over procedural programming:OOP is faster and easier to executeOOP provides a clear structure for the programsOOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debugOOP makes it possible to create full reusable applications with less code and shorter development time

Selenium 3.0 / WebDriver is purely Object Oriented in nature. You have to learn OOP in order to work with Selenium and in order to learn the architecture of selenium.

Object-Oriented Programming Object Class

Principle Object Oriented Concepts in Java Abstraction Encapsulation Inheritance Polymorphism

What is Object-Oriented Programming and Concepts?Object-Oriented Programming is a method of programming where programmers define the type of data as well the operations that the data can perform.In a nutshell, Object-Oriented Programming is a simple engineering advance to build software systems which models real-world entities using classes and objects.

What is an Object?An object in terms of software programming is nothing but a real-world entity or an abstract concept which has an identity, state, and behavior.For example: Let us consider a real-life entity Car.

Characteristics ExamplesIdentity Model Number, Model Name, License Plate/ Vehicle NumberState Speed, Gear, Engine temperature, Fuel levelBehavior Fast, Slow, Change Of Gears, Break Down, Go Reverse, Etc.

What is a Class?A class defines the structure of objects which include the state and behavior (operation).

Page 14 of 27

Page 15: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

For example: Let us consider a class named Bank_Account, whose state can be represented by variables like account_number, account_type. And the behavior can be represented by methods like amount_withdraw, amount_deposit, account_closure.

Principle Object Oriented Concepts in Java: Abstraction Encapsulation Inheritance Polymorphism

1. AbstractionThe process of highlighting the necessary and most concerned characteristics and hiding others is known as abstraction.

For instance, we can consider different kinds of cars and bus which have different engine type, shape, and purpose which make them distinctive from each other. Although all of them have some general features, i.e., gearbox, engine, tire, steering, brakes, etc.

So the general concept between them is that they are Vehicles. Therefore, we can display the feature common to both and exclude characteristics that are in particular concerned with car or bus.

This is a figure to describe Abstraction explained with an example.

Vehicle -> SUV/Sedan/AutoBus/OmniBus

In Java, abstraction can be achieved with the help of,

Abstract Class Interface

What is Abstract Class in Java?A class when declared using the keyword abstract is an abstract class in java. An abstract class is extended by other classes and the methods should be implemented.

For example: From the above figure, the vehicle is an abstract class which is extended by SUV, Sedan, etc.

Sample code:abstract class Vehicle{ public void changeGear(){ System.out.println(“Changing the gear”); }} class SUV extends Vehicle{ public void changeGear(){ System.out.println(“Gear has been changed.”); } public static void main(String args[]){ Vehicle vehicle = new SUV(); vehicle.changeGear();

Page 15 of 27

Page 16: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

}Output:Gear has been changed.

What is the interface in Java?An interface, in simple words, is a draft of a class which is used to achieve abstraction. Since an interface is similar to a class, it has variables and methods(which are by default abstract).

2. Encapsulation:The practice of combining data and operations into a single entity is defined as encapsulation. In Java, encapsulation can be illustrated by making the data member of class private and declare getter and setter methods to make it accessible.

Encapsulation example:

3. Inheritance:The process of reusing the properties of an existing class is defined as an inheritance.

The class whose properties are used inherited is considered the parent or superclass. And the inheriting class is the child or subclass.

Inheritance, in general, depicts the parent-child relationship in object-oriented programming, which is also called as the IS-A relationship.

How do we use inheritance in JAVA?The keyword extends is used to display inheritance in Java.

The syntax to depict inheritance is as follows:

class Parent {........}

class Child extends Parent {........

Page 16 of 27

Page 17: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

}For example:

class Gadget {.....}

class Laptop extends Gadget {.....}

class Tablet extends Gadget {.....}

class Smartphone extends Gadget{....}From the above example, we can say that-

Laptop IS-A Gadget, i.e., Gadget is the parent class and Laptop is the child class.Tablet IS-A Gadget, i.e., Gadget is the parent class and Tablet is the child class.Smartphone IS-A Gadget, i.e., Gadget is the parent class and Smartphone is the child class.

4. Polymorphism:The word polymorphism is derived from 2 Greek words namely – ‘poly’, which means many and ‘morph’ which means forms.

Therefore, the word ‘Polymorphism’ means a single operation with multiple forms.

For example:

Let us consider we have a class called Coffee that has a method called ingredients(). The class Coffee is inherited by 2 subclasses Latte and Cappuccino which vary in using the generic method ingredients ().

So, here the action performed by ingredients() method is based on the type of object which uses it.

7. Static & Non-Static FunctionsJava is an Object Oriented Programming(OOP) language, which means we need an object to access any method or variable inside or outside the class. However there are some special cases where we don’t need any object (or instance). In order to access static methods we don’t need any object. It can be directly called in a program or by using class name. A non-static method is always be called by using the object of class.

For non-static function, create a class (Car) with “public static void main ….”://========================= non-static example ================

Page 17 of 27

Page 18: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

public class Car {// non-static exampleString model;int price;int wheels;

public static void main(String[] args) {// creating the object of the class (ex: browser: chrome)Car c1 = new Car(); c1.model="BMW";c1.price=62754;c1.wheels=4; // this is common in every carc1.start();c1.accelarate();

Car c2 = new Car();c2.model="Tesla";c2.price=96111;c2.wheels=4; // this is common in every carc2.start();c2.accelarate();

System.out.println(c1.model);System.out.println(c2.model);System.out.println(c1.wheels);System.out.println(c2.wheels);

}

public void start(){ // non-static function/methodSystem.out.println(model + " starting");

}

public void accelarate(){ // non-static function/methodSystem.out.println(model + " accel");

}}

For static function, create a class (Car1) with “public static void main ….”:// ====================================== static example ======

// static example// c1.wheels=4; // this is common in every car

Page 18 of 27

Page 19: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

// let's remove wheels variable from both and put it in a common location, so that all the objects will access that from a common memory / location. In this case, change "int wheels" as static int wheels=4; that means, wheels is not part of an object now. it's now common for all objects of the car class. public class Car1 {

String model;int price;//int wheels;static int wheels=4;

// non-static examplepublic static void main(String[] args) {

// creating the object of the classCar1 c1 = new Car1();c1.model="BMW";c1.price=62754;// c1.wheels=4; // this is common in every carc1.start();c1.accelarate();

Car1 c2 = new Car1();c2.model="Tesla";c2.price=96111;// c2.wheels=4; // this is common in every carc2.start();c2.accelarate();

System.out.println(c1.model);System.out.println(c2.model);System.out.println(c1.wheels);System.out.println(c2.wheels);

}public void start(){ // non-static function/method

System.out.println(model + " starting");}

public void accelarate(){ // non-static function/methodSystem.out.println(model + " accel");

}

}

Note: Why main method in “public static void main(String[] args)” is static?main function is static in nature. Static things can be called with class.variable.

Page 19 of 27

Page 20: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

So we can call main function directly with class.function.

Note: Garbage Collection: In java, garbage collection means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

8. Difference between Object and Object ReferencesObject holds memory and it is created using new keyword. Object Reference is nothing but reference to that memory. It only points to memory that object holds.For example, you must have contacts of many people in your mobile. You can use a contact to call a person. The person is actually somewhere else, but the contact helps you to call them. You can think of a Reference variable to be a contact no(phone#) and Object to be the actual person you are calling. Basically a reference variable just points to an actual object.

Create a class (TestCar) with “public static void main ….”:

public class TestCar {String model;public static void main(String[] args) {

Car a = new Car(); //- IE webdriver iedriver = new IEdriver();

Car b = new Car(); //- FF webdriver ffdriver = new FFdriver();

Car c = new Car(); //- CH webdriver chdriver = new CHdriver();

a.model="A";b.model="B";c.model="C";

System.out.println(a.model);System.out.println(b.model);System.out.println(c.model);System.out.println("------------");// Run now, you will see A, B, C

a=b;b=c;c=a;

/* What modifications above will do in memory is: a=b: “a” reference will be removed and “a” will be pointed to where “b” is pointing to that is c. b=c: “b” reference will be removed and “b” will be pointed to where “c” is pointing to that is a.c=a: “c” reference will be removed and “c” will be pointed to where “a” is pointing to that is b*/

Page 20 of 27

Satyendra Kaith, 06/07/17,
Need to review again
Page 21: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

System.out.println(a.model);System.out.println(b.model);System.out.println(c.model);

//Now…a.model will print b, b.model will print c and c.model will print b/*i.e the objects still remain in the memory in a particular location, but object references keep on changing. Right now, object “a” doesn’t have any object reference, and cannot be accessed so it will be destroyed by mechanism called garbage collection*/// Run now, you will see B, C, B (so A is not needed anymore, and can be destroyed by Garbage collection)

}}

Tip: How to increase font size in Eclipse? Go to Windows -> Preference -> General -> Appearance -> Color and Fonts -> Basics -> Text Font -> Edit -> (Change the number from ex: 10 to 14) -> OK

9. Inheritance in Java ****Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

//Parent Class: (common functions in a single program)public class CommonFunctions{

public void login(){System.out.println("Successfully Logged In");

}

public void logout(){System.out.println("Successfully Logged Out");

}

}

//Purchase Ticket Child Class:public class PurchaseTicket extends CommonFunctions {

Page 21 of 27

Page 22: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

// PurchaseTicket extends CommonFunctions, is nothing but inheritance ... PurchaseTicket Class Inherits from CommonFunctions Class.

public void testPurchase(){System.out.println("Successfully Purchased the

flight ticket");}}

//TestPurchaseTicket Class:public class TestPurchaseTicket {

public static void main (String[] args){// creating the object of the classPurchaseTicket p = new PurchaseTicket();

System.out.println("--------");p.login();p.testPurchase();p.logout();

// TestPurchaseTicket can call functions from both CommonFunctions and PurchaseTicket classes since PurchaseTicket inherit from CommonFunctions class.}}//Run the TestPurchaseTicket class now…and you should see results like below:

--------Successfully Logged InSuccessfully Purchased the flight ticketSuccessfully Logged Out

Interface ****:Interface is something which is in-complete. Interface describes what the application supposed to do.

Create an interface known as Hospital: Right click on src -> New -> Interface -> Finish.

Now create 3 functions for an interface: operate(), doScan(), and doVaccination().We will not implement functions within an interface. This will tell, what hospital is offering you.

//Hospital Interface:public interface Hospital {

public void operate();//….. develop code here….

Page 22 of 27

Page 23: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

public void doScan();//….. develop code here….public void doVaccination();//….. develop code here….

}

Now create, 2 new classes: FortisHospital, and GovtHospital without public static void (src->New-Class->Enter name and Finish)

// Change class from “public class FortisHospital{“ to “public class FortisHospital implements Hospital{“ and Position the cursor on class name (ex: FortisHospital or GovtHospital) and click “add unimplemented methods”….it will let you add all 3 functions from Hospital Interface with @Override annotation for each function. (Need to do this for both FortisHospital, and GovtHospital classes) And you must use/implement all 3 functions. Both the classes extending the Hospital Interface.

Why should we use interface rather than directly writing individual classes?The reason is that: It gives a consistency in the system. i.e., both the hospitals implementing / offering the 3 functions. Interface defines the contract. In Selenium WebDriver, we'll use Java interface to automate some of the manual test cases.

// FortisHospital Classpublic class FortisHospital implements Hospital {

@Overridepublic void operate() {

System.out.println("Fortis Hospital Operating");

}

@Overridepublic void doScan() {

System.out.println("Fortis Hospital Scanning");

}

@Overridepublic void doVaccination() {

System.out.println("Fortis Hospital Vaccination");

}

}

Page 23 of 27

Page 24: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

// GovtHospital Class

public class GovtHospital implements Hospital{

@Overridepublic void operate() {

System.out.println("Govt Hospital Operating");

}

@Overridepublic void doScan() {

System.out.println("Govt Hospital Scanning");

}

@Overridepublic void doVaccination() {

System.out.println("Govt Hospital Vaccination");

}

}

Create another class TestHospital with public static void main ....if you try to create an object of Hospital interface, it will give an error. ex: Hospital h = new Hospital(); Hospital class is an interface. You cannot create an object of interface.But you can create an object of implementing classes... finally your TestHospital will like below:

// TestHospital Classpublic class TestHospital {

public static void main(String[] args) {// Hospital h = new Hospital(); //illegal (like

launching browser)FortisHospital f = new FortisHospital();f.doScan();f.doVaccination();f.operate();System.out.println("-------");

Page 24 of 27

Page 25: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

GovtHospital g = new GovtHospital();g.doScan();g.doVaccination();g.operate();

}

}

// Run now, you should see:Fortis Hospital ScanningFortis Hospital VaccinationFortis Hospital Operating-------Govt Hospital ScanningGovt Hospital VaccinationGovt Hospital Operating

10. Abstract Class:An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

Create a new class called StreetHospitalAssume this is a small hospital and can do only Vaccination but you cannot just use one function out of 3 from Hospital Interface. Only way you can do is… convert your regular class into abstract class like below:

public abstract class StreetHospital implements Hospital{public void doVaccination(){

System.out.println("StreetHospital doVaccination");}}

Create another Class CommunityHospital This is little bigger hospital compared to StreetHospital. It can do Scanning and Vaccination by extending the StreetHospital.

public abstract class CommunityHospital extends StreetHospital{

Page 25 of 27

Page 26: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

public void doScan(){System.out.println("CommunityHospital doScan");

}public void doVaccination(){

System.out.println("CommunityHospital doVaccination");}}

Create another Class CityHospitalThis is the biggest hospital. It extends the community hospital and it will give all 3 features including operate.public class CityHospital extends CommunityHospital{

public void doScan() {System.out.println("CommunityHospital doScan");

}public void doVaccination() {

System.out.println("CommunityHospital doVaccination");

}public void operate() {

System.out.println("CityHospital Operating");}}

What is the difference between Hashmap and Hashtable:1) Hashtable is synchronized whereas hashmap is not. 2) Another difference is that iterator in the HashMap is fail-safe while the

enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

3) HashMap permits null values in it, while Hashtable not.

For more info, please refer: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html

11. Create File, Writing text into file and Reading text from files using Java

Open eclipse and create a new class/java program CWRTestFle.java with below code:

import java.io.*;

public class CWRTestFle {public static void main (String[] args) throws IOException {

Page 26 of 27

Page 27: Table of Contents: · Web viewImplementing Log4j API 6.0 8/29/16 Minor changes in one of the script 7.0 3/9/17 Added another script for Abstract class 8.0 5/10/17 Added OOP concepts

// creating text file (below line of code will create new text file automatically)File f = new File ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt"); f.createNewFile();

// writing text into above text fileFileWriter w = new FileWriter ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt");BufferedWriter out = new BufferedWriter(w);out.write("writing data into text file");out.newLine(); // like press enter key to go to next lineout.write("This is a new line");out.flush();

// Reading data from above text fileFileReader r = new FileReader ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt");BufferedReader bfr = new BufferedReader(r);String x ="";

while ((x=bfr.readLine()) !=null){System.out.println(x);}}}

Right click on the java program -> 1JavaApplication. You should see textfile.txt created with data under C:\Selenium\0616\JavaIntro and you should see the data in Eclipse (Console tab in the bottom).

NOTE: In Selenium WebDriver Data Driven / Parameterize Test, we need to write a code to read data from a file (excel, csv, xml etc) to test some test cases like login/ logout with different user accounts.

To learn more about Java, please refer below website:https://www.w3schools.com/java/default.asp

Page 27 of 27