Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error with simple code [duplicate]

Tags:

java

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
...
like image 805
andy007 Avatar asked Sep 03 '25 05:09

andy007


1 Answers

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.

like image 167
Jean-François Fabre Avatar answered Sep 04 '25 19:09

Jean-François Fabre