Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

declare array in java  RSS feed

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


Why is this wrong in java?
 
Sheriff
Posts: 4865
136
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].
 
Marshal
Posts: 59092
180
  • 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: 59092
180
  • 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"};
 
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: 59092
180
  • 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[]?
 
Screaming fools! It's nothing more than a tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!