Saturday, August 29, 2020

L&T Interview Questions of both 1st and 2nd round

 1. Tell me about yourself ?

Java:

1. All OOPS concepts and where it is used in your project ?

2. What is String ?

3. Difference between List and Array ?

4.Which is Super Class of all Java Classes ?

5. Can we create non static call non static methods in static methods ?

6. Can we call static method in non static methods ?

7. Difference between Collection and Collections ?

8. Array List and Array ?

8. Map and Hash Map ?

9. String Buffer ?

10. Interface and Abstraction ? 

11. Exceptions in java ?

12. What exceptions you faced ?

13. How you handle Exceptions ?

Selenium 

1. annotations in TestNG ?

2. If you want to execute all Test cases how you will do it and ways to do it ?

3. what is glue in cucumber ?

4. what is use of j-unit ?

5. Waits in Selenium ?

6. What is Web-driver ?

7. What is Data-provider ?

8. how you implemented in your project ?

9. tell some syntax to access from xlsx file ?

10. what are in your util package in framework ?

11. how many ways to handle alert ?

12. What is Action ?

13. Suppose you want to Login in to application and do three task deposit amount, Withdraw amount and invest amount and then logout. What is your approach to write Scenario for it ?

14. What challenges you faced in your Automation Carrier ?

15. What is you Job in the Current Framework ?

16. What is CI ? you worked on it ?

17. how to work on you on you framework and do Jenkin execution ?

18. Who is reviewing you code and how ?

19. How can you make it to review your code ?

20. What is POI ?

21. What is use of maven surefire Plugin ?




  


Thursday, August 6, 2020

Xorient Interview Quetions

 1. Introduce yourself

2. write just function of Fibonacci series and return the series by using return

3. what is static and final

4. Map and Hashmap

5. can we use Arraylist in Hashmap?

6. what is String Literal ?

7.  Constructor Overloading ?

8. why use Constructor Overloading ?

9. LinkList and Arraylist ?

10. open flipkart and find xpath of View All Button.

11. how to find all view all buttons which are at 4 position and click on it and find broken links

12. actions method syntax?

13. JavascripExecutor syntax

14. how to refresh and nevigate by using JavaScriptExecutor ?

15. GIT all process with syntax which you do ?

16. What is Where and having Cluase and e.g?

17. Aggregation in SQL?

18. Updacasting in java ?

19. can we override static methods ?



2nd Round:

1. what is hidden methods in java ?

2. What is Interface ?

3. All the questions regarding Interface with Conditions ?

4. Find xpath of more Element from flipcart and 1st element from dropdown?

5. write program to count char, Integer, Special char from given String?

6. write a program to count how many words in string without split method ?

7. write code to click on flipcart one drop-down and then 1st value by using action ?

8. API how to validate Get output with specific values ?

9. Diff String and StringBuffer

10. Hashmap and HashSet Diff with some cross questions?

11.  Web Driver ?

12. what is Static Method in Java ?

13. Can we create Static method inside class ? why ?

14. Can we create class inside Interface ?

15. Can we create Interface inside Interface ?






REST Assured Automation Interview Questions

1. What is REST Assured API's ?
Ans: REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. In the following sections, I'll show you how to set up and configure REST Assured, write and run REST Assured tests, and apply some of its most powerful features.

2. 

Sunday, June 7, 2020

Cucumber Tagging




Collections of interview questions asked for performance Testing Tool Jmeter

Collections of interview questions asked for performance Testing Tool in various organisation - Jmeter

1.    Explain the architecture of JMeter

2.    How do u used Jmeter in ur project and why

3.    What are different timers used in Jmeter

4.   How requests are sent to the server in JMeter?

5.     Explain the Process of Parameterization
6.    Does JMeter simulate actual browser behavior?
7.    What is Distributed testing?

8.    What is the use of Regular Expression in JMeter?

9.       What are the types of processors in JMeter?

10.   What are the different ways of Data Parameterization in JMeter?

11.   What are the maximum recommended threads on a single system?

12.   Explain the difference between Gaussian and Poisson Timers.

13.   What are the major differences between JMeter and Load Runner.

14.   What is the use of co-relation in JMeter?

15.   Latest version of Jmeter

16.   What are the different types of listeners?

17.   Explain the flow of the Test Script Recorder.

18.   Can JMeter record actions from mobile? If yes, how?

19.   How to do master-slave configuration in JMeter?

20.   What are the JMeter supported protocols?

21.   Why is it recommended to run JMeter in GUI mode?

22.   Is it possible to run selenium scripts in JMeter? If yes, how?

23.   How do you manage sessions and cookies in JMeter?

24.   What are the important steps for testing JDBC request?

25.   What is BeanShell scripting?

26.   Can JMeter measure the performance of a complete application? For Example, you have multiple screens in your mobile app. Can JMeter measure the time taken to flip the screens?

27.   What is a Root CA certificate?

28.   Which factors decide the maximum threads that one should generate per system?

29.   What is a Workbench and why is it required

30.   What is Tidy Parsing?

31.   What are the important plugins that are supported in JMeter?

32.   What are the types of the controller in JMeter?

33.    Explain Ramp up period?

34. What are the roles of Listeners in JMeter. Can you name a few of them?
             
33.Name a few timers in JMeter. For what purpose they are considered?
34.   What do you mean by Rendezvous point?
35.  What do you know about assertions?

36.  What do you know about the Pre-processors in JMeter?


37.  Is it possible to run JMeter in GUI? If so, explain how?
38.  What are the different protocols that are supported by JMeter?
39.  What are the main parts of a Thread Group?
40.  How sampler and logical controllers in JMeter are different?
41.   Name at least 10 Listeners that JMeter is equipped with?
42.   What are the applications that you can test with JMeter?
43. What are Post-Processors in JMeter?
44. What do you know about the Concurrent user hit in JMeter?
45. : List some of the test plan elements in JMeter.
46. What are Controllers and its types?
47.  What is the execution order of Test Elements
48.  What is 90% line in JMeter?
49. What is heap size in jmeter?
50.  What is median in jmeter listener
51.   Is it possible that, if we increase the heap size in Jmeter, then application(jmeter) might not work?
52.    What is Blaze Meter?
53.  How do you ensure re-usability  in your JMeter scripts?

Cards and Payments Domain Interview questions

Cards and Payments Domain Interview questions

-What is Payment Gateway?

-What is BIN?

-What is MTI? Different codes of MTI ?

-Explain the transactional cycle in the cards and Payments?

-What is reconcillation process and when does it work?

-What is ISO? and Types oF ISO ?

-What is clearing and settlement ?

-Explain the different roles involved of the merchant bank in the cards and payments?

-What is authorization and authentication ?

-What is single message system and dual message system ?

-What is POS? and how it works ?

-What is the digit format to indicate the credit card and debit card number?

-What is MMS and ESB card allocation ?

-How you can define ON US/OFF US transaction ?

-What is Payment Schemes ?

-What is Multi currency wallet and single Currency wallet?

-What is batch closure?

-What is abbreviation of zpk / bdk / zmk ? in cards

-What is Offline Advice ? and concept of adjustment ?

-How the process of offline Transaction get submitted ?

-What are the different exceptional cases in the failure of the transaction ?

-How will you identify format of the card wheter it is a debit or credit card while checking out the transaction done by the user?

-What is the issuer bank ?

- Explain the concept of the prepaid in the cards and payments ?

-What is MSP?

-What are different types of transactional codes ?

-What is the authorization response and the request code for the MTI ?

-What is the full form of CVV ?

- What is cross border payments ?

-Explain charge back concept ?

-Explain tokenization in Payments ?

-What is capture file and clearing process flow?

-What is PCI DSS?

-What is Swift Payments and P2P, A2A transfer?

-What is SEPA and concept of Insta Payment

-Explain  ISO 8583, ISO 20022?

-What is FIX ?

-What is file maintenance error code and explain the batch file ?

- What is Burp Suite ? explain tool functioning of this tool ?

- Explain the process how you handle the processing stage in the burp suite?

Wednesday, April 29, 2020

FirstCry

Q1. Types of Popup in Selenium ?

Ans: There are the four methods that we would be using along with the Alert interface.
1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
3) String getText() – The getText() method returns the text displayed on the alert box.
4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Alert alert = driver.switchTo().alert(); alert.accept(); System.out.println(driver.switchTo().alert().getText()); driver.switchTo().alert().accept();
Q2. Which kind of Application you are working on ?
Ans: Web- Based Application.
Types of Applications: 
  • Mobile Applications
  • Desktop GUI Applications
  • Web-based Applications
  • Enterprise Applications
  • Scientific Applications
  • Gaming Applications
  • Big Data technologies
  • Business Applications
  • Distributed Applications
  • Cloud-based Applications

Q3 . Difference Between Junit and TestNG FW ?

JUnit   TestNG
It is opensource testing framework.It is also opensource testing framework with added benefits.
Does not support advanced annotations.Supports advanced annotations and special annotations.
Does not support parallel testing.Supports Parallel testing.
Group test feature is not present here.Group test feature is TestNG's commonly used feature.
Parameterized test case take less time.Parameterized test take more time and are complicated.
It is difficult to use.It is much easier to use.
Q4. With Cucumber can we use TestNG

Ans: Yes, definitely we can use TestNG along with Cucumber. We have already used the same in different frameworks while working for automation testing company. Below is the sample code of Cucumber runner file with TestNG and you can call it from TestNG suite,
Runner file:
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;

 import cucumber.api.CucumberOptions;
 import cucumber.api.testng.AbstractTestNGCucumberTests;
 import driver.Driver;

 @CucumberOptions(
 strict = true,
 features = "src/test/java/features",
 glue = "stepDefinations",
 plugin = {"pretty", "html:target/cucumber-html-report" },
 tags={"@login1"}
 )

 public class CucumberRunWithTestNG extends AbstractTestNGCucumberTests{

 @BeforeClass
 public void instantiateDriver(){

 Driver.getDriver();
 }

 @AfterClass
 public void tearDown(){
 Driver.getDriver().quit();
 }

 }
TestNG suite file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
 <suite name="Testng Cucumber Suite" parallel="none">
 <test name="Run All Tests">
 <classes>
 <class name="runners.CucumberRunWithTestNG"></class>
 <!-- <class name="main.AnotherRunner"></class> This class could be used to run multiple runner classes-->
 </classes>
 </test> <!-- Test -->
 </suite> <!-- Suite -->

Q5 What are the four Pillars of Java ? Explain ?


Ans: 

  1. Abstraction is the process of exposing the essential details of an entity, while ignoring the irrelevant details, to reduce the complexity for the users.
  2. Encapsulation is the process of bundling data and operations on the data together in an entity.
  3. Inheritance is used to derive a new type from an existing type, thereby establishing a parent-child relationship.
  4. Polymorphism lets an entity take on different meanings in different contexts.
Q 6. Is it necessary to use super keyword for calling parent class Constructor ?
Ans:  Yes, 
A subclass can have its own private data members, so a subclass can also have its own constructors.
The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass.
To call a superclass constructor the super keyword is used.

Q 6. Can we Automate OTP via email ?
Ans: Yes !
Once you send OTP from the application. You have to use javax.mail and have to write the code to read the email from mailbox for provided emailid. and then extract the OTP using suitable regex from content you get.
First add these dependency if you are using Maven project otherwise you have to add same libraries in your project
    <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>
Create one class and use this code :

String hostName = "smtp.gmail.com";
String username = "email username"
String password = "email passeord"
int messageCount;
int unreadMsgCount;
String emailSubject;
Message emailMessage;

public MailReader() {
    Properties sysProps = System.getProperties();
    sysProps.setProperty("mail.store.protocol", "imaps");

    try {
        Session session = Session.getInstance(sysProps, null);
        Store store = session.getStore();
        store.connect(hostName, username, password);
        Folder emailInbox = store.getFolder("INBOX");
        emailInbox.open(Folder.READ_WRITE);
        messageCount = emailInbox.getMessageCount();
        System.out.println("Total Message Count: " + messageCount);
        unreadMsgCount = emailInbox.getNewMessageCount();
        System.out.println("Unread Emails count:" + unreadMsgCount);
        emailMessage = emailInbox.getMessage(messageCount);
        emailSubject = emailMessage.getSubject();

        Pattern linkPattern = Pattern.compile("href=\"(.*)\" target"); // here you need to define regex as per you need
        Matcher pageMatcher =
                linkPattern.matcher(emailMessage.getContent().toString());

        while (pageMatcher.find()) {
            System.out.println("Found OTP " + pageMatcher.group(1));
        }
        emailMessage.setFlag(Flags.Flag.SEEN, true);
        emailInbox.close(true);
        store.close();

    } catch (Exception mex) {
        mex.printStackTrace();
    }
}

Q7. You are working on eCommerce application how you login ? Is there no Security ? 
Ans: 
  1. Use SSL and Ensure That Your Ecommerce web site is PCI Compliant

SSL. Stands for "Secure Sockets Layer." SSL is a secure protocol developed for sending information securely over the Internet. Many websites use SSL for secure areas of their sites, such as user account pages and online checkout. Usually, when you are asked to "log in" on a website, the resulting page is secured by SSL

The Payment Card Industry Data Security Standard is an information security standard for organizations that handle branded credit cards from the major card schemes. The PCI Standard is mandated by the card brands but administered by the Payment Card Industry Security Standards Council.

Q8 What is Bundle ID ?

Ans : Bundle ID is a tool Apple uses to identify individual apps. ... You can change your Bundle ID on iTunes Connect until your app has been approved by Apple and is available on the App Store. Once your app is approved and available for download on the Apple App Store, your Bundle ID cannot be changed.

Q9. Which is the fastest method getText() or getAttribute() ?
Ans: 

Q10. Suppose I hit a URL say www.facebook.com then I am on Homepage of it, As we know we are having many data on that page photos, titles, etc. So can we fetch all this data without hitting a Url ? How ?

Note: I am using that url but not hitting that url. can get all the data.

Ans: Yes, you can do that using headless. 


1. HtmlUnitDriver – the initial headless driver

2. PhantomJS

PhantomJS is one of the best options. A sample example taken from here.


var page = require('webpage').create(),
url = 'http://lite.yelp.com/search?find_desc=pizza&find_loc=94040&find_submit=Search';
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
    var results = page.evaluate(function() {
    var list = document.querySelectorAll('address'), pizza = [], i;
    for (i = 0; i < list.length; i++) {
    pizza.push(list[i].innerText);
}
    return pizza;
});
    console.log(results.join('\n'));
}
    phantom.exit();
});
OR
Don't use Selenium for this.
Use Jsoup.
100% headless, and does not require any 3rd party programs, unlike selenium, to get the page content.

Q11. Limitation of Selenium ?
Ans: 
  • Selenium does not support automation testing for desktop applications.
  • Selenium requires high skill sets in order to automate tests more effectively.
  • Since Selenium is open source software, you have to rely on community forums to get your technical issues resolved.
  • We can't perform automation tests on web services like SOAP or REST using Selenium.
  • We should know at least one of the supported programming languages to create tests scripts in Selenium WebDriver.
  • It does not have built-in Object Repository like UTF/QTP to maintain objects/elements in centralized location. However, we can overcome this limitation using Page Object Model.
  • Selenium does not have any inbuilt reporting capability; you have to rely on plug-ins like JUnit and TestNG for test reports.
  • It is not possible to perform testing on images. We need to integrate Selenium with Sikuli for image based testing.
  • Creating test environment in Selenium takes more time as compared to vendor tools like UFT, RFT, Silk test, etc.
  • No one is responsible for new features usage; they may or may not work properly.
  • Selenium does not provide any test tool integration for Test Management.
  • Using Selenium tool alone mobile applications cannot be tested, with use of Appium we can achieve it.
  • The Windows-based popup cannot be tested using Selenium alone we need to use AutoIT to handle the windows based popups.
Q12. Difference between annotations of Junit and TestNG ?

Ans:
Feature

JUnit 5

TestNG

Test annotation

@Test

@Test
Execute before the first test method in the current class is invoked

@BeforeAll

@BeforeClass
Execute after all the test methods in the current class have been run

@AfterAll

@AfterClass

Execute before each test method

@BeforeEach

@BeforeMethod

Execute after each test method

@AfterEach

@AfterMethod

Ignore Test

@ignore

@Test(enable=false)

Expected exception
@Test(expected=Arithmetic
Exception.class)
@Test(expectedException=Arithmetic
Exception.class)

Timeout

@Test(timeout = 1000)

@Test(timeout = 1000)
Execute before all tests in this suite have run

N/A

@BeforeSuite
Execute after all tests in this suite have run

N/A

@AfterSuite

Execute before the test

N/A

@BeforeTest

Execute after the test

N/A

@AfterTest
Execute before first test method that belongs to any of these groups is invoked

N/A

@BeforeGroups
Execute after the last test method that belongs to any of these groups is invoked

N/A

@AfterGroups
Q13. Difference between @test and @BeforeClass in TEstNG ?

Ans: @BeforeClass: The annotated method will be run before the first test method in the current class is invoked. @BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. Both the above TestNG annotations look similar in functionality.

Q14. What is Object repository ?

Ans: Object Repository is used to store element locator values in a centralized location instead of hard coding them within the scripts. We do create a property file (. properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.

Q15. Explain Exception Handling ? How can we achieve ?
Ans: 

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.

Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.

Exception Handling

If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. For example look at the system generated exception below:
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5)
 ExceptionDemo : The class name
 main : The method name
 ExceptionDemo.java : The filename
 java:5 : Line number
This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

Advantage of exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.

Difference between error and exception

Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.
Exception classes hierarchy

Types of exceptions

There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Q16. What are Different kind of Exceptions you have faced ?
Ans: The complete list of exceptions in Selenium
1. ConnectionClosedException: This exception takes place when there is a disconnection in the driver.
2. ElementClickInterceptedException: The command could not be completed as the element receiving the events is concealing the element which was requested clicked.
3. ElementNotInteractableException: This Selenium exception is thrown when an element is presented in the DOM but it is impossible to interact with such element.
4. ElementNotSelectableException: This Selenium exception is thrown when an element is presented in the DOM but you can be able to select. Hence, it is impossible to interact with.
5. ElementNotVisibleException: This type of Selenium exception takes place when existing element in DOM has a feature set as hidden. In this situation, elements are there, but you can not see and interact with the WebDriver.
6. ErrorHandler.UnknownServerException: Exception is used as a placeholder if the server returns an error without a stack trace.
7. ErrorInResponseException: This exception is thrown when a fault has occurred on the server side. You can see it happens when interacting with the Firefox extension or the remote driver server.
8. ImeActivationFailedException: This exception occurs when IME engine activation has failed.
9. ImeNotAvailableException: This exception takes place when IME support is unavailable.
10. InsecureCertificateException: Navigation made the user agent to hit a certificate warning, which is caused by an invalid or expired TLS certificate.
11. InvalidArgumentException: This Selenium exception is thrown if an argument does not belong to the expected type.
12. InvalidCookieDomainException: This happens when you try to add a cookie under a different domain rather than the current URL.
13. InvalidCoordinatesException: This happens if the coordinates offered to an interacting operation are not valid.
14. InvalidElementStateException: This Selenium exception occurs if a command cannot be finished as the element is invalid.
15. InvalidSessionIdException: Takes place when the given session ID is not included in the list of active sessions, which means the session does not exist or is inactive either.
16. InvalidSwitchToTargetException: Happens if frame or window target to be switched does not exist.
17. JavascriptException: This problem happens when executing JavaScript supplied by the user.
18. JsonException: Happens when you afford to get the session capabilities where the session is not created.
19. MoveTargetOutOfBoundsException: Takes place if the target provided to the ActionChains move() methodology is not valid. For example: out of document.
20. NoAlertPresentException: Happens when you switch to no presented alert.
21. NoSuchAttributeException: Occurs when the attribute of element could not be found.
22. NoSuchContextException: Happens in mobile device testing and is thrown by ContextAware.
23. NoSuchCookieException: This exception is thrown if there is no cookie matching with the given path name found amongst the associated cookies of the current browsing context’s active document.
24. NoSuchElementException: Happens if an element could not be found.
25. NoSuchFrameException: Takes place if frame target to be switch does not exist.
26. NoSuchWindowException: Occurs if window target to be switch does not exist.
27. NotFoundException: This exception is subclass of WebDriverException. It happens when an element on the DOM does not exist.
28. RemoteDriverServerException: This Selenium exception is thrown when server do not respond due to the problem that the capabilities described are not proper.
29. ScreenshotException: It is impossible to capture a screen.
30. ScriptTimeoutException: Thrown when executeAsyncScript takes more time than the given time limit to return the value.
31. SessionNotCreatedException: A new session could not be successfully created.
32. SessionNotFoundException: The WebDriver is performing the action right after you quit the browser.
33. StaleElementReferenceException: This Selenium exception happens if the web element is detached from the current DOM.
34. TimeoutException: Thrown when there is not enough time for a command to be completed.
35. UnableToCreateProfileException: You can open a browser with certain options using profiles, but sometimes a new version of Selenium driverserver or browser may not support the profiles.
36. UnableToSetCookieException: Occurs if a driver is unable to set a cookie.
37. UnexpectedAlertPresentException: This Selenium exception happens when there is the appearance of an unexpected alert.
38. UnexpectedTagNameException: Happens if a support class did not get a web element as expected.
39. UnhandledAlertException: It happens when there is an alert, but WebDriver is unable to perform Alert operation.
40. UnknownMethodException: Thrown when the requested command matching with a known URL but not matching with a methodology for that URL.
41. UnreachableBrowserException: This Selenium exception happens if the browser is unable to be opened or have crashed because of some reasons.
42. UnsupportedCommandException: Occurs when remote WebDriver does not send valid command as expected.
43. WebDriverException: This takes place when the WebDriver is performing the action right after you close the browser.
Q17. Explain Null pointer Exception ?

Ans: Java NullPointerException is an unchecked exception and extends RuntimeExceptionNullPointerException doesn’t force us to use catch block to handle it. This exception is very much like a nightmare for most of java developer community. They usually pop up when we least expect them.


1. Why NullPointerException occur in the code

NullPointerException is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null‘. A example java program which throws null pointer exception.

package com.howtodoinjava.demo.npe;


public class SampleNPE 
{
   public static void main(String[] args) 
   {
      String s = null;
      System.out.println( s.toString() );   // 's' is un-initialized and is null
   }
}

2. Common places where Java NullPointerException usually occur

Well, NullPointerException can occur anywhere in the code for various reasons but I have prepared list of most frequent places based on my experience.

Invoking methods on an object which is not initialized

Parameters passed in a method are null
Calling toString() method on object which is null
Comparing object properties in if block without checking null equality
Incorrect configuration for frameworks like spring which works on dependency injection
Using synchronized on an object which is null
Chained statements i.e. multiple method calls in a single statement
This is not an exhaustive list. There are several other places and reasons also. If you can recall any such other, please leave a comment. it will help others (beginners) also.


3. Best ways to avoid Java NullPointerException

3.1. Ternary Operator
This operator results to the value on the left hand side if not null else right hand side is evaluated. It has syntax like :

boolean expression ? value1 : value2;

If expression is evaluated as true then entire expression returns value1 otherwise value2. Its more like if-else construct but it is more effective and expressive. To prevent NullPointerException (NPE) , use this operator like below code:

String str = (param == null) ? "NA" : param;

3.2. Use apache commons StringUtils for String operations
Apache commons lang is a collection of several utility classes for various king of operation. One of them is StringUtils.java. Use StringUtils.isNotEmpty() for verifying if string passed as parameter is null or empty string. If it is not null or  empty; then use it further.

Other similar methods are StringUtils. IsEmpty(), and StringUtils.equals(). They claim in their javadocs that if StringUtils.isNotBlank() throws an NPE, then there is a bug in the API.


if (StringUtils.isNotEmpty(obj.getvalue())){

    String s = obj.getvalue();
    ....

}


Q18. I have to add 3 different kinds of products to cart i.e. 3 different urls, 3 different xpath for add to cart button so how will you write the code ? How will you reduce the length of code ?