Java Tutorial for Selenium


Java Programming for Selenium
 

A) Java Fundamentals 

(Comments, Data Types, Variables, Modifiers, Operators, Conditional statements, Loop statements, Arrays, Methods (Built inward together with User defined), File together with IO operations together with Exception Handling)

B) Java OOPS Concepts 


(Inheritance, Polymorphism, Abstraction together with Encapsulation)
---------------------------------------------------------------------------
Java Environment Setup together with Write First Java Program
 

> Download Java (JDK) Software together with Install

> Set Environment Variable (Path Variable)(* If desire to execute Java programs from whatsoever directory inward C Drive)

How to set:

OS: Windows 7

> Select MYComputer together with Right click

> Properties

> Advanced System Settings

> Environment Variables

> Select "New" inward System variables

> Enter Variable equally "Path"

> Enter JDK bin directory path ("C:\Program Files\Java\jdk1.8.0_45\bin") inward value field

> OK > OK > Ok
----------------------------------------
Verify the Environment setup:
> Launch Command Prompt

> Type coffee (It provides details)
-------------------------------------
Three steps to write together with execute Java Programs

i) Write Java Program inward Notepad (Editor)

ii) Compile the Program (It creates Class file)

Command prompt > Change to Program file Directory

> Type javac Programname.java (java is extension of Java program, javac command for compilation)

iii) Run /Execute the Java Program

> Type coffee programName
(It provides Output on the console)
-----------------------------------------------------
Use Eclipse IDE to write together with execute Java programs.

Eclipse IDE (Integrated Development Environment)

It is a platform to write together with execute Java programs, Perl, Python, PHP, Ruby etc...

It provides Editor, context help, assist for syntax errors, Auto compilation together with debugging.
-----------------------------
Download Eclipse software together with extract.
Steps:
----------------
> Create Java Project
    -> Create a Package
        -> Create a Class / Interface
(We tin write coffee code inward the Class file)
--------------------------------------

Ex:
public shape Sample {
    populace static void primary (String [] args){
        System.out.println("Hello Java together with Selenium");
    }
}
-------------------------------------------------
Java Program construction / Java Syntax:
 

1) Package annunciation statement
ex:

package abcd;
--------------------------------
2) Import statements
we tin import Built inward together with User defined Libraries using import keyword.
(In social club to exercise Existing Classes, Objects, together with Methods)


Example:

import java.io.console;

(It Imports Console Class merely from io package)

import java.io.*;

(It imports all classes from io package)
------------------
java - project

io - package

Console - Class
----------------------------------------------
3) Class annunciation statement
ex:

public shape Sample {
}

public - Access Modifier

class - Java keyword to declare a class

Sample - Name of the Class

Note: First missive of the alphabet of Class get upwards should live on upper case.
-------------------------------------------------
4) Comments section
// This is a Sample Java Program
-----------------------------------
5) Main Method (Java plan execution starts from primary method.)
(Main method is mandatory inward every Java program)

public static void primary (String [] args) {
}

public - Access Modifier

static - exercise primary method without invoking whatsoever object.

void - returns nothing

main - method name
-------------------------------------------
6) Declarations
We tin declare variables together with constants
-----------------------------
Normal statements

Conditional blocks

Loop blocks

Method declarations
Etc...
------------------------------------------
A Sample Java Program:
package abcd;

import java.io.Console;
import java.lang.*;

public shape Sample2 {
    // This is a Sample Java Program
    populace static void primary (String [] args){
        int a = 50, b, c; // Declaration of Variables
        b= 20; // Initialization
        System.out.println(a + b); // 70
        System.out.println("Addition of a, b is: "+ (a+b));
        concluding int MONEY = 100; // Declaration of Constant
       
        if (a > b) {
            System.out.println("A is a Big Number");
        }
        else
        {
            System.out.println("B is a Big Number");
        }   
       
        for (c = 1; c <= 10; c++){
            System.out.println(c);
        }
        }
    }
-----------------------------------------------
I) Comments inward Java
 

Comments are English linguistic communication words, tin live on used for code documentation.

Purpose of Comments:
a) To brand the code Readable

b) To brand the code disable shape execution

Comments Syntax inward Java:
Use // for unmarried work Comment or partial work equally comment

Use /* statements
----------
-----------
----------
*/ for multiple lines comment

Or
In Eclipse

Select statements
Source carte du jour -> Add Block Comment

Uncomment:
Select Comment block
Source carte du jour -> Remove comment block
-------------------------------------
Usage of Comments inward Test Automation
a) To write Test instance headers

b) To write Method headers

c) To explicate complex logic

d) To explicate resources usage
------------------------------
Example:
public shape Comments {

    populace static void primary (String [] args){
        int a = 10, b, c; // Declaration of Variables
        // It is a Sample Program
        System.out.println(a);// 10
        b = 50;
        c = 2;
        /*if (a > b) {
            System.out.println("A is a Big Number");
        }
        else {
            System.out.println("B is a Big Number");
        }*/
    }
}
---------------------------------------
II) Data Types inward Java
 

Data type is a classification of the type of information that a variable or object tin agree inward Computer programming.

Example:

Character, Integer, String, float etc...

Java supports explicit annunciation of Data types.
(We require to specify the information type earlier annunciation of variables.)

Syntax:

dataType VariableName

Example:

int a;
or
int a = 100;
-------------------------------------
In Java nosotros accept 2 types of Data types.
i) Primitive Data types

ii) Non -primitive Data types
------------------------------
i) Primitive Data types (8)
Integer Data types
1) byte (8 bits)

Example:

byte a = 10;

2) curt (16 bits)

Ex:

short b = 10000;

3) int (32 bits)

int c = 100000;

4) long (64 bits)

Ex:

long d = 100000L
-----------------------------
Rational Data types (Numbers amongst decimal places)

5) float (32 bits)

Ex:

float a = 1.2;

6) double (64 bits)

Ex:

double b = 19.234567;
----------
Characters

7) char (16 bits)

Ex:

char a = 'Z'
-------------------
Conditional

8) Boolean

Ex:

boolean a = true;
--------------------------------
ii) Non -primitive Data types

Non -primitive Data types inward Java are objects together with Arrays.

Ex:

Button = novel Button("OK")
--------------------------------------------
III) Java Modifiers
 

Modifiers are keywords that nosotros add together to those definitions to modify their meanings.

Two types of modifiers inward Java:
i) Access Modifiers

ii) Non Access Modifiers
-------------------------------
i) Access Modifiers
We exercise Access modifiers to define Access command for classes, methods together with variables.

There are 4 types of Access modifiers inward Java

1) Private

The private access modifier is accessible merely within class.

Ex:

class Abc {
private int a = 100;
.
.
.
}
--------------------------
2) default

If nosotros don't exercise whatsoever modifier thus it is treated equally default, this tin live on accessible merely within package.

Ex:
class Sample{
int a = 10;
.
.
}
-----------------------------------
3) protected

The protected access modifier is accessible within parcel together with out side of the parcel but
through Inheritance only.
-----------------------------
4) populace

public access modifier is accessible everywhere.

Ex:

public shape Abc{
.
.
}
--------------------------------------------------
Modifier Within class    within package    exterior of the package(by sub class) Outside of the package
----------------------------------------------------------------------------------------
private      Y        N        N                    N
------------------------------------------------------------------------------------
default   Y        Y        N                    N
-----------------------------------------------------------------------------------
protected Y        Y        Y                    N
----------------------------------------------------------------------------------
public    Y        Y        Y                    Y
---------------------------------------------------------------------------------
ii) Non Access modifiers

1) static

static modifiers are used to practice shape variable together with shape methods which tin live on accessed without instance of a class.

Ex:

class H5N1 {
static String get upwards = "Selenium";
}
---------------------
2 final

final modifier for finalizing the implementation of classes, methods together with variables.

class H5N1 {
int a = 10;
final int b = 20;
.
.
a = 30;
b = 50;//Incorrect
}
--------------------
3) abstract

abstract modifier is to practice abstract classes together with abstract methods.

Ex:

abstract sample {
Statements
--------
---------
------
}
--------------------------------
IV) Variables inward Java
 

1) What is Variable?

A named retention location to shop or agree the data.

Two types of retention inward estimator environment:

i) Primary retention - RAM

ii) Secondary retention -ROM

Ex: CD, DVD, HDD, USB campaign etc...
---------------------
2) Declaration of Variables

Syntax:

dataType variableName;

Ex:

int a;
-----------------
dataType varaible1, variable2, varaible3;

ex:

int a, b, c;
----------------------
dataType variableName = value;

Ex:

int a = 100;
--------------------------
3) Assigning values to variables

i) Initialization

Ex:
int a;
a = 100;

ii) Reading
    using input devices
    from files (text, excel)
    from databases
    from Application objects
--------------------------------
4) Types of Variables

In Java nosotros accept iii types of variables.

i) Instance variables
A variable that is declared within the shape but exterior the method.

ii) Local variables
A variable that is declared within the Method.

iii) Static / shape variables
A variable that is declared equally static, It cannot live on local.
------------------------------
5) Naming Restrictions

i) Java variables are instance sensitive, monkey is non the equally MONKEY or Monkey.

ii) Java variable get upwards must start amongst a missive of the alphabet or $ or _
Embedded periods can't live on used.

Ex:

myvar
MYVAR
$myvar
_myvar
myvar1
myvar_1
-----------
my var
my.var
1myvar
*myvar
my-var
-----------------------
iii) Variable names cannot live on equal to Java reserved words.

Ex:
int
for
import
-------------------
iv) Must live on unique inward the ambit of declaration.
--------------------------------------------
Variables example:
---------------------
public static void primary (String [] args){
        // Variable Declaration
        int a;
        a = 10; // Initialization
        // Declaration of multiple variables inward a statement
        int b, c, d;
        b = 20;
        c = 30;
        d = 40;
        // Declaration of multiple variable together with Assigning values.
        int e = 50, f=60, g = 70;
        char x ='A';
        double y = 2.345;
        String z = "Selenium123";
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
        System.out.println(f);
        System.out.println(g);
        System.out.println(x);
        System.out.println(y);
        System.out.println(z);
    }
}
-----------------------------------------------
V) Java Operators
 

Operators are used to perform mathematical, Comparison together with Logical operations.

Important categories of Operators inward Java:

i) Assignment Operators

ii) Arithmetic operators

iii) Relational operators

iv) Logical Operators
etc...
-------------------------------------
i) Assignment Operators

1) Assignment operator =

a = 10;

2) Add together with Assign Operator +=

a = 10;

a += 20;

3) Subtract together with Assign -=

a = 10;

a -= 5;

4) Multiply together with Assign *=

a = 10

a *= 5;
--------------------------------------
Example:
public static void primary (String [] args){
    int a = 10;
    System.out.println(a);// 10
    a += 10;
    System.out.println(a);//20
    a -= 10;
    System.out.println(a);//10
    a *= 5;
    System.out.println(a);//50
}
}
--------------------------------------
ii) Arithmetic Operators

Arithmetic Operators render value based Result.

1) Addition +  (for Addition together with String concatenation)

2) Subtraction - (for Subtraction together with negation)

3) Multiplication *

4) Division /

5) Modules %

6) Increment ++

7) Decrement --
-------------------------------
Example:

public static void primary (String [] args){
    int a = 10, b = 5;
    String c = "Selenium", d = " Testing";
   
System.out.println("Addition of a, b is: "  + (a + b)); // Addition of a, b is: 15
System.out.println("Concatenation of c, d is: " + (c+d)); //Concatenation of c, d is: Selenium Testing    

System.out.println("Subtraction of a, b is: " + (a-b)); // 5
System.out.println("Multiplication of a, b is: " + (a*b)); // 50
System.out.println("Divison of a, b is: " + (a/b)); //2
System.out.println("Modulas of a, b is: " + (a%b)); //0

a = ++b;
System.out.println(a); //6
b = 5;
a = --b;
System.out.println(a);//4
b =5;
a = b+4;
System.out.println(a); //9
b = 5;
a = b-4;
System.out.println(a);//1
}
}
---------------------------------------
iii) Relational Operators

Relational operators render boolean or logical upshot (true or false)

1) ==

2) !=

3) >

4) >=

5) <

6) <=
------------------------------
Example:
public shape OperatorsExample {
public static void primary (String [] args){
    int a = 10, b = 20;
    System.out.println("a > b is " + (a>b)); //False
    System.out.println("a >= b is " + (a >= b)); //False
   
    System.out.println("a < b is " + (a<b)); //True
    System.out.println("a <= b is " + (a <= b)); //True
   
    System.out.println("a == b is " + (a == b)); //False
    System.out.println("a != b is " + (a != b)); //True
}
}
------------------------------------------
iv) Logical Operators

1) Logical Not operator !

2) Logical And Operator &&

3) Logical Or operator ||
--------------------------------
Result Criteria for Not operator

Operand 1    Operand 2    Result
----------------------------------------
true        true        false
true        false        true
false        true        true
false        false        true
-----------------------------------------
Result Criteria for Add operator

Operand 1    Operand 2    Result
----------------------------------------
true        true        true
true        false        false   
false        true        false       
false        false        false       
-----------------------------------------
Result Criteria for Or operator

Operand 1    Operand 2    Result
----------------------------------------
true        true        true
true        false        true       
false        true        true           
false        false        false               
-----------------------------------------
Example 1:

public shape OperatorsExample {
public static void primary (String [] args){
    boolean a = true, b = false;
    System.out.println(! (a && b)); // true
    System.out.println((a && b)); //false
    System.out.println((a || b));//true
}
}
----------------------------------
Example 2:

public shape OperatorsExample {
public static void primary (String [] args){
    int a = 100, b = 500, c = 700;
    if ((a > b) && (a > c)) {
        System.out.println("A is a Big Number");
    }
    else
    {
    System.out.println("A is Not a Big Number");
    }
}
}
-----------------------------------------
public static void primary (String [] args){
    int a = 100, b = 500, c = 700;
    if (!(a > b) && !(a > c))  {
        System.out.println("A is a Big Number");
    }
    else
    {
    System.out.println("A is Not a Big Number");
    }
}
---------------------------
public static void primary (String [] args){
    int a = 100, b = 50;
    if (! (a > b))  {
    System.out.println("A is a Big Number");
    }
    else
    {
    System.out.println("B is a Big Number");
    }
}
------------------------------------------------
Java Flow Control statements
    Conditional statements
    Loop statements
-------------------------------------
VI) Java Conditional Statements
 

a) Types of Conditional statements inward Java:

i) if statement

ii) switch statement
-----------------------------
b) Types of Conditions

i) Single Condition

Ex:

if (a > b) {
Statements
-------
--------
.
.

ii) Compound Condition

Ex:

if ((a > b) && or || (a < c)) {
---------
----------
.
.
iii) Nested Condition

if (a > b) {
 if (a < c) {
  if (a < d) {
---------
------
}
}
}
-------------------
c) Usage of Conditional statements inward Selenium Test Automation

i) To insert Verification points

ii) For Error handling
-------------------------------
d) Usage of Conditional statements

i) Execute a block of statements when status is True.

if (condition) {
Statements
--------
------
-------
}
One way (Positive) Condition
Example:

public static void primary (String [] args){
        int a, b;
        a = 10; b= 50;
       
        if (a > b) {
            System.out.println("A is a Big Number");
        }
    }
}
---------------------------------------
One way (Negative) Condition

public static void primary (String [] args){
        int a, b;
        a = 10; b= 5;
       
        if (! (b > a)) {
            System.out.println("A is a Big Number");
        }
    }
}
-----------------------------------------
ii) Execute a block of statements when status is true; otherwise execute about other block of statements.

Syntax:

if (condition) {
Statements
---------
-------
------
}
else
{
Statements
---------
--------
---------
}

Example:

public static void primary (String [] args){
        int a, b;
        a = 10; b= 10;
       
        if (a > b) {
            System.out.println("A is a Big Number");
        }
        else {
            System.out.println("B is a Big Number");
        }
    }
}
--------------------------------------------
3) Execute a block of statements when a Compound status is true.

Syntax:

if ((condition1) && or || (condition2)) {
Statements
----------
----------
----------
}

Example:

public static void primary (String [] args){
        int a, b, c;
        a = 10; b= 7; c = 5;
       
        if ((a > b) && (a > c)) {
            System.out.println("A is a Big Number");
        }
    }
--------------------------------
public static void primary (String [] args){
        int a, b, c;
        a = 10; b= 7; c = 15;
       
        if ((a > b) || (a > c)) {
            System.out.println("A is a Big Number");
        }
    }
------------------------------------
4) Decide amid several alternates (else if)

Syntax:

if (condition) {
Statements
---------
---------
--------
}
else if (condition) {
Statements
---------
---------
--------
}
else if (condition) {
Statements
---------
---------
--------
}
else {
Statements
----------
---------
}

Example:

Requirement:
Verify the gain of a value

Conditions:
if the value is inward betwixt 1 to 100 thus display value is a Small number
if the value is inward betwixt 101 to grand thus display value is a Medium number
if the value is inward betwixt 1001 to 10000 thus display value is a Big number
Otherwise display the value is either null or negative value

Program:

    populace static void primary (String [] args){
        int val = -100;
    if ((val >= 1) && (val <=100)) {
        System.out.println("Value is a Small Number");
    }
    else if ((val > 100 ) && (val <=1000)) {
        System.out.println("Value is a Medium Number");
    }
    else if ((val > grand ) && (val <=10000)) {
        System.out.println("Value is a Big Number");
    }
    else {
        System.out.println("Value is Either Zero or Negative Number");
    }
}
--------------------------------------
v) Execute a Block of statements when to a greater extent than than ane status is True (Nested If)

Syntax:

if (condition) {
 if (condition) {
  if (condition {
Statements
--------
--------
}
}
}

Example:

public static void primary (String [] args){
        int a = 100, b = 90, c = 70, d = 50;
   
        if (a > b){
         if (a > c){
          if (a > d) {
              System.out.println("A is a Big Number");
          }
         }
        }
}
------------------------------
public static void primary (String [] args){
        int a = 100, b = 90, c = 70, d = 50;
   
        if (((a > b) && (a > c) && (a > d))) {
          System.out.println("A is a Big Number");
          }
}
----------------------------------
Difference betwixt Compound together with Nested Conditions

If it is Compound status nosotros tin write unmarried else component subdivision only.

If it is Nested status nosotros tin write multiple else parts.
----------------------------------------------------
vi) Decide amid several alternates (switch statement)

Syntax:

switch (expression) {

case value:
Statements
----------
----------
break;
case value:
Statements
----------
----------
break;
case value:
Statements
----------
----------
break;
default:
Statements
----------
-----
}

example:

public static void primary (String [] args){
        char degree = 'Z';
       
        switch (grade){
        instance 'A':
            System.out.println("Excellent");
            break;
        instance 'B':
            System.out.println("Well Done");
            break;
        instance 'C':
            System.out.println("Better");
            break;
        default:
            System.out.println("Invalid Grade");
        }
}
------------------------------------------------------
Java Flow Control Statements
    Conditional Statements
    Loop Statement

i) We tin exercise conditional statements merely inward our programs.

ii) We tin exercise Loop statements merely inward our programs.

iii) We tin exercise Conditional statements together with Loop statements together.
---------------------------------------------------------------
VII) Loop Statements
 

Whenever nosotros desire execute a block of statements multiple times thus nosotros exercise Loop structures.

There are iv types of Loop structures inward Java.

i) for loop

ii) spell loop

iii) practice spell loop

iv) Enhanced for loop
---------------------
i) for loop

Description:

It repeats a block of statements for a specified disclose of times.

Syntax:

for (startvalue; endvalue; increment/Decrement){
Statements
----------
----------
----------
}

Example: Print 1 to 10 Numbers

public static void primary (String [] args){
       
        for (int i = 1; i <= 10; i++){
            System.out.println(i);
        }
        }
---------------------------------------------------
Example: Print 10 to 1 Numbers

public static void primary (String [] args){
       
        for (int i = 10; i >= 1; i--){
            System.out.println(i);
        }
        }
-----------------------------------
Example: Print 1 to 10 Numbers, except fourth together with seventh numbers

public static void primary (String [] args){
       
        for (int i = 1; i <= 10; i++){
            if ((i != 4) && (i != 7)) {
            System.out.println(i);
            }
        }
        }
-------------------------------------------------
ii) While loop

It repeats a block of statements spell status is True.

Syntax:

Initialization
while (condition) {
statements
----------
----------
----------
increment / decrement
}

Example1: Print 1 to 10 Numbers

public static void primary (String [] args){
        int i = 1;
        spell (i <= 10){
            System.out.println(i);
            i++;
        }
        }
---------------------------------
Example2: impress 10 to 1 Numbers


public static void primary (String [] args){
        int i = 10;
        spell (i >= 1){
            System.out.println(i);
            i--;
        }
        }
-------------------------------------------
Example3: impress every tenth Number upwards to 100

    populace static void primary (String [] args){
        int i = 10;
        spell (i <= 100){
            System.out.println(i);
            i = i + 10;
        }
        }
---------------------------------------------------
Example4: Print 1 to 10 Numbers, except fourth together with seventh numbers

public static void primary (String [] args){
        int i = 1;
        spell (i <= 10){
            if ((i != 4) && (i != 7)){
            System.out.println(i);
            }
            i++;
        }
                }
----------------------------------------------------       
iii) practice spell loop

It repeats a block of statements spell status is true.
It executes statements at to the lowest degree ane time irrespective of the condition.

Difference betwixt spell loop together with practice spell loop:
---------------------------------------------
while loop kickoff checks the condition, if status is truthful thus it volition execute the statements.

do spell loop kickoff executes the statements thus it volition banking firm represent the condition, if condition
is true, it volition proceed otherwise come upwards out from the loop.
------------------------------------------------------
Syntax:

Initialization
do
{
Statements
----------
----------
----------
increment/decrement
} spell (condition);

Example:

public static void primary (String [] args){
        int i = 1;
        practice
        {
        System.out.println(i);   
            i++;
        }
        spell (i <= 10);
        }
---------------------------------
public static void primary (String [] args){
        int i = 11;
        practice
        {
        System.out.println(i);   
            i++;
        }
        spell (i <= 10);
        }
--------------------------------------
iv) Enhanced for loop

It executes all elements inward an Array.

Syntax:

Array declaration
for (declaration: expression/Array) {
Statements
---------
}

Example:

public static void primary (String [] args){
        String [] languages = {"C", "COBOL", "Java"};
        for (String lang: languages){
            System.out.println(lang);
        }
        }
Example2:
public static void primary (String [] args){
        int [] mathoperations = novel int[3];
        int a = 10, b =20;
        mathoperations[0] = a+b;
        mathoperations[1] = a-b;
        mathoperations[2] = a*b;
        for (int operation: mathoperations){
            System.out.println(operation);
        }
        }
------------------------------------------------------------
VIII) String Handling inward Java
 

What is String?

String is a sequence of characters written double quotes.

String may accept Alfa bytes, numbers together with special characters.

Example:
System.out.println("Selenium Testing"); // selenium Testing
System.out.println("123 Selenium"); // 123 Selenium
System.out.println("Selenium*&123Testing");//Selenium*&123Testing

Creating strings:

String is considered Object inward Java.

Ex:
public static void primary (String [] args){
    String myTool = "Selenium"; // String variable
    String [] myTools =    {"UFT", "Selenium", "LoadRunner"}; //Array of Strings
   
    System.out.println(myTool);//Selenium
   
    for (String tool: myTools){
        System.out.println(tool);//Print Array of Strings
    }
}
---------------------------------
Concatenating Strings:

public static void primary (String [] args){
    String str1 ="selenium";
    String str2 =" Testing";
    System.out.println(str1 + str2);//Selenium Testing
    System.out.println("Selenium" + " Testing"); // Selenium Testing
    System.out.println(1 + 1 + "Selenium");//2Selenium
    System.out.println("Selenium" + 1 + 1);//Selenium11
    }
-----------------------------------
String Comparison:
-------------------------------
i) String comparing using (==) operator.

It supports 2-way comparing (true/false)

ii) String comparing using equals() method

It supports 2-way comparing (true/false)

iii) String comparing using compareTo() method

It supports 3-way comparing (0, >1, <1)

if str1 == str2 thus 0
if str1 > str2 thus > 1 (Positive value)
if str1 < str2 thus < 1 (Negative value)

ANSI grapheme codes

A to Z (65 to 90)
a to z (97 to 122)
0 to ix (48 to 57)

Example:

public static void primary (String [] args){
    String str1 ="SELENIUM";
    String str2 ="selenium";
    String str3 ="SELENIUM";
    String str4 ="zselenium";
   
    //String comparing using == Relational operator
    System.out.println(str1 == str2);//false
    System.out.println(str1 == str3);//true
   
    // String comparing using equal() method
    System.out.println(str1.equals(str2));//false
    System.out.println(str1.equals(str3)); // true
   
    // String comparing using compareTo() method
    System.out.println(str1.compareTo(str3)); //0
    System.out.println(str2.compareTo(str1)); //Positive value
    System.out.println(str1.compareTo(str4)); //Negative value
        }
--------------------------------------------------
IX) Java Arrays
 

i) Introduction

> Java Array is an Object that holds a fixed disclose of values of a unmarried information type.

> The length of an Array is established when the Array is created.

> Array length is fixed, Java Array has Zero based index.
------------------------------------
ii) Declaration of Arrays
--------------------------
1st method:

int abc []; // Creating Array
    abc = novel int [4]; // Define Size
    abc[0] = 10; // Assign Values
    abc[1] = 20;
    System.out.println(abc[0] + abc[1]);//30
------------------
int abc []; // Creating Array
    abc = novel int [4]; // Define Size
    abc[0] = 10; // Assign Values
    abc[1] = 20;
    abc[4] = 40; //Error
    System.out.println(abc[0] + abc[1]);//30
--------------------------------------
2nd Method

int [] abc = novel int [5]; // Creating an Array amongst Size
    abc[0] = 10;
    abc[1] = 20;
    System.out.println(abc[1] + abc[2]); //20
------------------------------------------------
3rd Method

int [] abc = {10, 20, 30, 40, 50};
    System.out.println(abc[1] + abc[2]); //50   
--------------------------------------
iii) Creating diffiernt types of Arrays

char [] abc = {'A', 'B', 'c'}; //Array of Characters
    int [] xyz = {10, 20, 30, 40}; //Array of Integers
    String [] a = {"Selenium", "UFT", "LoadRunner"}; //Array of Strings
    boolean [] b = {true, false, false, true}; // Array of Boolean values
   
    System.out.println(abc[1]); //B
    System.out.println(xyz[0]);//10
    System.out.println(a[1]);//UFT
    System.out.println(b[2]);//false
---------------------------------------------
iv) Copy values an Array into about other Array

int [] array1 = {1, 2, 3, 4, 5};
    int [] array2 = array1;
    System.out.println(array2[2]); //3
    for (int i = 0; i < array2.length; i++){
        System.out.println(array2[i]);
    }
-----------------------------------
v) Types of Arrays

i) Single Dimensional Array

ii) Multi Dimensional Array

int [] array1 = {1, 2, 3, 4, 5};
    int [] [] array2 = {{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}}; //Multi dimensional Array
    System.out.println((array2[0][0]));//1
    System.out.println((array2[1][0]));//2
    System.out.println((array2[0][4]));//9
    System.out.println((array2[1][3]));//8
    System.out.println((array2[1][4]));//10
    System.out.println((array2[0][2]));//5
    System.out.println((array2[1][2]));//6
--------------------------------
Assignment

Print multi dimensional Array values using nested for loop
--------------------------------------------------------
vi) Advantages & Disadvantages of Arrays

Advantages:

i) Using Arrays nosotros tin optimize the code, information tin live on retrieved easily.

ii) We tin larn required information using index position.

Disadvantages

i) We tin shop fixed disclose of elements only.

ii) It doesn't modify its size during execution.
----------------------------------------------
X) Java Methods
i) Introduction

What is Method?

A laid of statements to perform an Operation.

Methods also known equally Procedures or Functions.

In Structure programming nosotros exercise Functions (Built inward together with User defined)

In Object Oriented programming nosotros exercise Methods (Built inward together with User defined)

Functions Vs. Methods
-----------------------
Functions are standalone things tin live on used individually.

Methods are by together with large associated amongst objects, but without object also nosotros tin telephone telephone methods inward Java.

Types of Methods:

Basically nosotros accept 2 types of Methods

i) Built inward Methods

ii) User defined Methods.
------------------------------------
i) Built inward Methods

> Java has a library of classes together with methods, organized inward packages.

Ex:

import java.io.Console;
import java.io.*;

> In social club to exercise built inward methods nosotros require to import packages or special classes.

> java.lang parcel is automatically imported inward whatsoever Java program.

> using import keyword nosotros tin import packages/classes.
-------------------------------------
Categories of Built inward Methods

i) String methods

ii) Character methods

iii) Number methods

iv) Array methods
etc...
------------------------------------
User defined Methods
 

Two types of User defined methods

i) Method without returning whatsoever value

ii) Method amongst returning a value
----------------------------------------
Writing methods (with returning value)

a) Syntax for creating a method together with calling the method without invoking whatsoever object:


accessmodifier nonaccessModifier returnType methodName(parameters){
Statements
----------
----------
----------
}

b) Syntax for Creating a method together with calling the method amongst invoking object:

accessModifier returnType methodName(Parameter){
Statements
---------
---------
----------
}
---------------------------

Example:
public static int add together (int a, int b){ // Creating a Method
        int result;
        upshot =  a +  b;
        render result;
    }
------------------------
Calling a Method amongst Returning a Value

Syntax:
dataType variableName = methodName(values);

example:

int xyz = add(123, 456); // Calling a Method
-----------------------------------------------
public static int multiply (int a, int b, int c){
        int result;
        upshot = a * b * c;
        render result;
}
public static void primary (String [] args){
int a = multiply(2, 4, 6);
System.out.println(a);
}
-------------------------------------
Creating together with Calling Methods using Object

Creating Objects

Synatx:

className objectName = novel className();

Example:

JavaArrays obj = novel JavaArrays();
----------------------------------
public int multiply (int a, int b, int c){
        int result;
        upshot = a * b * c;
        render result;
}
public static void primary (String [] args){

    JavaArrays obj = novel JavaArrays();
    int a = obj.multiply(2, 4, 6);
    System.out.println(a);
}
-----------------------------------------
ii) Method without returning whatsoever Value

a) Syntax for Creating a method together with calling the method without invoking whatsoever object:

acessModifier nonaccessModifier retrunType cypher methodname(parameters){
Statements
---------
-----------
------------
}
Example:
public static void studentRank (int marks){
        if (marks >= 600) {
            System.out.println("Rank A");
        }
        else if (marks >= 500){
            System.out.println("Rank B");
        }
        else
            System.out.println("Rank C");
        }

public static void primary (String [] args){
    studentRank(450);
    }
       
}
-----------------------------------
b) Syntax for Creating a method together with calling the method amongst invoking object:

accessModifier retrunType cypher methodName(parameters){
Statements
------------
-----------
----------
}

Example:

public  void studentRank (int marks){
        if (marks >= 600) {
            System.out.println("Rank A");
        }
        else if (marks >= 500){
            System.out.println("Rank B");
        }
        else
            System.out.println("Rank C");
        }

public static void primary (String [] args){
    JavaArrays xyz = novel JavaArrays();
    xyz.studentRank(450);
    }
-------------------------------
// Calling a method from about other class

public static void main(String [] args){
        JavaArrays abc = novel JavaArrays();
        abc.studentRank(650);
    }
------------------------
public static void main(String [] args){
        studentRank(650);
    }
--------------------------------------------
Creating User defined methods

    i) Creating a Method amongst returning a value

    ii) Creating a Method without returning whatsoever value
------------------------------------
Calling User defined methods

    i) Calling a method amongst returning a value together with without invoking object
    ii) Calling a method amongst returning a value together with amongst invoking object
    iii) Calling a method without returning whatsoever value together with without invoking object
    iv) Calling a method without returning whatsoever value together with amongst invoking object
    v) Calling an external method without invoking object
    vi) Calling an external method amongst invoking object
----------------------------------------
Method Overloading
------------------
Two or to a greater extent than methods amongst same name, but amongst dissimilar parameters
(different disclose of parameters or dissimilar information types)

i) past times changing dissimilar disclose of parameters

a) int add together (int a, int b)

b) int add together (int a, int b, int c)

Example:

public static int add together (int a, int b){
        int result;
        upshot = a+b;
        render result;
    }
public static int add together (int a, int b, int c){
    int result;
    upshot = a + b + c;
    render result;
}
public static void primary (String [] args){
    int a = add together (10, 20);
    int b = add together (10, 20, 30);
    System.out.println(a);//30
    System.out.println(b);//60
}
----------------------------------------
ii) past times changing information types

public static int add together (int a, int b){
        int result;
        upshot = a+b;
        render result;
    }
public static double add together (double a, double b){
    double result;
    upshot = a + b;
    render result;
}
public static void primary (String [] args){
    int a = add together (10, 20);
    double b = add together (1.234, 2.4567);
    System.out.println(a);//30
    System.out.println(b);//
}
--------------------------------------
Method Overriding

if 2 methods amongst same get upwards together with same disclose of arguments available inward super class
and sub class, thus nosotros telephone telephone those 2 methods are overridden.

Example:

Super class

int a = 10, b = 20;
public int add together (){
    int result;
    upshot = a+b;
    render result;
    }

Sub Class

    int a = 100, b = 200;
    populace int add together (){
        int result;
        upshot = a+b;
        render result;
    }
   populace static void main(String [] args){
       MethodOverloading2 xyz = novel MethodOverloading2();
       int x = xyz.add();
       System.out.println(x); // 300
      
       MethodOverloading abc = novel MethodOverloading();
       int y = abc.add();
       System.out.println(y);//30
   }
---------------------------------------
XI) Java Built inward Methods
 

Categories of Built inward Methods

i) String methods

ii) Number methods

iii) Character methods

iv) Array methods etc...
--------------------------------
i) String methods

1) compareTo() method (It compares 2 strings) - iii way comparison

if str1 = str2 thus 0
if str1 > str2 thus positive value
if str1 < str2 thus negative value

Ex:

 public static void main(String [] args){
String str1 = "SELENIUM";
String str2 = "selenium";
String str3 = "seleniuma";
String str4 = "selenium";

System.out.println(str1.compareTo(str2));
System.out.println(str3.compareTo(str2));
System.out.println(str2.compareTo(str4)); //0
   }

2) equals() method (It compares 2 strings) - 2 way comparison

 public static void main(String [] args){
String str1 = "SELENIUM";
String str2 = "selenium";
String str3 = "selenium";

System.out.println(str1.equals(str2)); //false
System.out.println(str2.equals(str3)); //true
 }
------------------------------------------------------
3) concat() Method (It concatenates / joins 2 strings)

 public static void main(String [] args){
String str1 = "Selnium";
String str2 = " Testing";

System.out.println(str1.concat(str2)); //Selenium Testing
 }
------------------------------------------
4) charAt() Method (Returns a grapheme past times position)

Example:

 public static void main(String [] args){
String str1 = "Selnium";

System.out.println(str1.charAt(1)); //e
 }
--------------------------------
5) equalsIgnorecase() method

Examples:

 public static void main(String [] args){
String str1 = "SELENIUM";
String str2 = "selenium";
String str3 = "UFT";

System.out.println(str1.equalsIgnoreCase(str2)); //true
System.out.println(str1.equalsIgnoreCase(str3)); //false
System.out.println(str1.equals(str2)); //false
 }
----------------------------------------
6) toUppercase() method (Converts values to Upper case)

Example:

public static void main(String [] args){
String str1 = "slenium";
String str2 = "SELEnium";
String str3 = "SELENIUM";
String str4 = "selenium123";

System.out.println(str1.toUpperCase()); //SELENIUM
System.out.println(str2.toUpperCase()); //SELENIUM
System.out.println(str3.toUpperCase()); //SELENIUM
System.out.println(str4.toUpperCase()); //SELENIUM123
}
------------------------------
7) toLowercase() Method (Converts values to Lower case)

Example:

public static void main(String [] args){
String str1 = "slenium";
String str2 = "SELEnium";
String str3 = "SELENIUM";
String str4 = "selenium123";

System.out.println(str1.toLowerCase()); //selenium
System.out.println(str2.toLowerCase()); //selenium
System.out.println(str3.toLowerCase()); //selenium
System.out.println(str4.toLowerCase()); //selenium123
}
-------------------------------------
8) trim() method (Removes spaces from both sides of a string)

Example:
public static void main(String [] args){
String str1 = "            Selenium               ";

System.out.println(str1);
System.out.println(str1.trim());
}
----------------------------------
9) substring method (Returns sub string)

Example:

public static void primary (String [] args) {
        String str = "Welcome to Selenium Testing";
        System.out.println(str.substring(11));//Selenium Testing
        System.out.println(str.substring(20));//Testing
        System.out.println(str.substring(11, 19));//selenium
   
    }
------------------------
10) endswith (ends amongst specified suffix)

Example:
public static void primary (String [] args) {
    String str = "Welcome to Selenium Testing";
    System.out.println(str.endsWith("Selenium Testing"));//true
    System.out.println(str.endsWith("Selenium"));//false
    System.out.println(str.endsWith("Testing"));//true
    System.out.println(str.endsWith("ing"));//true
    }
----------------------------------------------------
In Computer Programming nosotros accept iii types of Results

a) Value based Result, ex: iii + v = 8

b) Boolean or Logical Result, ex: true/false

c) Constant based Result, ex: 0, 1, -1
-------------------------------------

ii) Number Methods

1) compareTo() method

Result Criteria:

if the integer is equal to the Argument thus 0
if the integer is less than the Argument thus -1
if the integer is greater than the Argument thus 1
-------------------------------------------------
Example:
public static void primary (String [] args) {
    Integer a = 5;
    System.out.println(a.compareTo(8));//-1
    System.out.println(a.compareTo(5));//0
    System.out.println(a.compareTo(4));//1
    }
----------------------------------
2) equals Method

public static void primary (String [] args) {
    Integer a = 5;
    System.out.println(a.compareTo(8));//-1
    System.out.println(a.compareTo(5));//0
    System.out.println(a.compareTo(4));//1
    }
----------------------------------
3) abs (Returns absolute value)

double a = 10.234;
double b = -10.678;
    System.out.println(Math.abs(a));//10.234
    System.out.println(Math.abs(b));//10.676
-----------------------------------
4) circular (Rounds the value to nearest integer)

ex:

double a = 10.234;
double b = -10.678;
    System.out.println(Math.round(a));//10
    System.out.println(Math.round(b));//-11
---------------------------------------
5) 2nd (Returns minimum value betwixt 2 numbers)

Example:

public static void primary (String [] args) {
    int a = 10, b = 20;
    double c = 2.345, d = 2.3451;
    System.out.println(Math.min(a, b));//10
    System.out.println(Math.min(c, d));//2.345
    System.out.println(Math.min(5, 7));//5
    System.out.println(Math.min(1, 1));//1
    }
---------------------------------------
6) max (Returns maximum value betwixt 2 numbers)

public static void primary (String [] args) {
    int a = 10, b = 20;
    double c = 2.345, d = 2.3451;
    System.out.println(Math.max(a, b));//20
    System.out.println(Math.max(c, d));//2.3451
    System.out.println(Math.max(5, 7));//7
    System.out.println(Math.max(1, 1));//1
    }
--------------------------------
7) random (Generates random Number)

example:

public static void primary (String [] args) {
   
    System.out.println(Math.random());//
    System.out.println(Math.random());//
    }
---------------------------------------
iii) Character methods

i) isLetter (Checks conditions the value is Alfa byte or not?)

public static void primary (String [] args) {
    char a ='1';
    char b ='A';
    System.out.println(Character.isLetter(a));//false
    System.out.println(Character.isLetter(b));//true
    System.out.println(Character.isLetter('Z'));//true
    System.out.println(Character.isLetter('z'));//true
    }

---------------------------------
ii) isDigit (Returns conditions the value is Number or not?)

public static void primary (String [] args) {
    char a ='1';
    char b ='A';
    System.out.println(Character.isDigit(a));//true
    System.out.println(Character.isDigit(b));//false
    System.out.println(Character.isDigit('5'));//true
    System.out.println(Character.isDigit('z'));//false
    System.out.println(Character.isDigit('*'));//false
}
------------------------------------
iii) isUppercase (Checks conditions the value is Upper instance or not?)

public static void primary (String [] args) {
       
    System.out.println(Character.isUpperCase('A'));//true
    System.out.println(Character.isUpperCase('a'));//false
        }       
--------------------------------
iv) isLowecase (Checks conditions the value is Lower instance or not?)

public static void primary (String [] args) {
       
    System.out.println(Character.isLowerCase('A'));//false
    System.out.println(Character.isLowerCase('a'));//true
        }
-----------------------------------
iv) Array Methods

i) length

public static void primary (String [] args) {
    int [] array1 = {10, 20, 30, 40, 50};
    System.out.println(array1.length);//5
        }

----------------------------------
toString() (print Array)

public static void primary (String [] args) {
    String [] array1 = {"Selenium", "UFT", "RFT", "LoadRunner"};
    String str = Arrays.toString(array1);
    System.out.println(str);
        }
----------------------------
contains() (Checks if the Array contains surely value or not?)

Ex:

public static void primary (String [] args) {
    String [] array1 = {"Selenium", "UFT", "RFT", "LoadRunner"};
    boolean a = Arrays.asList(array1).contains("UFT");
    boolean b = Arrays.asList(array1).contains("QTP");
        System.out.println(a);//true
        System.out.println(b);//false
            }
----------------------------------
XII) Exception Handling inward Java
 

> An exceptions is an event, which occurs during execution of a program

> Exception treatment is machinery to grip exceptions

Common Scenarios where exceptions may occur
-------------------------------------------
1) Scenario where ArithemeticException occurs.

If nosotros split whatsoever disclose past times null thus ArithemeticException occurs.

Ex:

int a = 10/0;

2) Scenario where NullPointerException occurs.

If nosotros accept null value inward whatsoever variable, performing whatsoever functioning past times the variable.

Ex:

String s = null;
System.out.println(s.length()); //NullPointerException

3) Scenario where NumberFormatException occurs.

Ex:

String s ="123";
int y = Integer.parseInt(s);
System.out.println(y); //NumberFormatException

4) Scenario Where ArrayIndexOutofBounds exception occurs.

If nosotros are assigning whatsoever value inward the incorrect index.

Ex:

int [] a =  novel int [5];

a[10] = 100;
System.out.println(a[10)); //ArrayIndexOutofBounds exception
-------------------------------------------------------------
Ex:
public static void primary (String [] args) {
    int a = 10;
    int b = 0;
    int result;
   
    upshot = a/b;
    System.out.println(result);
    System.out.println("Hello Java");
    System.out.println("hello Selenium");
    }
--------------------------------------
Use endeavor block

Syntax:

try {
Statements
----------
-----------
---------
}
catch (exception e) {
Exception treatment code
}
---------------------------------------
public static void primary (String [] args) {
    int a = 10;
    int b = 0;
    int result;
   
    endeavor {
    upshot = a/b;
    System.out.println(result);
    }
    grab (ArithmeticException e) {
        System.out.println("Divided past times Zeo Error");
    }
    System.out.println("Hello Java");
    System.out.println("Hello Selenium");
    }
------------------------------------------
Multiple endeavor blocks for treatment multiple exceptions

public static void primary (String [] args) {
    int a = 10;
    int b = 0;
    int result;
    int [] array = novel int [4];
   
    endeavor {
    upshot = a/b;
    System.out.println(result);
    }
    grab (ArithmeticException e) {
        System.out.println("Divided past times Zeo Error");
    }
    System.out.println("Hello Java");
   
    endeavor {
    array[10] = 100;
    System.out.println(array[10]);
    }
    grab (ArrayIndexOutOfBoundsException e){
        System.out.println("Array Out of saltation Error");
    }
    System.out.println("Hello Selenium");
    }
------------------------------------------------------
IO Operations inward Java
 

Output on the Console

System.out.println ();

System.out.println(a); //100
System.out.println("Selenium Testing");//Selenium Testing
System.out.println("Selenium Testing " + a);
System.out.println("Selenium Testing " + " Java programming");
---------------------------------
Input

There are iii ways available for reading input.

i) Scanner

ii) DataInputStream

iii) BufferedReader
--------------------------
using java.util.Scanner is the easier together with includes methods to banking firm represent the input data.

public static void primary (String [] args) {
     Scanner scan = novel Scanner(System.in);
    
     System.out.println("Enter Your Name");
     String s1 = scan.nextLine();
     System.out.println("Your get upwards is: " + s1);
   
     System.out.println("Enter Your City");
     String s2 = scan.next();
     System.out.println("Your City is: " + s2);
   
     System.out.println("Enter a Number");
     int i = scan.nextInt();
      System.out.println("Value is: " + i);
     
     System.out.println("Enter Your Phone Number");
     long s3 = scan.nextLong();
     System.out.println("Your City is: " + s3);
    
     System.out.println("Read a Value");  
     double b = scan.nextDouble();
     System.out.println("Value is "+ b);
    
     scan.close();
         }
---------------------------------
File Handling inward Java
 

Using File shape nosotros tin perform File operations

Examples:

1) Create a Folder

public static void primary (String [] args) {
    File abc = novel File ("C:/Users/gcreddy/Desktop/Selenium");
    abc.mkdir();
    }
--------------------------
2) Check the beingness of Selenium folder

public static void primary (String [] args) {
    File abc = novel File ("C:/Users/gcreddy/Desktop/Selenium");
    boolean a = abc.exists();
    System.out.println(a); //true
    }
----------------------------------------------
3) Delete a Folder

public static void primary (String [] args) {
    File abc = novel File ("C:/Users/gcreddy/Desktop/Selenium");
    abc.delete();
    boolean a = abc.exists();
   
    if (a == true){
        System.out.println("Folder exists");
    }
    else
    {
        System.out.println("Folder Not exists");   
    }
   
    }
-----------------------------------------------
4) Create a Text file

public static void primary (String [] args) {
    File abc = novel File ("C:/Users/gcreddy/Desktop/Selenium.txt");
    endeavor {
        abc.createNewFile();
    } grab (IOException e) {
        // TODO Auto-generated grab block
        e.printStackTrace();
    }
-----------------------------
5) Delete a Text file

public static void primary (String [] args) {
    File abc = novel File ("C:/Users/gcreddy/Desktop/Selenium.txt");
    abc.delete();
}
---------------------------------------------
Java OOPS Concepts
 

OOPS - Object Oriented Programming System.

Four fundamentals of OOPS:

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation
----------------------------------------------
Java OOPS: Inheritance
 

> It is a procedure of Inheriting (reusing) the shape members (Variables together with Methods) from ane shape to about other shape is called Inheritance.

> Non static (Object Level) shape members merely tin live on inherited.

> The shape where the shape members are getting inherited is called equally Super shape / raise shape / Base class.

> The shape to which the shape members are getting inherited is called Sub shape / Child shape / Derived class.

> The inheritance betwixt Super shape together with Sub shape is achieved using "extends" keyword.
------------------------------
How to practice static shape members?

Using static non access modifier.

How to exercise Static shape members?

Using Class get upwards nosotros tin access static shape members.

How to exercise Non static shape members?

Using Object/Instance nosotros tin access Non static shape members.


Creating object inward a class

Syntax:

ClassName InstanceVariable = novel ClassName();

example for accessing static together with non static shape members:
----------------
static int a = 10, b = 20; // Static variables
    int c = 30, d = 40; // Non static variables
   
    populace static void add() { //static Method
        System.out.println("Addition of a, b is: " + (a+b));
    }
   
    populace void add2() { //Non static method
        System.out.println("Addition of c, d is: " + (c+d));
    }
public static void primary (String [] args) {
    // Access Static shape members using shape name
    System.out.println(FileHandling.a);//10
    FileHandling.add();//30
   
    //Access Non static shape members using Object/Instance
    FileHandling obj = novel FileHandling();
    System.out.println(obj.c);//30
    obj.add2();//70
}
--------------------------------------------------
Three types of Inheritance

i) Single Inheritance

Ex:

class B extends shape H5N1 {
--------------------------------
ii) Multi flat Inheritance

ex:

Class B extends shape H5N1 {

Class C extends shape B {

iii) Multiple Inheritance (* Java doesn't support)

Ex:

Class B extends Class H5N1 {

Class B extends Class D {
----------------------------
Class 1:

public shape H5N1 {
int a = 10;
int b = 20;
public void addition() {
    System.out.println("Addition of a, b is: " + (a+b));
}
public void subtraction() {
    System.out.println("Subtraction of a, b is: " + (a-b));
}
public static void primary (String [] args){
    H5N1 myObject = novel A();
    System.out.println(myObject.a);//10
    myObject.addition();//30
}
}
-------------------------
Class 2

public shape B extends H5N1 {
    int a = 100;
    int b = 200;
    populace void addition() {
        System.out.println("Addition of a, b is: " + (a+b));
    }
public static void primary (String [] args){
    H5N1 obj1 = novel H5N1 ();
    obj1.addition(); //30
    obj1.subtraction();//-10
   
    B obj2 = novel B();
    obj2.addition();//300
}
}
-------------------------------------
Class 3

public shape C extends B {
    int a = 1;
    int b = 2;
    populace void addition() {
        System.out.println("Addition of a, b is: " + (a+b));
    }
public static void primary (String [] args){
    //Accessing shape members from Home class
    C obj1 = novel C();
    System.out.println(obj1.a); //1
    obj1.addition();//3
   
    //Accessing shape members from raise class
    B obj2 = novel B();
    obj2.addition();//300
   
  //Accessing shape members from Grandparent class
    H5N1 obj3 = novel A();
    obj3.addition(); // 30
}
}
----------------------------------------------------
Java OOPS: Polymorphism
 

Polymorphism means, beingness of Object demeanor inward many forms

There are 2 types of Polymorphism

i) Compile Time Polymorphism / Static binding / Method overloading

ii) Run Time Polymorphism / Dynamic binding / Method overriding

i) Compile Time Polymorphism
If 2 or to a greater extent than methods having same get upwards inward the same shape but they differ inward the next ways.

i) Number of Arguments

ii) Type of Arguments

public shape MethodOverloading {
    populace void add(int a, int b){
        System.out.println(a+b);
    }
    populace void add(int a, int b, int c){
        System.out.println(a+b+c);
    }
    populace void add(double a, double b){
        System.out.println(a+b);
    }
    populace void add(double a, double b, double c){
        System.out.println(a+b+c);
    }
    populace static void primary (String [] args){
        MethodOverloading obj = novel MethodOverloading();
        obj.add(10, 20);
        obj.add(10, 20, 30);
        obj.add(1.2345, 2.3456);
        obj.add(1.2345, 2.3456, 4.45678);
    }
}
-----------------------------------------
ii) Run Time Polymorphism
If 2 or to a greater extent than methods having same get upwards together with same arguments available inward the super shape together with sub class.

Example:

Class 1

public shape H5N1 {

public void addition(int a, int b) {
    System.out.println(a+b);
}
public static void primary (String [] args){
    H5N1 myObject = novel A();
    myObject.addition(10, 20);//30
}
}
------------------------------
Class 2

public shape B extends H5N1 {
    populace void addition(int a, int b) {
        System.out.println(a+b);
    }
public static void primary (String [] args){
    H5N1 obj1 = novel H5N1 ();
    obj1.addition(10, 20); //30
       
    B obj2 = novel B();
    obj2.addition(40, 50);//90
}
}
--------------------------------------------------
Java OOPS: Abstraction
 

It is a procedure of hiding implementation details together with showing merely functionality to the user.

In coffee nosotros accept 2 types of methods

i) Concrete methods (The methods which are having body)

ex:

public void add(){
Statements
---------
--------
---------
}

ii) Abstract methods (The methods which are non having body)

Ex:

public void add();
-------------------------------------------------
if nosotros know the method name, but don't know the method functionality,
then nosotros become for abstract methods.

Java Class contains 100% concrete methods

Abstract Class contains ane or to a greater extent than abstract methods.

Ex:

Class 1 (having 10 methods)

(10 methods are concrete methods)

It is a Java Class
-------------------------
Class 2 (having 10 methods)

(5 concrete Methods together with v abstract methods)

Abstract class
--------------------------
Class iii (having 10 methods)

(10 methods are Abstract methods)

Abstract class
----------------------------------
public shape HeroHonda extends Bike {

    @Override
    populace void handle() {
        System.out.println("Bikes accept handle");
        }
    @Override
    populace void seat() {
        System.out.println("Bikes accept Seat");
    }
    populace static void primary (String [] args){
        HeroHonda obj = novel HeroHonda();
        obj.handle();
        obj.engine();
        obj.seat();
    }
-------------------------------------------
Selenium IDE has User interface

Selenium Webdriver is a Programming Interface

UFT has IDE together with Programming Interface

Java Interfaces
 

> Interface is a Java type Definition block which is 100% abstract.

> All the Interface methods are past times default populace together with abstract.

> Static together with concluding modifiers are non allowed for interface methods.

> In Interfaces variables accept to initialize at the fourth dimension of declaration.

int a; // Incorrect

int a = 10; // Correct

> In interfaces variables are populace static concluding past times default.

> Interface is going to live on used using "implements" keyword.
--------------------------------------------
Ex:

public shape Exa3 implements Example1{

    @Override
    populace void add() {
        System.out.println("Addition");
        }

    @Override
    populace void sub() {
        System.out.println("Subtraction");
        }
public static void primary (String [] args){
    Exa3 abc = novel Exa3();
    abc.add();
    abc.sub();
}
}
--------------------------------------------------------
From Class (Concrete Class or Abstract Class) to Class nosotros exercise "extends" keyword

i) From Concrete Class to Sub shape - nosotros tin access Super shape methods directly.

ii) From Abstract Class to Sub shape - Implement all abstract methods thus nosotros tin access all methods.
----------------------------------------------
From Interface to Class nosotros exercise "implements" keyword

From Interface to Class - Implement all methods together with access.
--------------------------------------
Java OOPS: Encapsulation
 

It is a procedure of wrapping code together with information into a unmarried unit.

Encapsulation is the technique making the fields inward a shape private together with providing access via populace methods

> It provides us command over the data

> By providing setter together with getter methods, nosotros tin brand a shape read merely or write only.

> If nosotros don't define setter method thus read only.

Example:

Class 1:
public shape Class1 {
    private String get upwards = "Test Automation";
   
    populace String getName(){
        render name;
    }
   
    populace void setName (String newName){
        get upwards = newName;
    }
}
-------------------------
Class 2:

public shape Class2 extends Class1 {

    populace static void main(String[] args) {
        Class1 obj = novel Class1();
        //obj.setName("Selenium");
        System.out.println (obj.getName());
    }
}
----------------------------------

Sumber http://www.gcreddy.com/
Post a Comment (0)
Previous Post Next Post