4

When I run this code I get the NullPointerException on line int length = origin.length();

If I run in the debug mode it stoped on the same line but in the variable tab the origin value is as it might be i.e. the value from the main method.

So why is NullPointerException there in runtime?

public static void main(String[] args) {

        String regexp = "(?:a)";
        Task t = new Task(regexp); // error
        t.process();

    }


class Task {

    private String origin;

    public Task() {
    }

    public Task(String origin) {
        this.origin = origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }

    public String getOrigin() {
        return origin;
    }

    int length = origin.length(); //NullPointerException
...
andy007
  • 907
  • 1
  • 15
  • 41

4 Answers4

3

origin is not initialized when you initialize your length variable. Set it to zero, and initialize origin like this:

private String origin = new String();

or the origin variable will be a null string before it is set through your setter.

And I would replace

int length = origin.length(); //NullPointerException

by public int get_length() { return origin.length(); }

so length property is always properly correlated to actual origin length.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Because of the lifecycle of Java objects: the length attribute is set before the code in the constructor is executed, so the origin attribute is still null.

Calculate the length in the constructor so solve that issue:

public Task (String o) {
    this.origin=o;
    this.length=this.origin.length();
}

And then update the setter:

public void setOrigin(String origin) {
    this.origin = origin;
    this.length=origin.length;
}

Or just create a getter for the length and don't store that value (best option, in my opinion):

int getLength() {
   this.origin.length();
}
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

The instance (and static) variables are initialized right after the (implicit or explicit) call to super(). So this is before you can assign anything to your String origin.

Robert van der Spek
  • 1,017
  • 3
  • 16
  • 37
0

Take care of initializing fields depending on different fields! JVM tries to initialize them before calling the constructor!

public static void main(String[] args) {

        String regexp = "(?:a)";
        Task t = new Task(regexp); // error
        t.process();

    }


class Task {

    private String origin;
    private int length;

    public Task() {
        //optional - depending on what you like/need
        origin = new String();
        length = 0;
    }

    public Task(String origin) {
        this.origin = origin;
        this.length = origin.length();
    }

    public void setOrigin(String origin) {
        this.origin = origin;
        this.length = origin.length(); 
    }

    public String getOrigin() {
        return origin;
    }

...
xenteros
  • 15,586
  • 12
  • 56
  • 91