2

i have a question regarding java int array initialization. i want to set the widths base on conditions, but when i try to compile it says malformed declaration. Anything wrong with my array initialization?

int []widths;
if(condition 1)
{
   widths = {1,4,5,3};
} 

if(condition 2)
{
   widths = {1,9,5,3,2};
}  

method1.setWidth(widths );  //method that take int array as argument.

2 Answers 2

3

widths = {1,4,5,3} is only valid when it's part of the declaration of the array variable.

change your code to :

int[] widths;
if(condition 1) {
   widths = new int[] {1,4,5,3};
} 

if(condition 2) {
   widths = new int[] {1,9,5,3,2};
}  

method1.setWidth(widths);

You should also consider giving the widths array a default value, in case neither of your two conditions is true, since your code wouldn't pass compilation otherwise.

It can be something like this :

int[] widths = null;
if(condition 1) {
   widths = new int[] {1,4,5,3};
} 

if(condition 2) {
   widths = new int[] {1,9,5,3,2};
}  

if (widths != null) {
    method1.setWidth(widths);
}
Sign up to request clarification or add additional context in comments.

2 Comments

the method1.setWidth(widths); shows Error(509,29): variable widths might not have been initialized
In Java8 you can do Optional<int[]> widths = Optional.empty();, later widths = Optional.of(new int[] {1,9,5,3,2}); and at the end you just do widths.ifPresent(method1::setWidth).
0

The answer given by @Eran was the correct one. But, if you still need an array and you not know in advance how many element the array will contain, try to get a look at List: <T> T[] toArray(T[] a) method.

This way, your example should become:

List<Integer> list = new ArrayList<Integer>();
if (condition 1) {
   // Fullfil the list in some way
} else if (condition 2) {
   // Fullfil the list in some other way
} 
// The array given in input to toArray is needed cause type erasure of 
// generics at compile time.
method1.setWidth(list.toArray(new Integer[list.size()]));

Clearly, you can't use array of primitive types this way.

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.