Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this String[] work in Java?

OK, this fails:

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        this.roles  = {"User"};
    }
}

This works:

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        String[] blah  = {"User"};
    }
}

Any information would be appreciated.

Thanks.

like image 202
cbmeeks Avatar asked Jun 26 '26 06:06

cbmeeks


2 Answers

Try

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        this.roles  = new String[]{"User"};
    }
}

the array initializer of type String[] foo = {"bar1", "bar2"}; can be used if only you have the declaration and initialization together. If you seperate the initialization from declaration, you cannot do {...}; you'll have to new String[]{...}

like image 85
Bala R Avatar answered Jun 28 '26 19:06

Bala R


Array initializers (the bit in braces) are only available at the point where you're declaring an array variable, or as part of an array creation expression of the form new ElementType[] initializer.

So this is fine:

// Variable declaration
String[] x = { "Blah" };

This isn't, because you have neither a declaration nor an array creation expression:

x = { "Blah" };

but this is fine again, as it's got an array creation expression:

x = new String[] { "Blah" };

The links above are to the relevant bits of the language specification.

like image 22
Jon Skeet Avatar answered Jun 28 '26 21:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!