Can
Can

Reputation: 4726

[Java]Null value in String Array when int inserted

I'm declaring a String array of [2][5]. Up until that point everything is fine. I can insert things into the array.

But when I insert an integer value into the array, 'null' keyword is automatically added before that int value.

So let's say I inserted 5 into arrayName[1][0]. When I print it afterwards I get 'null5'. Which is weird.

What exactly you guys think the problem is. Thanks, C@N.

Upvotes: 0

Views: 1050

Answers (3)

kundan bora
kundan bora

Reputation: 3889

if you are using any String variable let say myString (as a instance variable having default value null) and doing someting like this -

int i=5;
myString = myString+i;

because you are not initializing String mystring it get default value null and add up with i.

This may be one of the situation.

Upvotes: 0

daveb
daveb

Reputation: 76181

If you're using += to add items, then I think this could happen. Use String.valueOf()

Upvotes: 4

barsju
barsju

Reputation: 4446

The only way I can see this happening is if you use +=:

String[] a = new String[1];
a[0] += 1;
System.out.println(a[0]);

Cause if you just use a[0] = 1; you would get compile error. The reason you get null5 is because you are concatenating the string "null" with 5:

a[0] = (String) null + 1

So the question is what are you trying to achieve? Simply setting the value or adding to it?

If you just want to set it use:

String[] a = new String[1];
a[0] = Integer.toString(1);
System.out.println(a[0]);

If you do want to append to it:

String[] a = new String[1];
if (a[0] == null) {
    a[0] = Integer.toString(1);
} else {
    a[0] += 1;
}
System.out.println(a[0]);

Upvotes: 1

Related Questions