Thursday, 29 April 2021

Cypress Library

CYPRESS LIBRARY: 

package MavenTestNG;


public class A1CypressTutorial {


public static void main(String[] args) {

}

}


/*

IMP URL's

Learn JS from here

https://developer.mozilla.org/en-US/docs/Web/JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Assertions: https://docs.cypress.io/guides/references/assertions.html#Chai


Test Websites:



//1)CYPRESS PROGRAM==HANDLING WEB TABLE DATA===============

/// <reference types="Cypress" />

describe('My Second Test Suite', function() 

{

it('My FirstTest case',function() {

//Check boxes

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

//grab the nth required column value and get value from array index:

cy.get('tr td:nth-child(2)').each(($e1, index, $list) => {

     const text=$e1.text()

    if(text.includes("Python"))

    {

         cy.get("tr td:nth-child(2)").eq(index).next().then(function(price)

        {

         const priceText=   price.text()

         expect(priceText).to.equal('26')

        })

    }

 })

 })

 })

//2)CYPRESS PROGRAM==HANDLING CHILD WINDOW LINKS ==============

describe('My Second Test Suite', function() 

{

it('My FirstTest case',function() {

//Check boxes

cy.visit("http://qaclickacademy.com/practice.php")

cy.get('#alertbtn').click()

cy.get('[value="Confirm"]').click()

//window:alert

cy.on('window:alert',(str)=>

{

//Mocha FW-compare strings: expect(str1).to.equal(str2)

expect(str).to.equal('Hello , share this practice page and share your knowledge')

})

cy.on('window:confirm',(str)=>

{

//Mocha

expect(str).to.equal('Hello , Are you sure you want to confirm?')

})

//Opening child window from the same browser by removing target link in DOM

cy.get('#opentab').invoke('removeAttr','target').click()

//String attribute assertion and then apply browser back button 

cy.url().should('include','qaclickacademy')

cy.go('back')

}  )


}  )

//3)CYPRESS PROGRAM==HANDLING HIDDEN LINKS==============

// <reference types="Cypress" />

 

describe('My Second Test Suite', function() 

it('My FirstTest case',function() {

//Check boxes

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

//cy.get('div.mouse-hover-content').invoke('show')

cy.contains('Top').click({force: true})

cy.url().should('include','top')

})

})


//4)CYPRESS PROGRAM==HANDLING FRAMES==============

/// <reference types="Cypress" />

/// <reference types="Cypress-iframe" />

import 'cypress-iframe' //this will import cypress libraries


// npm install -D cypress-iframe (this command will download iframe related libraries and supports for IFrames)

 

describe('My Second Test Suite', function() 

it('My FirstTest case',function() {

//Iframe window and assertions (text and count assertions), always mention cy.Iframe if you want actions on iframe

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

cy.iframe().find("a[href*='mentorship'").eq(0).click()

cy.iframe().find("h1[class*='pricing-title'").should(have.ength', 2]

})

})


//4)CYPRESS HOOK (Annnotations)

 https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests.html#hooks

before -It should be outside of it block, inside describe block

after- 

beforeEach- before of each test case (it block)

afterEach-

 

//5)CYPRESS commands to store all custom/reusable functions

//Command.js to store reusable function in JSON (eg=SelectProduct function)

no need to create object etc..

 Cypress/Commands.add("SelectProduct", (productName) => {

 cy.get('h4.card-title').each($e1, index, $list) => {

  if($e1.text().includes(productName))

  {

  cy.get('button.btn.btn-info').eq(index).click()

  }

 }

 }


 */



=================================================================

##ItemDescription
01Cypress Child widnowVerify target is exist or not ?
Open child in same window, by removing target attribute to child will open on same windiw
02Target attribute
target='_blank'
Cypress having ability to manipulate the DOM-so we can  remove target attribute:
manipulate DOM to handle to open in same window
 
qaclickacademy.com
03Invoke Method Invoke Method will invokes function on previoulsy used method
cy.get('#opentab').invoke('removeattr', 'target').click()
Here after the link will open on same browser instead of opening in new windiw
04non fleaky testconsistent results from test using same browser 
05Browser back navigation
go method
cy.go('back')
cy.go('forward')
cy.url().should('include', 'qaclickacademy')
cy.go('back')
06url methodurl method to get the current url of the opened page
cy,location('href')
cy.url()
cy.url(options) 
07include - substring assertion methodsubstring assertion to check whether string included or not
cy.url().should('include', 'qaclickacademy')
cy.go('back')
08Web table handling Web table handling
https://rahulshettyacademy.com/AutomationPractice
cy.visit("url")
CSS selector to select all columns in table
tr- rows
td- columns
nth child CSS= tr td:nth-child(2) //this will give 2nd column
Write css for all columns, iterate columns to get required values, then pgrab nex t row value using index and apply next method,. resolve promise and capture expected value 
09next() methoduse this method on get() method in cypress
10eq() methodeq method will use from array value grabbing
we need to pass index to eq method to pull that index value
11then() methodthen method will be used to resolve current promise- and use the parameter to handle non cypress methods
12expect() methodexpect(price.toeqial('25')
use expect method to compare expected and actual values
13Mouse over on menu
Show() method
actions in Selenium,  no specific method in Cypress.
Jquery function to trigger mouse over - show() method can be used
move to that element and apply mouse over using show method to display hidden elements
Show method should be applied on immediate parent of hidden element 
14click() method for hidden elementcy.get('button').click({force: true})
We need to use force true when you want Cypress to click on hidden element 
15Open new windiw handlecopy new window url(using href attribute) and open on same browser to work on new windiw
Else remove target from DOM to use current browser to open link
16get attribute value
prop() jquery method
jQuery method to get the value of the property
use then function to resolve promise and use Jquery method to get property
17cy.log(url)will log url value in test runner
18Cypress restricts to visit one domain to another domain 
19Handling FRAMES in Cypress/// <reference types="Cypress-iframe" />
import 'cypress-iframe'
cy.iframe().find("a[href*='mentorship'").eq(0).click()
20Setting up test hooks
21Data Driven testFrom FIXTURES folder -cypress will get data from external files
1 JSON file for 1 test case and use for execution
22Custom Cypress commandsSupport> commands folder to save and reuse functions into the tests
23ParameterizationTell to JSON prodname is as Array to store multiple values ..  put fixtures as before hook
JS treats [] as array  productName":["nokia", "voda"]
how to iterate array in JS?
this.data.productName.forEach(function(element){
cy.selectProduct(element)
});
24Debug tests/ pause test
debug()
cy.pause()
cy.pause() method use to pause your test, resume button from test runner will continue the test
we can use debug() method also at end of step line to debug code
25POM design pattern
Create JS class for each page under Integration folder and export , import from classes 
Collect objects of page and update in 1 JS class..
INtegration folder> HomePage.js
class HomePage
{
getEditBox()
{ return cy.get('#test')  //this return is mandatory to return to object
}
getGender()
{
}
export default Homepage; //will available in all classes with this line
26Directory and creating objects from custom class../ (this will bring current directory) ; ../pageObjects/HomePage eg:
import HomePage from ' ../pageObjects/HomePage'
Create object in JS  ---> const homePage= new HomePage()
homePage.getEditBoac().type(this.data.name)  //using webelement from homePage class POM
27Config changes Cypress.jsontimeout can be updated from Cypress.json - global wait/timout
If you want to handle in specific class- we can update timeout config to that class only
28Screenshots & video path
29Cypress Dashboard
30Global Environment Variablesglobal variables declared to access for all test cases like url, username, env etc..
Global variables exposed by Cypress from cypress.json file
Global customer variables by user created - into another Cypress.json file
cy.visit(Cypress.env('url'))  --> this will bring actual url from global va from cypress.json
31Reporting for execution
32Integrate Cypress with CICD
33Assertion for PASS & Failcy.get('.alert').then(function(element)
{
const actualtext=element.text()
expect(actualText.includes("Success")).to.be.true
expect(actualText.includes("Success")).to.be.false

})
34split() method from the string (r. 50000) splits before and after space from e. 50000
var result= actualText(split(" ")
result[1].trim()
r. 50000 this will be split into 2 below in array indexes
result[0]= R.
results[1]=50000

car sum=0
sum=Sum+result
35convert strig to Number in JSsum=Number(sum)+Number(result)
36Cypress.env('url')
CLI command line interface
to get gloabl variable from cypress.json file which is created by custom variable
CLI method to update url:
cypress run
cypress run
PS C:users\rahul\projects\auto> node_modules\.bin\cypress run  --> TO RUN ALL TESTS
37Cypress run in chrome cmdcypress run -browser chrome
cypress run -b chrome
cypress run -b chrome -headed
38Cucumber with Cypressgithub page.. https://github.com/TheBrainFamily
 https://github.com/TheBrainFamily/cypress-cucumber-preprocessor
Install this plugin for your cypress..  package.json will hae an entry
npm install --save dev cypress-cucumber-preprocessor
Add cucumber preprocessor command into the plugins/index.js file
const cucumber = require('cypress-cucumber-preprocessor').default
module.exports = (on, config) => {
on('file:preprocessor', cucmber())
}
39inform cypress about feature files - command in you need to tell cypress to pick feature files to execute,,
"testFiles": "**/*.feature",
40Downlod plugin for cucumber feature filesvisual studio bdd extension ..
Cucumber(Gherkin) Full support plugin..
eCommerce.feature create file..
examples>BDD>eCommerce.feature
Feature: End to End E-commerce validation

application Regression
Scenario: eCommerce prod delivery
Given on Ecommerce web page
When adding items to the Cart
And validate the total pricess and submit
Then verify the success message on submission.
Then 
41steps pluginexamples>BDD>ecommStepDef.js craete step def file..
import {Given, When,Then} from "cypress-cucumner-preprocessor/steps";  add this 
42annonymous function - FAT OPERATORwe can change function() to ananymous function as ()=> when a function donn't havve name
Mocha not supports this fat operator [IMP]
43hooks in stepDefExamples>BDD>ecommerce> beforeEach.js   craete hook file -supports mocha related hooks 
44come out of sub folders ../../../../support/pageObjects/HomePage'
'../../../../support/pageObjects/ProductPage'   each ../ means one sub folder.
45Run cucumber feature filecypress run --spec cypress\integration\examples\BDD\ecommerce.feature --headed --browser chrome
46Data Driven Test in Cucumberfunction(dataTable) will bring feature file data into stepDef .js file
dataTable.rawTable[1]  -first row will be trieved,
dataTable.rawTable[1][0] this will give first col value from first row- nem value
dataTable.rawTable[1][1] this will give second col value from first row- nem value 
47variable inside function and global declaration
let method
let name = dataTable.rawTable[1][0] this will accessed within block/function
if you declare at global level, then it will accessible from all classes..
let name = this can accessible in all functions/blocks
48Tagging for sceanrios/ tagged test s @Regression
 ' @Smoke
Scenario                                                                                         
49npx  -use to shorten commandnode_modules\\.bin  this is equal
npx cypress-tags run -e TAGS="@Smoke" --headed --browser chrome
50cucumber.json outfile from cucumber-json folder will be created .this file is output of all feature files execution results
We need to add additional json object to the package.json file.. it will generates json file in outFolder..
so now use other plugin to read json output file and create html dahsboard report
STEP1- install plugin into yourframework.. npm install multiple-cucumber-html-reporter --save-dev  [this will add plugin into package.json file]
STEP-2  under proj create folder named as  cucumber-html-report.js and paste content - that wil create html report .
cucumber2.js js file will go and read output json file and creates cucumber dashboard report
STEP3 enter jsonDir path value.. cucumber.json path
reportPath - value
STPE 4- run this js file?  node cucumner-html-report.js
STEP 5- goto reports folde and open index.html report
51Xml http Request. API testing with CypressXHR test :is an api/XHR object to send data from abrowser to web server as response..
kitchensink application  -test api website..
https://example.cypress.io/commands/querying
https://example.cypress.io/commands/network-requests
F12--> Network Tab -- XHR tab- select row -- header , preiew , repsonse, Timing..
52cy.server()start server to begin routing responses to ..
route is  - Initiation of server command to listen API calls
53cy.route() for GET methodhelps to manage the behaviour of network request.
cy.route('GET', 'comments/*') as (;getCommnet')
54cyprus its method -to get a property value on the previously got value..
its('status')
cy.wait(@getComment').its('status').should('eq', 200)
55POST method// Listen to POST to comments
cy.intercept('POST', '**/comments').as('postComment')
// we have code that posts a comment when
// the button is clicked in scripts.js
cy.get('.network-post').click()
cy.wait('@postComment').should(({ request, response }) => {
  expect(request.body).to.include('email')
  expect(request.headers).to.have.property('content-type')
  expect(response && response.body).to.have.property('name', 'Using POST in cy.intercept()')
56Mock/Mimic API calls using CypressMock service response to replicate the issue/or to capture error / error handling scenario..
Cypress will inject the fake response to browser - 404 -then expected exception handling can be tested ..
57Stubbing responsecy.server()
cy.route()
58requet method -without using uIexplicitely hitting the server method..
resolve the promise and extract the response for validation..
59Cypress Request documentationhttps://docs.cypress.io/api/commands/request.html#Syntax
https://docs.cypress.io/api/commands/request#Method-and-URL
60SQL database connection with CypressCloud SQL server to connect and get data and connect with Cypress
SQL server on Azure.. Start Free account .. create MS account and login..
Azure Sign on form, entetr credit card details.. for 1.5 month free and ask for renew..

Create Resourece, Slect Create SQL database.. enter DB name rahulacademy ..create new Server .. rsademo..
take few min to setup..
Go to Query Eiditor--> Add IP address into firewall rule to query..
Set server Firewall -- Add clinet IP - save and retry login
Home page -select DB and select query Editor and login..
Create New EMP table using DB query..  and click RUN..
insert records intp EMP table..
Retrieve records from table using query..
DB server, Database, Table, records have been craeted ..



61VS Editor- create empty folder CypressDBGo to Terminal, enter command
nps cypress -save-dev  [to install and creates cypress project to start working on it]
INvoke cypress dash board using
go to path of node modules..
./node_modules/.bin/cypress opn  OR use below simple command to open cypress
npx cypress open 
62Cypress DB plugin integration for DB testing.bring cypress sql jars..
npm install --save-dev cypress-sql-server
should have package.json and download dependencies.. for easy use..
npm init -y  [it will create package.json file and all dependencies will be brought into it]
https://www.npmjs.com/package/cypress-sql-server
initialise plugin into cypress index.js file,so plugin will be initialised..
go to index.js file and enter below lines..
const sqlServer = require('cypress-sql-server');

module.exports = (on, config) => {
  tasks = sqlServer.loadDBPlugin(config.db);
  on('task', tasks);
}
Go to support.index.js file and use bellow lines..
import sqlServer from 'cypress-sql-server';
sqlServer.loadDBCommands();

Go to cypress.json and add below AZURE DB details..:
"db": {
    "userName": "",
    "password": "",
    "server": "",
    "options": {
        "database": "",
        "encrypt": true,
        "rowCollectionOnRequestCompletion" : true
    }
}

Go to Index.js file and add below config details to connect with DB server details.
const dbConfig = require('../../cypress.json')
63Create DB test fileGo to integration -- create a new file ..



JAVA Library

 

package MavenTestNG;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;


public class A3JavaLibrary {

//ctrl space

// tab - to indent


/* Strategies and rules in JAVA;

//second and third line of code will print as single statment as there is no PrintLn

// TODO Auto-generated method stub

//SysOut and click ctrl+space will open the options to get display complete print statement

//type main and click ctrl+space to get display complete main method statement

//click Ctrl+I which will indent code in your program

//select line of code and Ctrl + 7 which will comment the selected code lines 

//right click on package/class and selct refactor option to rename the package/class name

//public is access modifier , each class will have first line with package name

//Main method used to execute the program

//void is a return type -if no return type nothing to mention, if any return type then mention as String/Int which will be returned

//static can be called in any class/method 

//Compile program and run/execute java code using Run button/ right click -run as Java application

//right click on class -then Run as Java application to see output of code


 

Type SysOut and click Ctrl+Space to automatically bring the print statement syntax;

System.print("XYZ"); //prints in same line

system.println("ABC); //prints in next line

//Use "//" to comment sigle line AND for multiple lines use as /* text /*

*Declare variable and assign values -then use those variables to print;

static int a =4;

system.println(a); 

*Use double quotes to print string values and do not use for variables to be printed;

*void means not retrurn anything as an output;

*If function return expected string or int -then mention String/Int in method as return type;


**STRING: It is one of the in-built class in JAVA; 

There are two ways to define strings; 

1) String leteral way   Eg: String a ="Value of String";

2) by creating object of String class way   Eg: String sn = new String("Value of String); 


**STRING METHODS:

String st ="JavaTraining";

System.out.println(st.charAt(3));

System.out.println(st.indexOf("T"));

System.out.println(st.substring(4));

System.out.println(st.substring(4, 9));

System.out.println(st.concat("Venkat is learning"));

System.out.println(st.length());

System.out.println(st.toUpperCase());

System.out.println(st.toLowerCase());

System.out.println(st.replace("t", "s"));

String arr[]=st.split("T");

System.out.println(arr[0]);

System.out.println(arr[1]);


***METHODS- these are blocks in java class

Reusability we will use to call in other programs;

Methods should be written outside the main block and call in main block;

Create an object of class in any other class, and reuse those methods,variables,functions;


***IF CONDITION: based condition true or false-then respective block will be executed

If you have single line in statement - then we can remove braces under true/false condition and Java will execute that statement.

if(5>2) //Condition

{

SysOut.pintln(Execute this first statement)

}

else{

SysOut.pintln(Execute this second statement)

}


***FOR LOOP: 

for(i=0; i<=10; i=i+2)

{

if(1==8)

SysOut.pintln("8 is displayed");

else

System.Out.println("it is not found");

}

}


***WHILE LOOP SYNTAX:

int k=0; //INCREMENTAL WHILE LOOP

while(k<10)

{

System.out.println("while loop value now is "+ k);//this will print value from 0 to 10 incremental value

k++; //this condition will terminate the loop when it becomes false

}


int m=10;//DECREMENTAL WHILE LOOP 

while(m<0)

{

System.out.println("while loop value now is "+ m); //this will print from 10 to 1-decremental value

m--; //this condition will terminate the loop when it becomes false

}

***DO WHILE LOOP- execute block until the condition become false -this will execute at lease once

int n=10;

do {

System.out.println("DO WHILE LOOP value is " + n);

n++;

}

while(n<=30); //Execution will be terminated once n value reaches to 30 as per condition


***NESTED LOOPS:  (WITH OUTER AND INNER LOOPS; each outer loop cycle will execute all cycles from inner loop) 

for(int x=1; x<=3; x++) //Outer For loop will execute 3 times

{

for(int y=1;y<=4;y++) //Inner for loop will execute 4 times

{

System.out.println("this line is from INNER loop");

}

System.out.println("this is for OUTER loop value");

}


**** NESTED FOR LOOP to PRINT PYRAMID model output:

int r=1;

for(int p=0; p<4; p++) //Outer For loop will execute 3 times

{

for(int q=1;q<=4-p;q++) //Inner for loop will execute 4 times

{

System.out.print(r);

System.out.print("\t"); //this is used to add space after the output value

r++;

}

System.out.println("");

}

System.out.println("Pyramid model printed Descending model");

*****NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output

int c1=1;

for(int a1=1; a1<5; a1++) //Outer For loop will execute 3 times

{

for(int b1=1;b1<=a1;b1++) //Inner for loop will execute 4 times

{

System.out.print(c1);

System.out.print("\t"); //this is used to add space after the output value

c1++;

}

System.out.println("");

}

System.out.println("Pyramid model printed Ascending model");


***BREAKPOINT - double click on the line number will add breakpoint -which will used for execute code in DEBUG mode

STEPINTO-F5 - to execute code step by step

STEPOVER-F6 


****INTERFACE METHODS- IMPLEMENTATION IN CLASS

public class AusTrafficSystem implements CentralTraffic {


/* You can use interfaces without body in other class by using syntax as "Implements InterfaceName" (you can mention multiple interfaces using comma seperated)

once you implemented interface, we need to improt the all interface methods to new class

Once all interface methods are loaded in to the target class we can add additional code blocks to those interface methods

We need to create object of interface in target class to execute all blocks -SYNTAX is "interfacename Objname = new Classname();"

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("HELLO ");

CentralTraffic au=new AusTrafficSystem();

au.redStop();

au.flashyello();

au.greenGo();

AusTrafficSystem at = new AusTrafficSystem();

at.walkOnSymbol();


}


public void walkOnSymbol() {

System.out.println("local method");

}

@Override

public void greenGo() {

// TODO Auto-generated method stub

System.out.println("Green");

}

**** ABSTARCTTiON AND ABSTRACT METHOD:

Abstraction - process of hiding implementatio details 

Abstract Method is a method defined without body.

Parent class - where child classes are inherited 

INTERFACES - all methods in interface are Abstract methods 


A class which is declared with abstract keyword called as Abstract class

A class can be called as Abstract class if that has atleast one abstract menthod.

Class may contain both implimentation methods & Non implimentation methods.

Abstract classes achieves partial Abstraction whereas Interfaces achive 100 % abstraction 

We can create object for Abstract classes / we cannot instntiate abstract classes.

Abstract methods should be declared as public methods- which they need to be reused. (they should public or protected)

Child classes will be forced to implement abstract class methods

extends keyword used to inheritence of parent class in child class

implements keyword used to implement interface methods.


*****Inheritence in JAVA

Reuse of parent class related methods, properties in other child

 classes using inheritance concept:

NOTE: Java will not support/allow  multiple inhertitence in single child class.

//Use "extends" keyword for inheritance of parent class, methods, properties in child classes.


public class childClass extends parentClass 

{

public void engine() {

System.out.println("new Engine");

}


public void color() {

System.out.println(color); //this color property is being used from parent class which was inhertited

}


public static void main(String[] args) {

childClass cc=new childClass();

cc.color();

cc.engine();


}

}


*****FUNCTIONOVERRIDING /METHOD OVERRIDING:

When both methods(parent class method1, child class method2) are having same method name, signature, arguments and return type- 

then java will give prefernce to the local child class method 2 and it will overide the parent class method 1;

This is called functionoverriding. 

In Function overloading method arguments/return types different where as in FunctionOverloading arguments and all are same.



****FINCTION OVERLOADING:

If same class is using multiple methods with same method names are called as Function overloading.

Those methods should be differentiated with different arguments  

Rules are 1) either argumets count should be different OR 2) arguments data type/return type should be different,else java will throw errors


public class functionOvverloading {

public static void main(String[] args) {

// TODO Auto-generated method stub

functionOvverloading fo = new functionOvverloading();

fo.getdata(3);

fo.getdata("Hello");

fo.getdata(2, 5);


}


public void getdata(int a) {

System.out.println(a); //method 1 has argument return type as int

}

public void getdata(String a) {

System.out.println(a); //method 2 has argument return type as String

}

public void getdata(int a, int b) {

System.out.println(b); //method 3 has multiple arguments than method 1

}

}

*****ARRAYS: A container which stores mutiple values of same data type.

If you want to save multiple values we will use Arrays

new keyword allocates memory which will provide space for 5 values;

declares an array and allocated memory for 5 integers


*** SINGLE DIMENTION ARRAY: SYNTAX int a[index]=value;

*** MULTI DIMENTIONAL ARRAY: SYNTAX  int a[row index][column index]={value1, value2}


public class Arrays {


public static void main(String[] args) {

/SINGLE DIMENTION ARRAYS

//1st method of array initialization and assign values to array 

int b[]= {10,20,30,40,50,600};

for(int j=0; j<b.length;j++)

{

System.out.println("Single dimentional array 0 value is " + b[j]);

}


//2nd method of array initialization and assign values to array

int a[] = new int[5]; //declares an array a[] and allocated memory for 5 integers

a[0]=2;

a[1]=3;

a[2]=10;

a[3]=14;

a[4]=15;


for(int i=0; i<a.length;i++)

{

System.out.println("Single dimentional array 1 value is " + a[i]);

}


//MULTI DIMENTIONAL ARRAY:  int a[row][column]

int p[][] = new int[2][3]; //declares an array a[] and allocated memory for 5 integers

p[0][0]=2;

p[0][1]=3;

p[0][2]=10;

p[1][0]=14;

p[1][1]=15;

p[1][2]=16;

System.out.println("Multi dimentional array 0 value is " + p[1][2]);

for(int i1=0;i1<2;i1++) {


for(int j1=0;j1<3;j1++) {

System.out.println("Multi dimention array content is " + p[i1][j1]);

}

}


int q[][]= {{100,20,30},{40,50,600}};

System.out.println("Multi dimentional array 1 value is " + q[1][0]);

}

}


**** DATE CLASS:

*DATE Class comes from util package which will used to retrive date,Current date, current time, to print date we need to convert o String and then print stmt


import java.text.SimpleDateFormat;

import java.util.Date;

Date dt = new Date();

System.out.println(dt.toString());

//print as Sat Dec 05 12:30:46 AEDT 2020 


//Simple date format class

SimpleDateFormat sdf=new SimpleDateFormat("M/dd/yyyy");

System.out.println(sdf.format(dt));

SimpleDateFormat sd=new SimpleDateFormat("M/dd/yyyy hh:mm:ss");

System.out.println(sd.format(dt));


**** CALENDAR CLASS will be used to get the date, time , month details using this date class in java

Calendar cal=Calendar.getInstance();

SimpleDateFormat sdt=new SimpleDateFormat("M/dd/yyyy hh:mm:ss");

System.out.println(sdt.format(cal.getTime()));

System.out.println(cal.get(Calendar.DAY_OF_MONTH));

System.out.println(cal.get(Calendar.WEEK_OF_MONTH));

System.out.println(cal.get(Calendar.YEAR));

***** CONSTRUCTOR 

 Constructor will not return any value..it is just like method but not retun any value

 Code from constructor will be executed automatically when constructor object is created.

 Name of the constructor should be always class name only when you creating constructor in class

 Implicit constructor will be called by java when no constuctor OR parameterised constructor defined and instanciated in class

 Constructor defined code, vairables and statements will be resued in clss when object of constructor is created 

 Constructors are 2 types - 

 1 default constructor OR non-parameterized constructor

 2 parameterised constructor with parameters [this will execute when we pass parameters while creating an object of constructor]

 Parameterzied constroctors will execute and ignore default constructor when user passed parameters. 

public class ConstructorDemo {


//Creating constructor without any return type

public ConstructorDemo()

{

int a =100;

System.out.println("I am in the default constructor method stmt");

System.out.println("Value of from default constructor is " +a);

}

//Creating method with return type

public void getData()

{

System.out.println("I am in generic method statement");

}

public ConstructorDemo(int a, int b)

{

System.out.println("I am in the parameterised constructor");

}


public static void main(String[] args) {


ConstructorDemo cd=new ConstructorDemo(); //Instantiating non parameterized/default costructor

ConstructorDemo cd1=new ConstructorDemo(5,6);//Instantiating parameterized/user created costructor

}


//PARAMETERISED CONSTRUCTOR (default one)


}


**** SUPER KEYWORD-

this super keyword will be used to refer the variables from the parent class

When the same same method or same variables declared in child and parents class

When we use super constructor in child class-It should be in the first line of child class

SYNTAX- super();  //super keyword with constructors

SYNTAX- super.name;  //super keyword with variables

SYNTAX- super();  //super keyword with methods



 static String name = "Steven Academy";

public void engine() {

super();

System.out.println("new Engine");

System.out.println(name); //this will refer to the local child class declared variable and print 

System.out.println(super.name); //Super keyword will refer to parent class and refers from the parent class

super.getData(); // this method will call from parent class

}



***** THIS KEYWORD

If same name of local and global variable is used in class and if we need to use the global varaible value- then java allows to use 

THIS.variable name which will refer to the global level declared variable.

this KEYWORD will refers/ties to the class level objects/global level variables

String city = "Delhi"; Global/class level variable

String city ="Chennai" Local method level variable

System.out.println(city); //statement output will be Chennai

System.out.println(this.city);//statement output will be Delhi


*****STATIC KEYWORD

//static keyword will allows to share this keyword across class as class variables and it can be updated by other methods

//static will save memory

//static method will be uses/accepts only static variables

//static methods can be called in class without creating oblects- SYNTAX- className.staticMethodName

//Static block is which can be defined with all static variables, so this block created variables can be used in all static methods.

EG: static String city='Hyd';

public static void getCity() 

{

System.out.println(state); //this will thorow error to make if non static address variable

}

**** FINAL KEYWORD

IF class name as final, then we can not extend the class 

If the variable declared as final variable -then we can not change the variable value

If the method is declared as final method, we can not override the method again.

EG: final void finalMethod() //this final method can not be override in other child classes due to final KEYWORD

{

final int i1=90; //this i1 variable value can not be changed as final keyword used before the variable declaraton.

System.out.println(i1);

}

******* PACKAGES- TYPES of Packages:

Package is set of classes and interfaces

1] java.lang -default java inbuilt package come from compiler

2] java.util - this package have collections, classes & interfaces

3] java.io - file reading and file output 

user defined package- will list on top of the class 


Class A can use Class B directly if both classes are in the same package.

If class A is in package 1 and you want to use Class a is in package2, then we need to import the class from package1. 

SYNTAX- import.package.classname


**** ACCESS MODIFIERS/ SPCIFIERS in JAVA:

1 Default-If not mentioned for methods/variables, then java will treat default modifier and 

allows everywhere in that package alone:

2 public -If method/variables eclared as public- they can access in anywhere in same/other package

3 private -If method/variables eclared as private- they can't access outside of the class

4 protected -If method/variables eclared as protected those will be accessed in all the classes of same package.

then only child classes which are inherited are able to use those methods/variable.

DEFAULT + other packages-child class which are inherited using extends keyword.


**** EXCEPTIONS in JAVA [TRY ,CATCH, FINALLY blocks]

We use Try-Catch blocks to handle java exveptions and see those error messages

One TRY can be followed by multiple catch blocks in script

CATCH should be an immediate Try block.

Exception is the parent class used for all kind of exceptions in Catch block:

FINALLY block will be execute block of code-when execution fails in midle or PASS, then this block will be executed  always, Finally should have atleast 1 try block


public static void main(String[] args){

int a =8;

int b=0;

try{

int k=b/a;

System.out.println(k);

}

Catch(exception e){

System.out.println(e);

}

Catch(indexOutOfBoundsException ets){

System.out.println(ets);

}

Catch(ArithmeticException et){

System.out.println(et);

}

finally{

System.out.println("this is finally block code");

//to delete cookies, close browser cam be used in finally block;

}


*****ARRAYLIST INTERFACE

//ArrayList has dynamic size to add records where Array have fixed size

//ArraList class have multiple methods to add,remove records and print records based on index or text -contains methods etc

//ArrayList, LinkedList, Vector will accept duplicate values

//You can access, insert,remove any value in any index using Array List methods below


ArrayList<String> ar=new ArrayList<String>();

ar.add("venkat");

ar.add("java");

ar.add("testing");

ar.add("testing1");

System.out.println(ar);

ar.add(0, "Rajkumar");//to add reord to Array List

System.out.println(ar);

ar.remove(1); //to remove record from Array List

System.out.println("ArrayList output is " + ar);

System.out.println("ArrayList value at index 0 position is " + ar.get(0));

System.out.println("ArrayList output based on contains method is " + ar.contains("testing")); //contains method returns true or flase

System.out.println("ArrayList output based on value is " + ar.indexOf("testing"));

System.out.println("ArrayList is empty or not? is " + ar.isEmpty());

System.out.println("Size of ArrayList is " + ar.size());

System.out.println(ar.contains("testing"));


}


******HASH SET INTERFACE:

// HashSet treeSet, LinkedHashSet implements SET Interface 

//These Set will not accept duplicate values, where list will accept duplicate values

//There is no guarantee where elements are added in sequence order-they will store randomly.

public static void main(String[] args) {

HashSet<String> hs=new HashSet<String>();

hs.add("Venkatesh");

hs.add("UK");

hs.add("USA");

hs.add("USA2");

hs.add("USA3");

hs.add("USA4");

hs.add("India");

System.out.println(hs);

hs.add("India");//this duplicate value will just ignored and will not add to hashList

System.out.println(hs);

System.out.println(hs.remove("India"));

System.out.println(hs.isEmpty());

System.out.println(hs.size());

System.out.println(hs);

System.out.println("========================");


Iterator<String> it=hs.iterator();

//System.out.println(it.next()); //This stmt will execute the next record from the HashSet records.

while(it.hasNext())

{

System.out.println(it.next());

}

}


*********JAVA STREAMS ver8 Compatible:

=====================================================================================================================

JAVA STREAMS avaialble from Java version 8 onwards to optimize the code efficently to perform aggregate opertaions over SETS/LIST/ARRAY LISTS

Stream will perform action parallellay using Lambda Expression(new arrow operator "->")

Strems will not change the data source; 

We can create a stream API directly and apply filter conditon, terminal operation; without converting from list to Stream 

Stream.of("Adam","Anan","Ankit","Keshav","Ram","Raj")

If action is more than one line- then we should write code in {}

forEach- to get item based on for each condition;

limit(1)- this will limit results to single;

MAP method--> to modify results in uppercase, lowercase for filtered results.


For SORTED output results we will use ArrayList, streams to arraylist conversion -then print required index 

Array to ArraList conversion [ Arrays.asList()]

sorted method - to get results in sort ASC order

Match/anyMatch method-to find matched records 

Collect method- to collect results and covert into List 

(.collect(Collectors.toList()); //to print required sorted/limited/required output only

DISTINCT method - to filter records which are unique ones


WEBTABLE- SORTING- 

1click sort,

2capture all webelements into Original List 

3grab text of webelements in to new list 

4apply sort from the result in sorted list. 

5compare original and sorted list 


Scan the column/attribute using getText X and print X,

WEBTABLE-PAGINATION Handling:(when multiple page exist)


STEPS TO WORK WITH JAVA STREAMS:

1.Create a java stream 

assign/Convert ArryList/set to Java Streams 

with filter(condition);

Lamda Expression filter(parameter -> action)(s->s,startsWith("A"));


2.Perform Intermediate stream operation (filtered stream) [filtered data]

Intermediate streal life will be based on final stream(termination operation)

Data type should be as "Long" 


3.Perform Termination stream operation [action on filtered data]


********* WEB PAGE FILTER RESULTS VALIDATION USING JAVA STREAMS

public class filter {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.get("https://rahulshettyacademy.com/greenkart/#/offers");

        driver.findElement(By.id("search-field")).sendKeys("Rice");

        List<WebElement> veggies=driver.findElements(By.xpath("//tr/td[1]"));

        //1 results

       List<WebElement> filteredList= veggies.stream().filter(veggie->veggie.getText().contains("Rice")).

        collect(Collectors.toList());

       //1 result

       Assert.assertEquals(veggies.size(), filteredList.size());

}

}

=====================================================================================================================



******HASHMAP EXAMPLE:

public class HashMapExample {


public static void main(String[] args) {

// TODO Auto-generated method stub


HashMap<Integer, String> hm=new HashMap<Integer, String>();

hm.put(0, "Hello");

hm.put(1, "Venkatesh");

hm.put(2, "Java");

hm.put(3, "Morning");

System.out.println(hm);

System.out.println(hm.get(2));

//hm.remove(3);

System.out.println(hm);

//Convert Hash Table to Set collections and Print those key-pair values;

Set sn=hm.entrySet();

Iterator it=sn.iterator();

while(it.hasNext())

{

System.out.println(it.next());

Map.Entry mp=(Map.Entry)it.next();

System.out.println(mp.getKey());

System.out.println(mp.getValue());

}

}


*****HASHTABLE EXAMPLE

DIFFERENCE BETWEEN HASHMAP and HASHTABLE

Hashmap -not have synchronization, multiple prog can access at a time, not synchronized

Hashmap allows null values, 

Hashmap.put(3,"");

Hashmap.put(3,"null");

Hashmap values can be iterated using iterator interface 


Hashtable - has Synchronization, multiple prog can not access at a time, one by one access 

Hashtable not allows null values 

Hashtable cannot support iterator interface.. need other enumerator



===========================EXAMPLE CODES==================================

public class Interview {

//FIND MINIMUM VALUE FROM THE GIVEN MULTI DIM ARRAY

public static void main(String[] args) {

// TODO Auto-generated method stub

int abc[][]= {{1,2,3},{4,5,6},{6,7,8}};

int min=abc[0][0];

for(int i=0; i<2; i++) 

{


for(int j=0; j<3; j++)

{

if(abc[i][j]<min)

{

min=(abc[i][j]);

}

}

}

System.out.println("Minimum value from the given array is " + min);

}


}



*/



public static void main(String[] args) {

int myInt = 10;

String text = "Hello";

String blank = " ";

String name = "Venkatesham";

double myDouble = 9.59;

System.out.println("My Number is "+ myDouble + ".");

String greeting = text + blank + name;

System.out.println(greeting);

System.out.println(text);

System.out.println(myInt);


//STRINGS and STRING METHODS

/*String st ="JavaTraining";

System.out.println(st.charAt(3));

System.out.println(st.indexOf("T"));

System.out.println(st.substring(4));

System.out.println(st.substring(4, 9));

System.out.println(st.concat("Venkat is learning"));

System.out.println(st.length());

System.out.println(st.toUpperCase());

System.out.println(st.toLowerCase());

String arr[]=st.split("T");

System.out.println(arr[0]);

System.out.println(arr[1]);

*/

//Print the STRING IN REVERSE -POLYNDRUM 

String st1 = "MADAM";

String st0 = "" ;

//FOR LOOP 

for(int i=st1.length()-1; i>=0; i--)

{

st0 = st0 + st1.charAt(i);

}

System.out.println(st1);

System.out.println(st0);

if(st1==st0)

System.out.println("This is polyndrum");

else

{

System.out.println("This is not a Polyndrum");

}

for(int j=0; j<=10; j=j+2)

{

if(j==8)

System.out.println("8 is displayed");

else

System.out.println("it is not found");

}

//WHILE LOOP

int k=0;

while(k<10)

{

System.out.println("while loop value now is "+ k);//this will print value from 0 to 10 incremental value

k++; //this condition will terminate the loop when it becomes false

}


int m=10;

while(m<0)

{

System.out.println("while loop value now is "+ m); //this will print from 10 to 1-decremental value

m--; //this condition will terminate the loop when it becomes false

}


//DO WHILE LOOP

int n=10;

do {

System.out.println("DO WHILE LOOP value is " + n);

n++;

}

while(n<=30); //Execution will be terminated once n value reaches to 30 as per condition


//NESTED FOR LOOP with Outer and Inner for loops

for(int x=1; x<=3; x++) //Outer For loop will execute 3 times

{

for(int y=1;y<=4;y++) //Inner for loop will execute 4 times

{

System.out.println("this line is from INNER loop");

}

System.out.println("this is for OUTER loop value");

}

//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output

int r=1;

for(int p=0; p<4; p++) //Outer For loop will execute 3 times

{

for(int q=1;q<=4-p;q++) //Inner for loop will execute 4 times

{

System.out.print(r);

System.out.print("\t"); //this is used to add space after the output value

r++;

}

System.out.println("");

}

System.out.println("Pyramid model printed Descending model");

//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output

int c1=1;

for(int a1=1; a1<5; a1++) //Outer For loop will execute 3 times

{

for(int b1=1;b1<=a1;b1++) //Inner for loop will execute 4 times

{

System.out.print(c1);

System.out.print("\t"); //this is used to add space after the output value

c1++;

}

System.out.println("");

}

System.out.println("Pyramid model printed Ascending model");

//NESTED FOR LOOP with Outer and Inner for loops to PRINT PYRAMID model output

for(int a2=1; a2<5; a2++) //Outer For loop will execute 3 times

{

for(int b2=1;b2<=a2;b2++) //Inner for loop will execute 4 times

{

System.out.print(b2);

System.out.print("\t"); //this is used to add space after the output value

}

System.out.println("");

}

System.out.println("Pyramid model printed Ascending model");

}




}


/* ******OOPS Interview questions

What are the core concepts of OOPS?

OOPS core concepts are;

Abstraction

Encapsulation

Polymorphism

Inheritance

Composition

Association

Aggregation

What is Abstraction?

Abstraction is an OOPS concept to construct the structure of the real world objects. During this construction only the general states and behaviors are taken and more specific states and behaviors are left aside for the implementers.


What is Encapsulation?

Encapsulation is an OOPS concept to create and define the permissions and restrictions of an object and its member variables and methods. A very simple example to explain the concept is to make the member variables of a class private and providing public getter and setter methods. Java provides four types of access level modifiers: public, protected, no modifier and private.


What is the difference between Abstraction and Encapsulation?

�Program to interfaces, not implementations� is the principle for Abstraction and �Encapsulate what varies� is the OO principle for Encapsulation.

Abstraction provides a general structure of a class and leaves the details for the implementers. Encapsulation is to create and define the permissions and restrictions of an object and its member variables and methods.

Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using four types of access level modifiers: public, protected, no modifier and private.

What is Polymorphism?

Polymorphism is the occurrence of something in various forms. Java supports various forms of polymorphism like polymorphic reference variables, polymorphic method, polymorphic return types and polymorphic argument types.


What is Inheritance?

A subclass can inherit the states and behaviors of it�s super class is known as inheritance.


What is multiple inheritance?

A child class inheriting states and behaviors from multiple parent classes is known as multiple inheritance.


What is the diamond problem in inheritance?

In case of multiple inheritance, suppose class A has two subclasses B and C, and a class D has two super classes B and C.If a method present in A is overridden by both B and C but not by D then from which class D will inherit that method B or C? This problem is known as diamond problem.


Why Java does not support multiple inheritance?

Java was designed to be a simple language and multiple inheritance introduces complexities like diamond problem. Inheriting states or behaviors from two different type of classes is a case which in reality very rare and it can be achieved easily through an object association.


What is Static Binding and Dynamic Binding?

Static or early binding is resolved at compile time. Method overloading is an example of static binding.


Dynamic or late or virtual binding is resolved at run time. Method overriding is an example of dynamic binding.


What is a Class?

A class is the specification or template of an object.


What is an Object?

Object is instance of class.


What is Runtime Polymorphism?

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.


In this process, an overridden method is called through the reference variable of a super class. The 


 What is the difference between abstraction and encapsulation?

Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.




 What is abstract class?

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.


 Can there be any abstract method without abstract class?

No, if there is any abstract method in a class, that class must be abstract.


Can you use abstract and final both with a method?

No, because abstract method needs to be overridden whereas you can't override final method.


Is it possible to instantiate the abstract class?

No, abstract class can never be instantiated.


What is interface?


Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance.




 Can you declare an interface method static?


No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.


 Can an Interface be final?

No, because its implementation is provided by another class.


 What is marker interface?

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.


 What is difference between abstract class and interface?

Abstract class Interface

1)An abstract class can have method body (non-abstract methods). Interface have only abstract methods.

2)An abstract class can have instance variables. An interface cannot have instance variables.

3)An abstract class can have constructor. Interface cannot have constructor.

4)An abstract class can have static methods. Interface cannot have static methods.

5)You can extends one abstract class. You can implement multiple interfaces.

 Can we define private and protected modifiers for variables in interfaces?

No, they are implicitly public.


 When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.


 */