Macosx Iam
Macosx Iam

Reputation: 377

Null pointer exception when testing in Java

public boolean isItMyName(String name)
    {    
       name = fullname.substring(0,fullname.indexOf(' '));
       ...
    }

Then my code goes on and on. When I run this, I get a null pointer exception and the error is pointing to this line.

I also created a JUnit tester, where it tests whether the input is true or false.

Name myName = new Name();
assertEquals(false, myName.isItMyName("Troll");

It also gives me a null pointer exception at assertEquals(false, myName.isItMyName("Troll"));

I'm at my wit's end. How do I fix this?

@ Greg Hewgill:

In my Name class, I do this:

public class Name(String n)
{
  name = n;
}

But in my main method, I pass in the string: Name myName = new Name("Johnathy");

So string isn't null.

FULLNAME:

public class EmailAddress {
private String address;



public EmailAddress(String a)
{
  address = a;

}

public String toString()
{
    return address;
}

Upvotes: 1

Views: 3959

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503459

Well you're ignoring your parameter... you're assigning a new value to name in the first line. That means your method is almost certainly broken to start with.

Then consider where fullname (which I assume is an instance variable) is going to come from. Unless you're setting it to a value within your parameterless constructor, it's going to be null by default. Is that really what you want?

I suggest you change your Name class to only have constructors taking name parameters, and that you validate that they're not null. That way you can never have an invalid Name object, where the full name is null.

EDIT: Now you've posted more code, look at your parameterless constructor and the setName method:

public Name()
{
   setName(fullname);     
}

public void setName(String n)
{
    fullname = n;
}

That means your parameterless constructor is equivalent to:

public Name()
{
   fullname = fullname;
}

... i.e. a no-op. fullname will be null, hence the exception.

My advice is to get rid of the parameterless constructor entirely, and make the other one validate the parameter.

Upvotes: 3

fjlj
fjlj

Reputation: 146

if no ' ' index is found in the full name wouldnt it return -1 thus causing substring to grab 0,-1 which is null... perhaps toss it in an if and skip that step if the index is < 0... and shouldnt your parameter that is incomming be fullname

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994619

   name = fullname.substring(0,fullname.indexOf(' '));

If you get a null pointer exception on that line, then fullname is null. It's really the only possibility.

Upvotes: 3

corsiKa
corsiKa

Reputation: 82589

Without more code I can't say for sure, but I bet you fullname is null and never set to anything.

Upvotes: 2

Related Questions