athresh
athresh

Reputation: 161

Initializing a specific index in string array with null

I have string a[]=new a[4];

How to initialize a[0] = null;?

I need to have the following values in my array: a,null,b,null

I do not want to initialize when I declare my string array itself.

Upvotes: 0

Views: 2457

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500375

You're using a to mean three different things - the array variable, a type, and a value within the array. That's clearly not going to work. However, you can do this:

String a = "hello";
String b = "there";

String[] array = { a, null, b, null };

or if you want to separate the declaration and initialization:

String[] array;

...

array = new String[] { a, null, b, null };

If you just create a new array, e.g.

String[] array = new String[4];

then all the element values will be null by default to start with, so you don't need to do anything else. You could do:

String[] array = new String[4];
array[0] = a;
array[2] = b;

If you need to set an element to null, you just do that in the obvious way:

array[0] = null;

Upvotes: 4

Related Questions