0

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.

4
  • 3
    Could you post some code, please? Commented Apr 5, 2012 at 7:02
  • Why do u insert int to a String type array anyway ? Commented Apr 5, 2012 at 7:02
  • The problem is clear: Why do you insert integers into a String array? Call array[n][m]=String.valueOf(value). Commented Apr 5, 2012 at 7:03
  • You definitely need to post how you insert the 5 into the array. arrayName[1][0] = 5; does not work. Neither does arrayName[1][0] = new Integer(5);. Commented Apr 5, 2012 at 7:20

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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]);

1 Comment

Thanks pal. Just what I needed. Appreciate it.
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.