lang.nullpointerexception while running the below code.

package aditi;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;

public class TestNG {

    public static WebDriver driverok ;

  public void main(){
    driverok.findElement(By.id("email")).sendKeys("[email protected]");
     System.out.println("login successfully");

  public void beforeMethod() {
      System.setProperty("webdriver.chrome.driver", "E:\\selenium\\chromedriver.exe\\");
        WebDriver driverok = new ChromeDriver();
      driverok.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

  public void afterMethod() {
  • 1
    There are numerous similar questions here. with answers.
    – Alexey R.
    Jun 9, 2018 at 22:22

1 Answer 1


On your beforeMethod, you are creating a local object:

WebDriver driverok = new ChromeDriver();

This object is alive during the beforeMethod, but sent to the garbage collect right after.

In the main method, you are referencing to the instance driverok object, which was never initialized (null by default). Therefore, when you try to call findElement on null, you get a NullPointerException.

Changing the beforeMethod to the following will initialize the instance property, making the main method work correctly:

this.driverok = new ChromeDriver();

See this answer to more information about this: https://stackoverflow.com/a/3728075/2252076

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.