This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

declare array in java  RSS feed

 
Chris Yates
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why is this wrong in java?
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you are declaring the array, not initializing it. You simply say that models is a String array with String[], then initialize it to three elements with new String[3].
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer to initialise and fill the array in one fell swoop. That will get rid of the naughty nulls which otherwise would fill the array:-
String[] words = {"Campbell", "is", "brilliant"};
Remember that unless you mark the variable final, you cna always re‑assign it to another array, and you can always re‑assign each element because arrays are always mutable.
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, somebody wrote:. . .
String[] words = {"Campbell", "is", "brilliant"};
. . .
words[] = new String[]{"Nobody", "will", "believe", "a", "word", "of", "this"};
 
Joshua Daniels
Greenhorn
Posts: 11
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

For primitive types:


For classes, for example String, it's the same:
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Do you know when you have to write new XYZ[]{...} and when you can write {...} without new XYZ[]?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!