Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Thursday, 23 January 2020

core java interview questions

Can we Override static methods in java? - NO
If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class

Can we overload static methods? - Yes
We can have two ore more static methods with same name, but differences in input parameters.

what is factory design pattern?
Pattern provides one of the best ways to create an object - We create object without exposing the creation logic to the client and refer to newly created object using a common interface.

https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

how you initialize Page factory object
https://www.seleniumeasy.com/selenium-tutorials/page-factory-pattern-in-selenium-webdriver

what is POM design pattern?
https://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html


is java pure object oriented?  - NO
- because it supports primitive data type [Non Object types] like byte,short,int,long,float,double,char,boolean,which are not objects.
- evrything in java is class, except primitive datatypes.still wrapper classess are there..for this reason we can say java is not fully object oriented language
-The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value
-the main difference between two types is that primitive types store actual values but reference type stores handle to object in the heap
-modification on one primitive variable doesn't affect the copy but it does in the case of the reference variable

int i = 20; int j = i; j++; // will not affect i, j will be 21 but i will still be 20
List<String> list = new ArrayList(2);
List<String> copy = list;
copy.add("EUR");
// adding a new element into list, it would be visible to both list and copy
System.out.printf("value of list and copy after modification list: %s, copy: %s %n", list, copy);




staic class :
Static classes are basically a way of grouping classes together in Java. Java doesn't allow you to create top-level static classes; only nested (inner) static classes.
 public class CarParts {
 
    public static class Wheel {
        public Wheel() {
            System.out.println("Wheel created!");
        }
    }

    public CarParts() {
        System.out.println("Car Parts object created!");
    }
}

wrapper class:
Each Java primitive has a corresponding wrapper:
boolean, byte, short, char, int, long, float, double
Boolean, Byte, Short, Character, Integer, Long, Float, Double
These are all defined in the java.lang package, hence we don't need to import them manually.

Basically, generic classes (Collection Framework)only work with objects and don't support primitives. As a result, if we want to work with them, we have to convert primitive values into wrapper objects.

heap memory vs stack memory:
stack memory is used to store local variables and function call
heap memory is used to store objects in Java
Each Thread in Java has their own stack which can be specified using
If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError:
If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of  heap memory in Java.
ariables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads.

== vs equals
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //True

Friday, 2 August 2019

ElementNotInteractableException



ElementNotInteractableException::
is caused when an element is found, but you can not interact with it. For instance, you may not be able to click or send keys.

There could be several reasons for this:

1. Wait until an element is visible / clickable
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOf(element));
wait.until(ExpectedConditions.elementToBeClickable(element));

2. Add Implicit wait

Interview qns on final keyword | java

1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).

2) Java final method
If you make any method as final, you cannot override it.

3)Java final class
If you make any class as final, you cannot extend it.

Q)Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:

Q)Can we initialize blank final variable?
Yes, but only in constructor. For example:

Q)static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.   int cube(final int n){ n = n+2; }

Q)Can we declare a constructor final?
No, because constructor is never inherited.

Monday, 22 July 2019

Interview Qns - Core java

Output please

public class Test123 {

static {
System.out.println("first static block");
}
static {
System.out.println("Second static block");
}

public static void main(String[] args) {
System.out.println("Main Method");
Test123 t = new Test123();
}

Test123() {
System.out.println("COnstructor");
}

}


Output:
first static block
Second static block
Main Method
COnstructor



Yes, we can write n number of static blocks 
Main method executes after static blocks
--------------------------------


Can we write Throwable in Catch block??

public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}

Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it!

If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application. Typical examples for that are the OutOfMemoryError or the StackOverflowError. Both are caused by situations that are outside of the control of the application and can’t be handled.

So, better don’t catch a Throwable unless you’re absolutely sure that you’re in an exceptional situation in which you’re able or required to handle an error.

-----------------------------------
The task is to write a program to generate the largest number possible using these digits.
Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}
Output : Largest number: 87664420


static int findMaxNum(int arr[])
{
    // sort the given array in
    // ascending order and then
    // traverse into descending
    Arrays.sort(arr);
   
    int num = arr[0];
    int n = arr.length;
   
    // generate the number
    for(int i = n - 1; i >= 0; i--)
    {
        num = num * 10 + arr[i];
    }
   
    return num;
}
--------------------------------------
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
FileReader thows FileNotFoundException is a subclass of IOException - hence am throwing


import java.io.*;

class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
       
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
       
        fileInput.close();
    }
}

Ex:
ClassNotFoundException,
IOException,
SQLException


Unchecked: are the exceptions that are not checked at compiled time
Ex:
NullPointerException
ArithmeticException,
ArrayStoreException,
ClassCastException
IndexOutofbounds
---------------------------------------

Inheritance - Class casting -  Parent to Child and Child to parent


public class Parent {

public void m1() {
System.out.println("parent method");
}

}

public class Child1 extends Parent {

public void m1() {
System.out.println("Child1 method");
}

public static void main(String[] args) {
Parent p = new Parent();
p.m1();

Child1 c = new Child1();
c.m1();

Parent p1 = new Child1();
p1.m1();

Child1 cer = (Child1) p;// RuntimeError : java.lang.ClassCastException:
// javaProg.Parent cannot be cast
// to
// javaProg.Child1

Child1 cerr1 = (Child1) new Parent();// Runtime error :
// java.lang.ClassCastException: javaProg.Parent cannot be
// cast to javaProg.Child1
}
}

output:
parent method
Child1 method

Child1 method

Note - Only Child to parent casting is possible, Rest all Runtime Exception
--------------------------------------------------
Remove duplicates from array

// NOTE : SORTED ARRAY
public static int removeDuplicateElements(int arr[], int n){
        if (n==0 || n==1){
            return n;
        }
        int[] temp = new int[n]; // lets use temp array
        int j = 0;
        for (int i=0; i<n-1; i++){
            if (arr[i] != arr[i+1]){
                temp[j++] = arr[i];
            }
         }
        temp[j++] = arr[n-1]; // ADD LAST ITEM TO TEMP ARRAY
 
        // Changing original array
        for (int i=0; i<j; i++){
            arr[i] = temp[i];
        }
        return j;
    }
---------------------------------------------------
how to make thread safe

Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:

  public static synchronized void add(int value){
      count += value;
  }
Also here the synchronized keyword tells Java that the method is synchronized.

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.


If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
--------------------------------------
public vs protected

The protected specifier allows access by all subclasses of the class in a program, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages

----------------------------------------

Guess the out put of below prog


try{
System.exit(-1);
System.out.println("in try");
}
catch(Exception ex){
System.out.println("in Exception block");
}

output : Nothing - as program exits then and there



Java System exit() Method
The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.


System.exit(0) or EXIT_SUCCESS;  ---> indicates Successful termination
System.exit(1) or EXIT_FAILURE;  ---> indicates unsuccessful termination with Exception
System.exit(-1) or EXIT_ERROR;   ---> indicates Unsuccessful termination


Thursday, 9 May 2019

Interview | @CacheLookup - in Page Object Model | Page Factory


@CacheLookup, as the name suggests helps us control when to cache a WebElement and when not to.

This annotation when applied over a WebElement instructs Selenium to keep a cache of the WebElement instead of searching for the WebElement every time from the WebPage. This helps us save a lot of time.

Syntax:
 @FindBy(how = How.NAME, using = "firstname")
 @CacheLookup
 public WebElement firsNameCached;

Tuesday, 7 May 2019

Interview | How can you solve StaleElementReferenceException

How can you solve StaleElementReferenceException

Answer : ExpectedConditions.refreshed

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.


public WebElement waitForElementToBeRefreshedAndClickable(WebDriver driver, By by) {
    return new WebDriverWait(driver, 30)
            .until(ExpectedConditions.refreshed(
                    ExpectedConditions.elementToBeClickable(by)));
}

So basically, this is a method that waits until a DOM manipulation is finished on an object.

When the DOM has manipulated, and say after clicking a button, adds a class to that element. If you try to perform an action on said element, it will throw StaleElementReferenceException since now the  WebElement returned now does not represent the updated element.

You'll use refreshed when you expect DOM manipulation to occur, and you want to wait until it's done being manipulated in the DOM.

Wednesday, 16 May 2018

Interview question | Page Factory | Lazy loading

Here is the interview question:

As per "Page Factory", all the elements will be initialized at the time of page load.
But in dynamic applications how page factory works?
Ex: Assure a drop down content ( options)  loads on click of the respected select box, how can you implement page factory for this?, as page factory initializes elements at the time of page load only.

Answer:
Lazy load concept.

AjaxElementLocatorFactory is a lazy load concept in Page Factory pattern to identify WebElements only when they are used in any operation
i.e. a timeOut for a WebElement can be assigned to the Object page class with the help of AjaxElementLocatorFactory.

Syntax : ( similer to plain "Page Factory init elemnts"  method )

PageFactory.initElements(new c(driver, 30), this);

If element not found in 30 secs, NoSuchElemementException throws.

happy coding.

Wednesday, 25 April 2018

Java Program : write a method to check if it is well formed expression. Eg: {[()]}

This question was asked in an interview that I found interesting.

Here you go.

I know, There are other ways to do it better.

                Map<Character, Character> exprssionMap = new HashMap<>();
exprssionMap.put('{', '}');
exprssionMap.put('[', ']');
exprssionMap.put('(', ')');

String inputExpression = "{[({{)}}]}";
int expressionLengh = inputExpression.length();
if (expressionLengh % 2 == 1) {
System.out.println("malformed Expression; Size of the Expression is not even                                           number");
} else {
for (int i = 0; i < expressionLengh / 2; i++) {
if (!exprssionMap.get(inputExpression.charAt(i))
.equals(inputExpression.charAt(expressionLengh - 1 - i))) {
System.out.println(
"Matching expression not found for: " +                                                                                                    inputExpression.charAt(i) + "; index:" + i);
}
}
}

Happy Coding.

Thursday, 8 December 2016

selenium quick tutorial

Tool Selection:
Before finalizing automation tool we should consider below points
Ease of usage
Quick Support
Technology support
Cost
Compatible with different browsers and operating systems

Selenium is open source WEB automation testing tool.
Technologies: java , c#, Ruby, Python, PHP
Browsers: ie, chrome, Firefox, opera, safari
OS: win, max, Linux, Unix

Selenium components:
IDE, RC, WebDriver 2.0, Web Driver 3.0, Grid
IDE: add-on Firefox browser. For record and play back only. With the help of user extensions, we can improve functionality. Supports conditional, iterative, regex. Tests can be parameterized using IDE
RC: (1.0 ), supports multiple browsers, supports most of the programming languages
WD: (2.0, 3.0) : eliminated drawbacks in RC ( by eliminating server ). We can make direct calls to the browser using various drivers available. Supports mobile testing
GRID: to run tests parallel on different machines at a time

Advantages:
Free and open source
Multi browser and OS support
Parallel execution
Mobile testing
IDE – record and play back for quick automation evaluation
Continuous integration support
Easy framework development (data, keyword, hybrid, POM, PF )
Support for testing, junit etc

Capabilities:
Capabilities are options that you can use to customize and configure a Browser Driver session. 

Chrome:


DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Add the WebDriver proxy capability.
Proxy proxy = new Proxy();
proxy.setHttpProxy("myhttpproxy:3337");
capabilities.setCapability("proxy", proxy);

// Add ChromeDriver-specific capabilities through ChromeOptions.
ChromeOptions options = new ChromeOptions();

options.addExtensions(new File("/path/to/extension.crx"));//browser extensions
options.addArguments("start-maximized");//start chrome maximised
options.setBinary("/path/to/other/chrome/binary");// chrome.exe file path, if multiple verions available
options.addArguments("user-data-dir=/path/to/your/custom/profile");//By default, ChromeDriver will create a new //temporary profile for each session. At times you may want to set special preferences or just use a custom //profile altogether

capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
--OR--
RemoteWebDriver driver = new RemoteWebDriver(
     new URL("http://localhost:4444/wd/hub"), capabilities);


Internet Explorer:
Set below browser options



DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
 
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(InternetExplorerDriver.
  INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "https://testvmm6.partnersonline.com/vmm");
capabilities.internetExplorer().setCapability("ignoreProtectedModeSettings", true);

capcapabilities.setCapability("IE.binary", "C:/Program Files (x86)/Internet Explorer/iexplore.exe");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("requireWindowFocus", true);
capabilities.setCapability("enablePersistentHover", false);

System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");//32 bit driver is good

WebDriver driver = newInternetExplorerDriver(capabilities);


Navigation methods:
Driver.get(“url”)
Driver.getTitle()
Driver.getCurrentURl()
Driver.getPageSource()
Driver.close()//closes current browser
Driver.quit()//closes all browsers under the driver
Driver.navigate().to(“url”)
Driver.navigate().forward()
Driver.navigate().back()
Driver.navigate().refresh()

Locators:
Common web elements are TextBox, Button, DropDown, Anchor Tag, ChecBox, Radio Button.
We can locate elements using ID, class name, Name, link text, xpath, css selector ( id, class, attribute, substring, Innter text )

<input id=”myId” name=”name1” class=”class1” title=”sample toot tip”/>
<a>help</a>

ID: Driver.findElement(By.id(“myId”))
Name: Driver.findElement(By.name(“name1”))
Class: Driver.findElement(By.class(“class1”))
linkText: Driver.findElement(By.LinkText(“Help”))
Xpath: Driver.findElement(By.xpath(“//intput[@title=’sample tool tip’]”)
Tagname: Driver.findElement(By.tagName(“input”))
cssSelector: driver.findElement(By.css(‘#myId’))

FindElement vs FindElements
WebElement ele = Drive.findElement(By.id(“#myId”)) // returns only one element
List<WebElemen> list = Driver.findElements(By.tagName(“input”))// returns list of elements

Events:
Common web element interactions are
Click(), clear(), sendKeys(“”), isDispalyed(), isSelected() ( applicable for check box and Radio button ) ,getText().getAttribute(“attr”), getSize(), getLocation() ( returns X and Y co-ordinate )

Synchronization ( webDriver waits):
Implicit wait: wait is applicable for all the elements under the driver object.
Wait for all the elements maximum 10 seconds if not available by default.
If element found, skips the wait time.
Driver.manage().timeouts.implicitWait(10,TimeUnits.SECONDS)
Explicit Wait : wait is applicable for only one element under the driver object.
We can specify explicit waiting conditions for any element so that our test should pass.
Ex: wait for this element until this element is clickable , upto maximum 55 seconds.
If element found, skips the wait time.
Few expected conditions are below:
elementToBeClickable()
textToBePresentInElement()
alertsPresent()
Titles()
framToBeAvaialbeAndSwitchToIt()

Actions Class:
Helps to handle keyboard and mouse events ( ex: drag and drop, selecting items holding Control key or alt key etc )


Actions builder=new Actions(driver);
        builder.moveToElement(username,150,22);
        builder.sendKeys("Mahesh");
        builder.perform();

Action seriesofactions=builder.moveToElement(username).click().keyDown(username,Keys.SHIFT).sendKeys(username,"hell").keyUp(username,Keys.SHIFT).doubleClick(username).contextClick(username).build();
       seriesofactions.perform();

clickAndHold()
release()
contextClick()
doubleClick()
dragAndDrop(source,target)
dragAndDropBy(source,x-offset,y-offset)
keyDown(modifier_key)
keyUp(modifier_key)
moveByOffset(x-offset, y-offset)
moveToElement(toElement)
sendKeys(onElement, charSequence)


Screen capture:
If we wanted to take screen shot of current browser, here is the way

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Switch to :
Here is the code to switch to new browser and and close it and switch back to original browser.
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)

Alerts:
Below is the code for accepting alert box and getting alert text

String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
// This will wait for a maximum of 5 seconds, everytime wait is used

driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something

wait.until(ExpectedConditions.alertIsPresent());
// Before you try to switch to the so given alert, he needs to be present.

Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();

return alertText;


Monday, 18 April 2016

Selenium Question

-          Assume, given web application contains 10 dynamic text boxes.
-          Text box placing/location will also changes dynamically.
-          Now we need to key in text in one specific text box, which does not contain any unique locator ( We are not able to find out uniqueness with partial text too )

How you do you achieve this?                                                  

Analysis:
-          No unique ID , tool tip, value, css style, etc.
-          We are not able to draw unique ness with partial ID / text / value / etc

Tip:
-          Only one control is having unique ID and whose position is dynamic.
      

  Idea:
-          Can we use below Xpath selectors


AxisName
Result
ancestor
Selects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-self
Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself
attribute
Selects all attributes of the current node
child
Selects all children of the current node
descendant
Selects all descendants (children, grandchildren, etc.) of the current node
descendant-or-self
Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself
following
Selects everything in the document after the closing tag of the current node
following-sibling
Selects all siblings after the current node
namespace
Selects all namespace nodes of the current node
parent
Selects the parent of the current node
preceding
Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes
preceding-sibling
Selects all siblings before the current node
self
Selects the current node


Examples:

Example
Result
child::book
Selects all book nodes that are children of the current node
attribute::lang
Selects the lang attribute of the current node
child::*
Selects all element children of the current node
attribute::*
Selects all attributes of the current node
child::text()
Selects all text node children of the current node
child::node()
Selects all children of the current node
descendant::book
Selects all book descendants of the current node
ancestor::book
Selects all book ancestors of the current node
ancestor-or-self::book
Selects all book ancestors of the current node - and the current as well if it is a book node
child::*/child::price
Selects all price grandchildren of the current node




Examples:


//td[text() = ' Color Digest ']/following-sibling::td[2]
//h2[contains(text(),'Hello')]/parent::div//div[//a[text()='SELENIUM']]/following-sibling::div[@class='rt-grid-2']

Selenium Question


-          Assume, given web application is accessible in one Machine ( IP : 10.10.10.10)
-          You need to write selenium tests and run.
-          You are not allowed to install / download any software except browser in IP: 10.10.10.10.
How you do you achieve this?                                                 
Analysis:
-          We can start coding in our local laptop , later we can think about executing tests.
-          To find out locators ( xpaths / css / etc) , connect to the machine IP 10.10.10.10 via remote desktop and fetch as much info as needed.
Now Execution part,
-          When we execute our test in local, tests should run in the IP 10.10.10.10.
-          This can be achieved via selenium GRID.
-          Create a node in IP 10.10.10.10 and connect to a HUB ( either in your laptop / IP 10.10.10.10)
-          Write Remote web driver code instead of plain webdriver.

Just hit run. That’s all.