0

Whats the difference between this :

String [] columns = new String []{KEY_ROWID, KEY_TITLE, KEY_DESC, KEY_TIME};

And This :

String [] columns={KEY_ROWID, KEY_TITLE, KEY_DESC, KEY_TIME};
1
  • No difference. Most people prefer the second one because is sort of shorthand. Commented Mar 17, 2014 at 18:58

3 Answers 3

1

None.

The latter version is a handy shortcut syntax that will only work in declaration statements, but the result is exactly the same.

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

Comments

0

The first line uses an array creation expression that contains an array initializer, and the second line contains just the array initializer. Here, they perform the same exact function -- create and initialize an array. But only one is only valid when declaring the array.

The array initializer is defined in the JLS, Section 10.6:

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10)

ArrayInitializer:
    { VariableInitializersopt ,opt }

VariableInitializers:
    VariableInitializer
    VariableInitializers , VariableInitializer

and Section 15.10 defines the array creation expression to require new SomeType[]:

An array creation expression is used to create new arrays (§10).

ArrayCreationExpression:
     new PrimitiveType DimExprs Dimsopt
     new ClassOrInterfaceType DimExprs Dimsopt
     new PrimitiveType Dims ArrayInitializer 
     new ClassOrInterfaceType Dims ArrayInitializer

DimExprs:
     DimExpr
     DimExprs DimExpr

DimExpr:
     [ Expression ]

Dims:
     [ ]
     Dims [ ]

So, you can omit the new SomeType[] part if it's part of the declaration of the array variable, but you must include it elsewhere, such as an assignment expression.

1 Comment

so complicating....im still a baby to this java thing. However, Thanks for going so indepth.
0

They produce the same instantiation (only usable in declarations) of the string array, no difference at all in the result obtained. However, I mostly choose the first one (just a personal preference).

EDIT: Sorry, I was typing while the 1st answer appeared.

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.