0

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.

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Since the original question is marked with the tag "Java", the 'string' in your code snippets should be 'String'. :-)

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.