Saturday, October 31, 2020

 Q)How to do Scroll Up and Down in Selenium add Re-usable method  and Add In Framework .

package com.seleniumpractice;


import java.util.concurrent.TimeUnit;



import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;


public class ScrollUpandDown {


public static void main(String[] args) throws InterruptedException {


System.setProperty("webdriver.chrome.driver","D:\\driver1016\\chromedriver.exe\\");

WebDriver driver=new ChromeDriver();

driver.get("https://www.youtube.com/");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

//JavascriptExecutor js= (JavascriptExecutor)driver;

//js.executeScript("scroll(0,1500)");

//Thread.sleep(1000);

//js.executeScript("scroll(-1500,0)");

HelperTest.scrollWindow(driver,"scroll(0,1500)");

Thread.sleep(1000);

HelperTest.scrollWindow(driver,"scroll(-1500,0)");


}


}

=========================================================================
package com.seleniumpractice;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class HelperTest {
public static WebDriver driver;
public static String driverpath="D:\\SeleniumJar_08_28_2020\\chromedriver_win32 (4)\\chromedriver.exe\\";
public static String url="file:///D:/Ingenious_TechHub_Teaching/Ingenious_Selenium/Htmldoc/dob.html";

/**
* This Method is used to launch App
*/
public static void launchApp(){
System.setProperty("webdriver.chrome.driver", driverpath);
driver=new ChromeDriver();
driver.get(url);
maxmizeBrowser();
}

/**
* This Method is used to max browser
*/
public static void maxmizeBrowser(){
driver.manage().window().maximize();
}

/**
* This Method is used to close borwser
*/
public static void closeBrowser(){
driver.close();
}

/**
* This Method is used to compare String
* @param actual is String Type
* @param Expected is String Type
*/
public static void compareString(String actual,String expected){
if(actual.equals(expected)){
System.out.println("************ Test Cased is passed ***********");
}

else{
System.out.println("************ Test Cased is Failed ***********");
}

}

public static WebElement explicitlyWait(WebDriver driver,int a,String str){
WebDriverWait wait=new WebDriverWait(driver,a);
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(str)));

}


public static WebElement fluentWait(WebDriver driver,int a,int b,String strxpath){
Wait<WebDriver> wait=new FluentWait<>(driver)
.withTimeout(a, TimeUnit.SECONDS)
.pollingEvery(b, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(strxpath)));

}

public static WebElement getfirstOptions(WebElement ele){
Select sel=new Select(ele);
WebElement getFirstOption=sel.getFirstSelectedOption();
String strgetFirstOption= getFirstOption.getText();
System.out.println("strgetFirstOption..."+ strgetFirstOption);
return getFirstOption;




}


public static WebElement listofDropdown(WebElement ele){
Select sel=new Select(ele);
List<WebElement> listofDropdown=sel.getOptions();
for(int i=0;i<listofDropdown.size();i++){
String listofDrop=listofDropdown.get(i).getText();
System.out.println("listofDrop..." + listofDrop);
}
return ele;

}


public static WebElement selctByIndexEle(WebElement ele1,int index){
Select selEle=new Select(ele1);
selEle.selectByIndex(index);
return ele1;

}

public static WebElement selectByValueEle(WebElement ele2,String value){
Select selEle=new Select(ele2);
selEle.selectByValue(value);
return ele2;
}

public static WebElement selectByTextEle(WebElement ele3,String text){
Select selEle=new Select(ele3);
selEle.selectByVisibleText(text);
return ele3;
}

public static List<WebElement> selectBosttrapDropDown(List<WebElement> list,String xpath,String selValue){
list=driver.findElements(By.xpath(xpath));
for(int i=0;i<list.size();i++){
String str=list.get(i).getText();
if(str.equalsIgnoreCase(str)){
list.get(i).click();
break;
}

}
return list;


}


public static WebElement movetoElement(WebDriver driver,WebElement ele){
Actions act=new Actions(driver);
act.moveToElement(ele).perform();
return ele;


}

public static void ClickWithActions(WebDriver driver,WebElement ele){

Actions act=new Actions(driver);
act.moveToElement(ele).click().perform();


}

public static void dragAndDrop(WebDriver driver,WebElement drag,WebElement drop){
Actions act=new Actions(driver);
act.dragAndDrop(drag, drop).build().perform();


}

public static void movetoOffSet(WebDriver driver,WebElement ele,int xoffSet,int yoffSet){

Actions act=new Actions(driver);
act.moveToElement(ele, xoffSet,yoffSet).perform();


}

public static String alertGetText(WebDriver driver){
Alert alt=driver.switchTo().alert();
String getStr=alt.getText();
System.out.println(getStr);
return getStr;
}

public static void alertAccept(WebDriver driver){
Alert alt=driver.switchTo().alert();
alt.accept();
}

public static void alerDismiss(WebDriver driver){
Alert alt=driver.switchTo().alert();
alt.dismiss();
}

public static String gettilteofPage(WebDriver driver){
String str=driver.getTitle();
System.out.println(str);
return str;
}

public static String getParentWindow(WebDriver driver){
return driver.getWindowHandle();
}

public static void getChildWindow(WebDriver driver){
Set<String> set=driver.getWindowHandles();
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
String childWindow=itr.next();
String parentdow=getParentWindow(driver);
if(!parentdow.equals(childWindow)){
driver.switchTo().window(childWindow);
}
}

}
public static void switchToWindow(WebDriver driver,String window){
driver.switchTo().window(window);
}

public static void scrollWindow(WebDriver driver,String str){
JavascriptExecutor js= (JavascriptExecutor)driver;
js.executeScript(str);
}


}


Thursday, October 29, 2020

 Q)How to handle Multiple Window in Selenium and write code to make Re-usable  method  and Add in framework

package com.seleniumpractice;


import java.util.Iterator;

import java.util.Set;

import java.util.concurrent.TimeUnit;


import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;


public class CityBankMutipleWindow extends HelperTest{


public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver","D:\\driver1016\\chromedriver.exe");

WebDriver driver=new ChromeDriver();

driver.get("https://www.online.citibank.co.in/");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

//String parentWindow= driver.getWindowHandle();

String parentWindow= HelperTest.getParentWindow(driver);


String actualparentWindowtite=driver.getTitle();

System.out.println("actualparentWindowtite.." + actualparentWindowtite);


String expectedparentWindowtite="Citi India - Credit Cards, Personal & Home Loans, Investment, Wealth Management & Banking";

HelperTest.compareString(actualparentWindowtite, expectedparentWindowtite);


driver.findElement(By.xpath("//a[@id='loginId']/img")).click();


/*

Set<String> set= driver.getWindowHandles();

Iterator<String> itr=set.iterator();


while(itr.hasNext()){

String childWindow=itr.next();

if(!(parentWindow).equals(childWindow)){

driver.switchTo().window(childWindow);

//String actualchildwinowTite=driver.getTitle();

//System.out.println("actualchildwinowtite....");

//String expectedchidwindowTitle="citibank";

//System.out.println("expectedchidwindow"+expectedchidwindowTitle);

*/

HelperTest.getChildWindow(driver);

String actualStr=driver.findElement(By.xpath("//h1[contains(text(),'Welcome to Citibank Online')]")).getText();

System.out.println("actualStr..." + actualStr);


String expctedStr="Welcome to Citibank Online";

System.out.println("expctedStr..."+ expctedStr);

HelperTest.compareString(actualStr, expctedStr);

//driver.switchTo().window(parentWindow);

HelperTest.switchToWindow(driver, parentWindow);

driver.quit();


}

}

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

package com.seleniumpractice;


import java.util.Iterator;

import java.util.List;

import java.util.Set;

import java.util.concurrent.TimeUnit;


import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.Wait;

import org.openqa.selenium.support.ui.WebDriverWait;


public class HelperTest {

public static WebDriver driver;

public static String driverpath="D:\\SeleniumJar_08_28_2020\\chromedriver_win32 (4)\\chromedriver.exe\\";

public static String url="file:///D:/Ingenious_TechHub_Teaching/Ingenious_Selenium/Htmldoc/dob.html";


/**

* This Method is used to launch App

*/

public static void launchApp(){

System.setProperty("webdriver.chrome.driver", driverpath);

driver=new ChromeDriver();

driver.get(url);

maxmizeBrowser();

}


/**

* This Method is used to max browser

*/

public static void maxmizeBrowser(){

driver.manage().window().maximize();

}


/**

* This Method is used to close borwser

*/

public static void closeBrowser(){

driver.close();

}


/**

* This Method is used to compare String

* @param actual is String Type

* @param Expected is String Type

*/

public static void compareString(String actual,String expected){

if(actual.equals(expected)){

System.out.println("************ Test Cased is passed ***********");

}


else{

System.out.println("************ Test Cased is Failed ***********");

}


}


public static WebElement explicitlyWait(WebDriver driver,int a,String str){

WebDriverWait wait=new WebDriverWait(driver,a);

return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(str)));


}



public static WebElement fluentWait(WebDriver driver,int a,int b,String strxpath){

Wait<WebDriver> wait=new FluentWait<>(driver)

.withTimeout(a, TimeUnit.SECONDS)

.pollingEvery(b, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(strxpath)));


}


public static WebElement getfirstOptions(WebElement ele){

Select sel=new Select(ele);

WebElement getFirstOption=sel.getFirstSelectedOption();

String strgetFirstOption= getFirstOption.getText();

System.out.println("strgetFirstOption..."+ strgetFirstOption);

return getFirstOption;





}



public static WebElement listofDropdown(WebElement ele){

Select sel=new Select(ele);

List<WebElement> listofDropdown=sel.getOptions();

for(int i=0;i<listofDropdown.size();i++){

String listofDrop=listofDropdown.get(i).getText();

System.out.println("listofDrop..." + listofDrop);

}

return ele;


}



public static WebElement selctByIndexEle(WebElement ele1,int index){

Select selEle=new Select(ele1);

selEle.selectByIndex(index);

return ele1;


}


public static WebElement selectByValueEle(WebElement ele2,String value){

Select selEle=new Select(ele2);

selEle.selectByValue(value);

return ele2;

}


public static WebElement selectByTextEle(WebElement ele3,String text){

Select selEle=new Select(ele3);

selEle.selectByVisibleText(text);

return ele3;

}


public static List<WebElement> selectBosttrapDropDown(List<WebElement> list,String xpath,String selValue){

list=driver.findElements(By.xpath(xpath));

for(int i=0;i<list.size();i++){

String str=list.get(i).getText();

if(str.equalsIgnoreCase(str)){

list.get(i).click();

break;

}


}

return list;



}



public static WebElement movetoElement(WebDriver driver,WebElement ele){

Actions act=new Actions(driver);

act.moveToElement(ele).perform();

return ele;



}


public static void ClickWithActions(WebDriver driver,WebElement ele){


Actions act=new Actions(driver);

act.moveToElement(ele).click().perform();



}


public static void dragAndDrop(WebDriver driver,WebElement drag,WebElement drop){

Actions act=new Actions(driver);

act.dragAndDrop(drag, drop).build().perform();



}


public static void movetoOffSet(WebDriver driver,WebElement ele,int xoffSet,int yoffSet){


Actions act=new Actions(driver);

act.moveToElement(ele, xoffSet,yoffSet).perform();



}


public static String alertGetText(WebDriver driver){

Alert alt=driver.switchTo().alert();

String getStr=alt.getText();

System.out.println(getStr);

return getStr;

}


public static void alertAccept(WebDriver driver){

Alert alt=driver.switchTo().alert();

alt.accept();

}


public static void alerDismiss(WebDriver driver){

Alert alt=driver.switchTo().alert();

alt.dismiss();

}


public static String gettilteofPage(WebDriver driver){

String str=driver.getTitle();

System.out.println(str);

return str;

}


public static String getParentWindow(WebDriver driver){

return driver.getWindowHandle();

}


public static void getChildWindow(WebDriver driver){

Set<String> set=driver.getWindowHandles();

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

String childWindow=itr.next();

String parentdow=getParentWindow(driver);

if(!parentdow.equals(childWindow)){

driver.switchTo().window(childWindow);

}

}


}

public static void switchToWindow(WebDriver driver,String window){

driver.switchTo().window(window);

}




}



Saturday, October 17, 2020

How to Handle Alert POP'up in Selenium and Make re-usable method in your framework

 package com.seleniumpractice;


import java.util.concurrent.TimeUnit;


import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;


public class AlertTest extends HelperTest {


public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver","D:\\driver1016\\chromedriver.exe\\");

    WebDriver driver=new ChromeDriver();

    driver.get("https://artoftesting.com/sampleSiteForSelenium");

    driver.manage().window().maximize();

    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

    Actions act=new Actions(driver);

   WebElement ele= driver.findElement(By.id("dblClkBtn"));

   act.doubleClick(ele).perform();

   //Thread.sleep(2000);

   //Alert alt=driver.switchTo().alert();

   //String strActual=alt.getText();

   //System.out.println("strActual" + strActual);

   //Thread.sleep(2000);

   String strActual=HelperTest.alertGetText(driver);

   

   String strexpected="Hi! Art Of Testing, Here!";

   System.out.println("expected..." + strexpected);

   HelperTest.compareString(strActual, strexpected);

   HelperTest.alertAccept(driver);

   



}


}

=========================================================================
package com.seleniumpractice;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class HelperTest {
public static WebDriver driver;
public static String driverpath="D:\\SeleniumJar_08_28_2020\\chromedriver_win32 (4)\\chromedriver.exe\\";
public static String url="file:///D:/Ingenious_TechHub_Teaching/Ingenious_Selenium/Htmldoc/dob.html";

/**
* This Method is used to launch App
*/
public static void launchApp(){
System.setProperty("webdriver.chrome.driver", driverpath);
driver=new ChromeDriver();
driver.get(url);
maxmizeBrowser();
}

/**
* This Method is used to max browser
*/
public static void maxmizeBrowser(){
driver.manage().window().maximize();
}

/**
* This Method is used to close borwser
*/
public static void closeBrowser(){
driver.close();
}

/**
* This Method is used to compare String
* @param actual is String Type
* @param Expected is String Type
*/
public static void compareString(String actual,String expected){
if(actual.equals(expected)){
System.out.println("************ Test Cased is passed ***********");
}

else{
System.out.println("************ Test Cased is Failed ***********");
}

}

public static WebElement explicitlyWait(WebDriver driver,int a,String str){
WebDriverWait wait=new WebDriverWait(driver,a);
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(str)));

}


public static WebElement fluentWait(WebDriver driver,int a,int b,String strxpath){
Wait<WebDriver> wait=new FluentWait<>(driver)
.withTimeout(a, TimeUnit.SECONDS)
.pollingEvery(b, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(strxpath)));

}

public static WebElement getfirstOptions(WebElement ele){
Select sel=new Select(ele);
WebElement getFirstOption=sel.getFirstSelectedOption();
String strgetFirstOption= getFirstOption.getText();
System.out.println("strgetFirstOption..."+ strgetFirstOption);
return getFirstOption;




}


public static WebElement listofDropdown(WebElement ele){
Select sel=new Select(ele);
List<WebElement> listofDropdown=sel.getOptions();
for(int i=0;i<listofDropdown.size();i++){
String listofDrop=listofDropdown.get(i).getText();
System.out.println("listofDrop..." + listofDrop);
}
return ele;

}


public static WebElement selctByIndexEle(WebElement ele1,int index){
Select selEle=new Select(ele1);
selEle.selectByIndex(index);
return ele1;

}

public static WebElement selectByValueEle(WebElement ele2,String value){
Select selEle=new Select(ele2);
selEle.selectByValue(value);
return ele2;
}

public static WebElement selectByTextEle(WebElement ele3,String text){
Select selEle=new Select(ele3);
selEle.selectByVisibleText(text);
return ele3;
}

public static List<WebElement> selectBosttrapDropDown(List<WebElement> list,String xpath,String selValue){
list=driver.findElements(By.xpath(xpath));
for(int i=0;i<list.size();i++){
String str=list.get(i).getText();
if(str.equalsIgnoreCase(str)){
list.get(i).click();
break;
}

}
return list;


}


public static WebElement movetoElement(WebDriver driver,WebElement ele){
Actions act=new Actions(driver);
act.moveToElement(ele).perform();
return ele;


}

public static void ClickWithActions(WebDriver driver,WebElement ele){

Actions act=new Actions(driver);
act.moveToElement(ele).click().perform();


}

public static void dragAndDrop(WebDriver driver,WebElement drag,WebElement drop){
Actions act=new Actions(driver);
act.dragAndDrop(drag, drop).build().perform();


}

public static void movetoOffSet(WebDriver driver,WebElement ele,int xoffSet,int yoffSet){

Actions act=new Actions(driver);
act.moveToElement(ele, xoffSet,yoffSet).perform();


}
public static String alertGetText(WebDriver driver){
Alert alt=driver.switchTo().alert();
String getStr=alt.getText();
System.out.println(getStr);
return getStr;
}
public static void alertAccept(WebDriver driver){
Alert alt=driver.switchTo().alert();
alt.accept();
}
public static void alerDismiss(WebDriver driver){
Alert alt=driver.switchTo().alert();
alt.dismiss();
}




}

Friday, October 16, 2020

How to handle Drag and Drop in Selenium and Make Re-usable method add in your framework

 Q)How to handle  Drag and Drop in Selenium

package com.seleniumpractice;


import java.util.List;

import java.util.concurrent.TimeUnit;


import org.openqa.selenium.By;

import org.openqa.selenium.NoSuchElementException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.Wait;

import org.openqa.selenium.support.ui.WebDriverWait;


public class HelperTest {

public static WebDriver driver;

public static String driverpath="D:\\SeleniumJar_08_28_2020\\chromedriver_win32 (4)\\chromedriver.exe\\";

public static String url="file:///D:/Ingenious_TechHub_Teaching/Ingenious_Selenium/Htmldoc/dob.html";

/**

     * This Method is used to launch App

     * 

     */

public static void launchApp(){

System.setProperty("webdriver.chrome.driver", driverpath);

driver=new ChromeDriver();

driver.get(url);

maxmizeBrowser();

}

/**

     * This Method is used to max browser

     * 

     */

public static void maxmizeBrowser(){

driver.manage().window().maximize();

}

/**

     * This Method is used to close borwser

     * 

     */

public static void closeBrowser(){

driver.close();

}

/**

     * This Method is used to compare String

     * @param actual is String Type

     * @param Expected is String Type

     */

public static void compareString(String actual,String expected){

if(actual.equals(expected)){

System.out.println("************ Test Cased is passed ***********");

}

else{

System.out.println("************ Test Cased is Failed ***********");

}

}

public static WebElement explicitlyWait(WebDriver driver,int a,String str){

WebDriverWait wait=new WebDriverWait(driver,a);

return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(str)));

}

public static WebElement fluentWait(WebDriver driver,int a,int b,String strxpath){

Wait<WebDriver> wait=new FluentWait<>(driver)

.withTimeout(a, TimeUnit.SECONDS)

.pollingEvery(b, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(strxpath)));

}

public static WebElement getfirstOptions(WebElement ele){

Select sel=new Select(ele);

WebElement getFirstOption=sel.getFirstSelectedOption();

String strgetFirstOption= getFirstOption.getText();

System.out.println("strgetFirstOption..."+ strgetFirstOption);

return getFirstOption;

}

public static WebElement listofDropdown(WebElement ele){

Select sel=new Select(ele);

List<WebElement> listofDropdown=sel.getOptions();

for(int i=0;i<listofDropdown.size();i++){

String listofDrop=listofDropdown.get(i).getText();

System.out.println("listofDrop..." + listofDrop);

}

return ele;

}

public static WebElement selctByIndexEle(WebElement ele1,int index){

Select selEle=new Select(ele1);

selEle.selectByIndex(index);

return ele1;

}

public static WebElement selectByValueEle(WebElement ele2,String value){

Select selEle=new Select(ele2);

selEle.selectByValue(value);

return ele2;

}

public static WebElement selectByTextEle(WebElement ele3,String text){

Select selEle=new Select(ele3);

selEle.selectByVisibleText(text);

return ele3;

}

public static List<WebElement> selectBosttrapDropDown(List<WebElement> list,String xpath,String selValue){

list=driver.findElements(By.xpath(xpath));

for(int i=0;i<list.size();i++){

String str=list.get(i).getText();

if(str.equalsIgnoreCase(str)){

list.get(i).click();

break;

}

}

return list;

}

public static WebElement movetoElement(WebDriver driver,WebElement ele){

Actions act=new Actions(driver);

act.moveToElement(ele).perform();

return ele;

}

public static void ClickWithActions(WebDriver driver,WebElement ele){

Actions act=new Actions(driver);

act.moveToElement(ele).click().perform();

}


public static void dragAndDrop(WebDriver driver,WebElement drag,WebElement drop){

Actions act=new Actions(driver);

act.dragAndDrop(drag, drop).build().perform();

}


public static void movetoOffSet(WebDriver driver,WebElement ele,int xoffSet,int yoffSet){

Actions act=new Actions(driver);

act.moveToElement(ele, xoffSet,yoffSet).perform();

}


}

====================================================================
package com.seleniumpractice;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropTest  extends HelperTest{

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:\\driver1016\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://jqueryui.com/resources/demos/droppable/default.html");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
WebElement dragpath=driver.findElement(By.id("draggable"));
WebElement droppath=driver.findElement(By.id("droppable"));
//Actions act=new Actions(driver);
//act.dragAndDrop(dragpath, droppath).build().perform();
HelperTest.dragAndDrop(driver,dragpath, droppath);

}

}
======================================================================
package com.seleniumpractice;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class MoveToEleoffset extends HelperTest {

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","D:\\driver1016\\chromedriver.exe\\");
    WebDriver driver=new ChromeDriver();
    driver.get("https://demoqa.com/slider/");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    WebElement ele=driver.findElement(By.id("sliderContainer"));
    HelperTest.movetoOffSet(driver, ele,50,10);
   // Actions act=new Actions(driver);
    //act.moveToElement(ele, 50,0).perform();
    ele.click();

    
    
    
    
    
    
    

}

}

Sunday, October 4, 2020

Interview Programming question for Automation Testing Engineer and java Developer

Interview Programming question for Automation Testing Engineer and java Developer 

Q) 1. Write Java Program To Check Whether Two Strings Are Anagram Or Not?

package com.javaprog;


import java.util.Arrays;


public class CheckAnagram {

/*

* “Mother In Law” and “Hitler Woman” are anagrams.

*/

static int i=0;

static int j=0;

public static void checkAnagramStr(String inputStr1,String inputStr2){

String removeSpace=inputStr1.replaceAll("\\s","");

System.out.println("removeSpace...." + removeSpace);

String lowerChar=removeSpace.toLowerCase();

System.out.println("lowerChar...." + lowerChar);

String removeSpace2=inputStr2.replaceAll("\\s","");

System.out.println("removeSpace2...." + removeSpace2);

String lowerChar2=removeSpace2.toLowerCase();

System.out.println("lowerChar2...." + lowerChar2);

if(lowerChar.length()==lowerChar2.length()){

boolean status=true;

char[] ch2=lowerChar2.toCharArray();

char[] ch1=lowerChar.toCharArray();

Arrays.sort(ch2);

Arrays.sort(ch1);

boolean retval= Arrays.equals(ch2,ch1);

System.out.println("retval.. " + retval);

if(retval){

System.out.println("Strings are Anagram");

}

else{

System.out.println("Strings are not Anagram");

}

}

}

public static void main(String[] args) {

checkAnagramStr("Mother In Law","Hitler Woman");

checkAnagramStr("keEp","peeK");


}


}

Q) 2.How To Find Duplicate Characters In A String In Java?

package com.javaprog;

import java.util.HashMap;
import java.util.Set;

public class CountDublicteChar {
public static void dublicateChar(String intputString)
{
HashMap<Character ,Integer> hm=new HashMap<Character,Integer>();
char[] ch=intputString.toCharArray();
for(char c:ch){
if(hm.containsKey(c)){
hm.put(c,hm.get(c)+1);
}
else{
hm.put(c,1);
}
}
Set<Character> setc= hm.keySet();
System.out.println("Dublicate String..." + intputString);
for(Character c1:setc){
if(hm.get(c1)>1){
System.out.println(c1+":"+hm.get(c1));
}
}
}
public static void main(String[] args) {
dublicateChar("J22eee");

}

}

Q) 3.Java program to check whether a string is a Palindrome.

package com.javaprog;

public class PalindromorNot {
public static boolean isPalindrom(String inputString){
int i=0;
int j=inputString.length()-1;
System.out.println("i.." + i);
System.out.println("j.." + j);
while(i<j){
if(inputString.charAt(i)!=inputString.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
public static void main(String[] args) {
    String str="madam";
    if(isPalindrom(str)){
    System.out.println("String is palindrom");
    }
    
    else{
    System.out.println("String is not palindrom");
    }

}

}

OR
package com.logicalprograming;

public class CheckStrIsPalimdrom {
public static void main(String[] args) {
String str = "madam";
String str1=str.toLowerCase();
    if(isPalindrome(str1)) {
        System.out.println("Palindrome");
    } else {
        System.out.println("Not a Palindrome");
    }
}
private static boolean isPalindrome(String str1) {
    // Convert String to char array
    char[] charArray = str1.toCharArray();  
    for(int i=0; i < str1.length(); i++) {
        if(charArray[i] != charArray[(str1.length()-1) - i]) {
            return false;
        }
    }
    return true;

}

}


Q) 4.How to find max and min Number in Array 
package com.javaprog;

public class MaxorMinNumberArray {
public static int maxNumber(int[] arr){
int max=0;
for(int i=0;i<arr.length;i++){
if(arr[i]>max){
max=arr[i];
}
}
return max;
}
public static int minNumbr(int[] arr){
int min=arr[0];
for(int j=0;j<arr.length;j++){
if(arr[j]<min){
min=arr[j];
}
}
return min;
}
public static void main(String[] args) {
int[] a={1,2,3,4,5};
System.out.println(maxNumber(a));
System.out.println(minNumbr(a));

}

}



Q) 5.How to find remove elements in an array?
package com.javaprog;

public class FindDublicateElementInArray {
static int count=0;
static int i;
public static void removedublicateEle(int[] a){
    
for(i=0;i<a.length;i++){
count=0;
for(int j=0;j<=i;j++){
if(a[i]==a[j]){
count++;
}}
if(count<=1){
System.out.println(a[i]);
}
}
}
public static void main(String[] args) {
removedublicateEle(new int[]{1,1,1,1,1,2,2,3,4,8,10,10,20,50,60,100,30,30});

}

}

Q) 6. WAP to remove the vowels and print constants of index ?
package com.javaprog;

import java.util.Scanner;

public class RemoveVowels {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String.....");
String inputString=sc.nextLine();
String newString=inputString.replaceAll("[AEIOUaeiou]","");
String removespace=newString.replaceAll("\\s","");
String finaloutput=removespace.toLowerCase();
System.out.println("The String withoutvowles....");
System.out.println(finaloutput);
char[] ch=finaloutput.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print((i)+"="+ch[i]+" ");
}
sc.close();

}

}

Output:-
Enter the String.....
elepaht
The String withoutvowles....
lpht
0=l 1=p 2=h 3=t 

Q.7 How to find all pairs of elements in an array whose sum is equal to given number?
package com.javaprog;

public class SumOfPair {
public static void sumofpairofArray(int[] a){
//int sum={20};
// (9, 11), (7, 13) and (8, 12)
int sum=20;
for(int i=0;i<a.length;i++){
for(int j=0;j<i;j++){
if(sum==a[i]+a[j]){
System.out.println("("+a[i]+","+ a[j]+")");
}
}
}
}
public static void main(String[] args) {
sumofpairofArray(new int[]{4, 5, 7, 11, 9, 10,10,13, 8, 12});

}

}

O/P
(9,11)
(10,10)
(13,7)
(12,8)

Q)How To Count Occurrences Of Each Character In String In Java?
package com.javaprog;

import java.util.HashMap;

public class CountNoOccurance {
public static void countNoOfOcc(String inputstr){
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
char[] ch=inputstr.toCharArray();
for(char c:ch){
if(hm.containsKey(c)){
hm.put(c,hm.get(c)+1);
}
else{
hm.put(c,1);
}
}
System.out.println(inputstr+":"+hm);
}
public static void main(String[] args) {
countNoOfOcc("Java J2EE Java JSP J2EE");

}

}



Q) 15) How to find continuous sub array whose sum is equal to given number?

package com.javaprog;
public class PairsOfElements {
public static void pairsOfEle(int[] a){
int sum=45;
for(int i=0;i<a.length;i++){
for(int j=0;j<i;j++){
for(int k=0;k<j;k++){
if(sum==a[i]+a[j]+a[k]){
System.out.println("{"+a

[i]+","+a[j]+","+a[k]+"}");
}
}
}
}
}
public static void main(String[] args) {
pairsOfEle(new int[]{12, 5, 31, 9, 21,8,20,20,5});

   }

}


O/p
{9,31,5}
{20,20,5}
{5,9,31}
{5,20,20}

Q16)How To Remove Duplicate Elements From ArrayList In Java?
package com.javaprog;

import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDublicateInArrayList {

public static void main(String[] args) {
    ArrayList<String> listwithDubicate= new ArrayList<String>();
    listwithDubicate.add("java");
    listwithDubicate.add("Selenium");
    listwithDubicate.add("BBD");
    listwithDubicate.add("API Tesing");
    listwithDubicate.add("BBD");
    listwithDubicate.add("API Tesing");
    //printing listwithDubicate
    System.out.print("ArrayList With Duplicate Elements :");
    System.out.println(listwithDubicate);
    
    //Constructing HashSet using listwithDubicate
    
    HashSet<String> set=new HashSet<String>(listwithDubicate);
    
  //Constructing listWithoutDuplicateElements using set
    ArrayList<String> listofwithoutEle=new ArrayList<String>(set);
    
    //Printing listWithoutDuplicateElements
    System.out.println("ArrayList After Removing Duplicate Elements :");
    
    System.out.println(listofwithoutEle);

}

}

Q)17 Check Whether The Given Number Is Binary Or Not?

package logicalprog;

public class CheckBinaryNumnew {
static void checkbinary(int num){
boolean isBinary=true;
int copyofnum=num;
while(copyofnum!=0){
int temp=copyofnum%10;
if(temp>1){
isBinary=false;
break;
}
else{
copyofnum=copyofnum/10;
}
}
if(isBinary){
System.out.println(num+" is a binary num");
}
else{
System.out.println(num+ "is not binary num");
}
}
public static void main(String[] args) {
checkbinary((10110101));
checkbinary((42578));


}

}

Ques-18>How to reverse String without inbuilt method?
class ReverseStringFuncationality 
{
  static String reverseString(String str){
  char[] ch=str.toCharArray();
  for(int i=ch.length-1;i>=0;i--){
  System.out.print(ch[i]);
      }
      return str;
}
 public static void main(String[] args) 
{
reverseString("mohit");
}
}

Ques-18>WAP to reverse String using inbuild method?

class StringBufferDemo 
{
public static void main(String[] args) 
{
StringBuffer bf=new StringBuffer("mohit");
bf.reverse();
System.out.println(bf);
}
}

Ques -19> WAP
String  is "hello" and  is "java".
A has a length of , and  has a length of ; the sum of their lengths is .
When sorted alphabetically/lexicographically, "hello" precedes "java"; therefore,  is not greater than  and the answer is No



package com.hackerran;

import java.util.Arrays;

public class Task3 {
public static void multipleOperation(String str1,String str2){
int A=str1.length();
int B=str2.length();
int sum=A+B;
System.out.println("sum::"+sum);
char[] ch1=str1.toCharArray();
Arrays.sort(ch1);
String strsorted1=new String(ch1);
//System.out.println("strsorted1::" + strsorted1);
char[] ch2=str2.toCharArray();
Arrays.sort(ch2);
String strsorted2=new String(ch2);
//System.out.println("strsorted2::" + strsorted2);
if(!(strsorted1.length()>strsorted2.length())){
System.out.println("Yes");
}
else{
System.out.println("No");
}

}
public static void main(String[] args) {
// TODO Auto-generated method stub
multipleOperation("hello","java");

}

}


Ques 20)Check Armstrong number program in java

package logicalprog;

public class ArmstrongNum {

/*
* 153, 9474, 54748
* 1*1*1+5*5*5+3*3*3=153
*/

public static void checkArmstrongNum(int num){
int sum=1;
int num1=0;
while(num>0){
num=num%10;
sum=sum+num*num*num;
System.out.println("sum::" +sum);
num=num/10;
System.out.println("num::" +num);
}

if(sum==num){
System.out.println("num is Armstrong::");
}
else{
System.out.println("num is not Armstrong");
}

}


public static void main(String[] args) {
checkArmstrongNum(153);


}

}

Ques 21)Write a java program to find common elements between two arrays?

package com.logicnew;

import java.util.HashSet;

public class CommonElements {
public static void findcommonEleinArray(String[] s1,String[] s2){
HashSet<String> set=new HashSet<String>();
for(int i=0;i<s1.length;i++){
for(int j=0;j<s2.length;j++){
if(s1[i].equals(s2[j])){
set.add(s1[i]);
}
}

}
System.out.println(set);
}
public static void main(String[] args) {
findcommonEleinArray(new String[]{"one","one","two","three"},new String[]{"one","two","four"});


}

}

Ques22)Q)How To Remove White Spaces From String .

package logicparctie;

public class RemoveWhiteSpace {
public static void removeWhiteSpace(String inputstr){
String removewhitespace=inputstr.replaceAll("\\s","");
System.out.println(removewhitespace);
}

public static void removespcwithoutinbutitMethod(String inputstr1){
char[] ch=inputstr1.toCharArray();
for(char c:ch){
if(!(c==' ')){
System.out.print(c);
}
}


}
public static void removewhitespace(String inputstr2){
char[] ch=inputstr2.toCharArray();
String stringwithoutSpaces="";
for(int i=0;i<ch.length;i++){
if((ch[i]!=' ') &&(ch[i]!='\t')){
stringwithoutSpaces=stringwithoutSpaces+ch[i];

}
}
System.out.print(stringwithoutSpaces);
}

public static void main(String[] args){
removeWhiteSpace("mohit kumar");
removespcwithoutinbutitMethod("mohit kumar");
removewhitespace("mohit kumar");
}

}

22) How to reverse each word of a string in java?

package logicalprog;

public class Reverseeachword {

public static void reverseEachword(String inputstr){
String[] words=inputstr.split(" ");
String reverseString="";
for(int i=0;i<words.length;i++){
String word=words[i];
String reverseword="";
for(int j=word.length()-1;j>=0;j--){
reverseword=reverseword+word.charAt(j);
}
reverseString=reverseString+reverseword+" ";
}
System.out.println(inputstr);
System.out.println(reverseString);
System.out.println("====================");

}



public static void main(String[] args) {
reverseEachword("java Selenium API");

}

}

23)How To Check If Number Belongs To Fibonacci Series Or Not?
Fibonacci Series : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89……..

package logicparctie;

import java.util.Scanner;

public class FibonacciSeries {
public static void checkFibonacciSeries(int inputNumber){
int firstNum=0;
int SecondNum=1;
int thirdNum=0;

while(thirdNum<inputNumber){
thirdNum=firstNum+SecondNum;
firstNum=SecondNum;
SecondNum=thirdNum;
}

if(thirdNum==inputNumber){
System.out.println("Number belong to Fibonacci series");
}
else{
System.out.println("Number does not belong to Fibonacci series");
}
}
public static void main(String[] args) {
checkFibonacciSeries(344);


}

}

24) Decimal To Binary, Decimal To Octal And Decimal To HexaDecimal In Java

package logicalprog;

import java.util.Scanner;

public class DecimalToBinary {

public static void convertDecimalToBinary(int inputNumber){
int copyOfInputNumber=inputNumber;
String binary="";
int rem=0;
while(inputNumber>0){
rem=inputNumber %2;
binary=rem+binary;
inputNumber=inputNumber/2;
}
System.out.println("Binary Equivalent of" + copyOfInputNumber + "is " +binary);
}
public static void convertDecimalToOctal(int inputNumber){
int copyOfNumber=inputNumber;
String octal="";
int rem=0;
while(inputNumber>0){
rem=inputNumber%8;
octal=rem+octal;
inputNumber=inputNumber/8;
}
System.out.println("Octal Equivalent Of " + copyOfNumber +" is" + octal);
}
public static void convertDecimalToHexaDecimal(int inputNumber){
int copyOfNumber=inputNumber;
String hexa="";
char hexaDecimals[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int rem=0;
while(inputNumber>0){
rem=inputNumber%16;
hexa=hexaDecimals[rem]+hexa;
inputNumber=inputNumber/16;
}
System.out.println("HexaDecimal Equivalemnt of " + copyOfNumber + " is " + hexa);
}
public static void main(String[] args) {
DecimalToBinary.convertDecimalToBinary(50);
DecimalToBinary.convertDecimalToOctal(1000);
convertDecimalToHexaDecimal(2000);
}
}


25)Reverse a Number using a while loop in Java

package com.revisonprograming;

public class ReverseNumber {
public static void reverseNumber(int inputNumber){
int reversed=0;
while(inputNumber!=0){
int lastdigit=inputNumber%10;
reversed=reversed*10+lastdigit;
inputNumber=inputNumber/10;
}
System.out.println("Reversed Number:" + reversed);
}
public static void main(String[] args) {
reverseNumber(1234);
}
}

28)How to Remove Special Characters from String in Java

class RemoveSpacialChar 
{

public static void removeSpacialChar(String str){
str=str.replaceAll("[^a-zA-Z0-9]", " ");
System.out.println(str);
}

/*
we are replacing all the special character with the space.
*/
public  static void removeSpacialCharWithSpace(String str){
str=str.replaceAll("[-+^]*","");
System.out.println(str);

}
public static void removeSpecialCharacter(String str){
String restStr="";
for(int i=0;i<str.length();i++){
//comparing alphabets with their corresponding ASCII value  
if(str.charAt(i)>64 && str.charAt(i)<=22){
restStr=restStr+str.charAt(i);
}
}

     System.out.println("String after removing special characters: "+ restStr);
}


public static void main(String[] args) 
{
//removeSpacialChar("This#string%contains^special*characters&.");
//removeSpacialCharWithSpace("Hello+-^Java+ -Programmer^ ^^-- ^^^ +!");
removeSpecialCharacter("Pr!ogr#am%m*in&g Lan?#guag(e");
}


}

29)How to count String in Array
package com.javapractice;

import java.util.HashMap;
import java.util.Map;

class CountValueInArray 
{
  public static void countElement(String[] strArray){
  Map<String,Integer> hm=new HashMap();
  for(String x:strArray){
if(!hm.containsKey(x)){
hm.put(x,1);
}
else{
hm.put(x,hm.get(x)+1);
}
  }

  System.out.println(hm);
 
}

public static void main(String[] args) 
{
countElement(new String[]{"a","b","c","c"});
}
}

30)WAP to move  all zeroes of an integer array to the start ?

package com.javapractice;

public class MoveZeroInFirst {
static void movezeroinLast(int[] arr){
int current=arr.length-1;
for(int i=arr.length-1;i>=0;i--){
if(arr[i]!=0){
arr[current]=arr[i];
current--;
}
}

while(current>=0){
arr[current]=0;
current--;
}

for(int i=0;i<arr.length;i++){
System.out.println(arr[i] + " ");
}

//for(int i=arr.length-1;i>=0;i--){
//System.out.println(arr[i] + " ");
//}




}
public static void main(String[] args) {
movezeroinLast(new int[] {1, 2, 0, 4, 6, 0, 9, 0, 4, 0, 3, 0, 9, 0, 1, 0, 3, 0});

}

}



31)WAP to move  all zeroes of an integer array to the last?

package com.javapractice;

public class MoveZeroInFirst {
static void movezeroinLast(int[] arr){
int current=arr.length-1;
for(int i=arr.length-1;i>=0;i--){
if(arr[i]!=0){
arr[current]=arr[i];
current--;
}
}

while(current>=0){
arr[current]=0;
current--;
}

//for(int i=0;i<arr.length;i++){
//System.out.println(arr[i] + " ");
//}

for(int i=arr.length-1;i>=0;i--){
System.out.println(arr[i] + " ");
}




}
public static void main(String[] args) {
movezeroinLast(new int[] {1, 2, 0, 4, 6, 0, 9, 0, 4, 0, 3, 0, 9, 0, 1, 0, 3, 0});

}

}

32)WAP to convert first char in lower Case and last char in Upper Case

class CaptalizeLastWord 
{
public static void captalizeLastword(String str){
char FirstChar=str.charAt(0);
System.out.println(FirstChar);
String charToStr=Character.toString(FirstChar);
System.out.println(charToStr.toLowerCase());
char lastChar=str.charAt(str.length()-1);
System.out.println(lastChar);
String  charToStrLast=Character.toString(lastChar);
System.out.println(charToStrLast.toUpperCase());
}
public static void main(String[] args) 
{
captalizeLastword("Mohit");
}
}


33)WAP to 

/*
input
I Am Not String --> 
Output
“gnirtS toN mA I”.
*/

class ReverseStringPreserving1 
{
/*
I Am Not String --> “gnirtS toN mA I”.
*/
public static void preveropstionOfSpaceStr(String str){
String[] words=str.split(" ");
String reversestring="";
for(int i=words.length-1;i>=0;i--){
//System.out.print(words[i]);
String word=words[i];
String reverseword="";
for(int j=word.length()-1;j>=0;j--){
reverseword=reverseword+word.charAt(j);
}
     reversestring =reversestring+reverseword+" ";
}
System.out.println(reversestring);
}
public static void main(String[] args) 
{
preveropstionOfSpaceStr("I Am Not String");
}
}


34)Capitalize last char on each word in Sentence   .

public class LastWordCapital {
public static void main(String[] args) {
String[] s= {"Rohit","Kumar","java"};
String result="";
String[] resultArr=new String[s.length];
for(int i=0;i<s.length;i++) {
String word=s[i].toLowerCase();
char[] wordArr=s[i].toCharArray();
for(int j=0;j<wordArr.length;j++) {
int len=wordArr.length-1;
if(wordArr[j]>='a'&&wordArr[j]<='z'&& j==len) {
wordArr[j]=(char)(wordArr[j]-32);
}
result=result+wordArr[j];
if(len==j) {
result=result+" ";
}
}
}//outer for
System.out.println(result);
}
}

35)How to remove all vowels from a string in java?

package com.javapractice;

public class RemoveAllVowelInString {

static void removeVowel(String str){
char[] ch=str.toCharArray();
String resultStr="";
for(int i=0;i<ch.length;i++){
int count=0;
if(ch[i]=='a' || ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u'){
count++;
}
if(count<1){
//System.out.println(ch[i]);
resultStr=resultStr+ch[i];
}
}
System.out.println(resultStr);
}
public static void main(String[] args) 
{
removeVowel("mohitasdad");
}
}

OR
import java.util.*;
class RemoveVowelTest 
{
public static void main(String[] args) 
{
Scanner scn=new Scanner(System.in);
System.out.println("Enter the String");
String inputString=scn.nextLine();
        String newInputString=inputString.replaceAll("[AEIOUaeiou]","");
System.out.println("The String without vowels::");
System.out.println(newInputString);
scn.close();
}
}


36)How to sort Array Without Using the Method(Asked in Mysys);
import java.util.Arrays;
class SortArray 
{
/*WithOut Inbuild method
*/
static void sortArray(int[] a){
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
int temp=0;
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
System.out.println(a[i]);
}
  
}
/*WithOut build method
*/
     static void sortArrayInbuildMethod(int[] a){
Arrays.sort(a);
System.out.println("Elements of Array sorted in accending order");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
     }



public static void main(String[] args) 
{
sortArray(new int[] {8,7,3,4,5});
sortArrayInbuildMethod(new int[] {8,7,3,4,5});
}
}

39)Sort an Array in Descending Order?

package com.javapractice;

import java.util.Arrays;   
import java.util.Collections;   
public class SortArrayExample4   
{   
public static void main(String[] args)   
{   
int [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};   
// sorts array[] in descending order   
Arrays.sort(array); 
    
System.out.println("Array elements in descending order: " +Arrays.toString(array));
for(int i=array.length-1;i>=0;i--){
System.out.println(array[i]);
}
}   
}

40) Prime Number Programs In Java

What Is Prime Number?
Prime number is a whole number which is greater than 1 and is divisible only by 1 and itself. In the other words, prime number has only two factors, 1 and itself.

Example : 2, 3, 5, 7, 11, 13, 17……
class FindPrimeNumber 
{
static void findPrimeNumber(int num){
int copyOfNumber=num;
int primeNumber=0;
if(copyOfNumber>1&&copyOfNumber%1==0&&copyOfNumber%copyOfNumber==0){
System.out.println("Prime Number");
}
else{
System.out.println("Not Prime Number");
}
}
public static void main(String[] args) 
{
findPrimeNumber(13);
}
}

Note : 0 and 1 are not prime numbers.



41)WAP to Java Program To Reverse A Sentence Word By Word ?
import java.util.*;
class ReverseString 
{
public static String reverseString(String str){
String[] strArray=str.split("\\s");
String reverString="";
for(int i=strArray.length-1;i>=0;i--){
//System.out.println(strArray[i]);
reverString=reverString+strArray[i]+" ";
//System.out.println(reverString);
}
      return reverString;
}
public static void main(String[] args) 
{
         Scanner sc=new Scanner(System.in);
System.out.println("Enter Input String");
  String inputString=sc.nextLine();
  String reverString=reverseString("Mohit kumar");
  //System.out.println("Input String::" + str);
  System.out.println("Output String::" + reverString);


}
}


42)How to find Duplicate element in Array?

package com.collection;

import java.util.HashMap;
import java.util.Set;

public class Testing {
    /*
     * input: {4,3,5,2,1,6,7,9,8,9}
output - 9
     */
static void findDublicate(int[] a,int size){
int count=0;
for(int i=0;i<size;i++){
for(int j=i+1;j<size;j++){
if(a[i]==a[j]){
System.out.println(a[i]);
}
}
}
}
static void findDublicate2(int[] a){
HashMap<Integer, Integer> hm=new HashMap<Integer, Integer>();
for(Integer c:a){
//if(hm.containsKey(c)){
hm.put(c, hm.get(c)+1);
//}
//else{
//hm.put(c, 1);
//}
}
System.out.println(hm);
Set<Integer> set= hm.keySet();
for(Integer c1:set){
if(hm.get(c1)>1){
System.out.println(c1+"::"+hm.get(c1));
}
}
}
public static void main(String[] args) {
//int[] a={4,3,5,2,1,6,7,9,8,9};
//int sizee=a.length;
//findDublicate(a,sizee);
findDublicate2(new int[] {4,3,5,2,1,6,7,9,8,9});

}

}

Q)How to sort an Array?

public class SortArray {

public static void main(String[] args) {
int[] marksArray=new int[]{44,88,22,77,99};
int temp;
for(int i=0;i<marksArray.length;i++){
for(int j=i;j<marksArray.length;j++){
if(marksArray[i]>marksArray[j]){
temp=marksArray[i];
marksArray[i]=marksArray[j];
marksArray[j]=temp;
}
}
}
for(int a:marksArray){
System.out.println(a);
}

}

}

Q)How to find the Kth highest number in Array ?

package com.javaprograming;

public class FindFifthHighNum {

public static void main(String[] args) {
int[] a={5,8,12,7,6,2,4};
int k=5;
for(int i=0;i<a.length-1;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]<a[j]){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
if(i==k-1){
System.out.println(k + " Largest element is " + a[i]);
break;
}
}
System.out.println("--------------------");
for(int i=0;i<a.length;i++){
System.out.println(a[i]+"");
}

}

}

Q)How to add two ArrayList without inbuild method.

static void addArrayList() {
ArrayList<Integer> list1=new ArrayList<Integer>();
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(40);
ArrayList<Integer> list2=new ArrayList<Integer>();
list1.add(50);
list1.add(60);
list1.add(70);
list1.add(80);
ArrayList<Integer> Itmerger=new ArrayList<>();
for(int i=0;i<list1.size();i++) {
Itmerger.add(list1.get(i));
}
for(int i=0;i<list2.size();i++) {
Itmerger.add(list2.get(i));
}
System.out.println(Itmerger);
}

public static void main(String[] args) {
//finddublicateChar("mohitmohoit");
//addArrayList();
addArrayList();

}

}

Q)Bubble sort (String and Int Array)?

package com.testprog;

public class BubbleSort {

public static void main(String[] args) {
      
int[] a= {36,19,29,12,5};
int temp;
for(int i=0;i<a.length;i++) {
int flag=0;
for(int j=0;j<a.length-1-i;j++) {
if(a[j]>a[j+1]) {
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
if(flag==0) {
break;
}
}
for(int i=0;i<a.length;i++) {
System.out.println(a[i]+ "");
}
}

}
===========
package com.testprog;

public class StringButtbleSort {

public static void main(String[] args) {
        String[] a= {"deepak","amit","rahual","vironika","deepesh","rohit"};
        String temp;
        for(int i=0;i<a.length;i++) {
        for(int j=0;j<a.length-1-i;j++) {
        if(a[j].compareTo(a[j+1])>0) {
        temp=a[j];
        a[j]=a[j+1];
        a[j+1]=temp;
        }
        }
        }
        
        for(int i=0;i<a.length;i++) {
        System.out.println(a[i]+"");
        }
}

}


Q) How To Find Duplicate Characters In A String In Java?

Step1:- Creating a HashMap containing char as key and it's occurrences as value. Step2:- Converting given string to char array. Step3:- ...