0

What is the difference between these declarations -

String[] names = {"Max", "Sam", "Ram"};

and

String[] names = new String[]{"Max", "Sam", "Ram"};
  • *"Is it related to one being mutable and the other being immutable?"* no. – Timothy Truckle Feb 06 '17 at 07:14
  • Possible duplicate of [What is the difference between "text" and new String("text")?](http://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext) – BudwiseЯ Feb 06 '17 at 07:15
  • 2
    The link which @budwiser have given is way wrong! you have string arrays not string constructor! – yaser eftekhari Feb 06 '17 at 07:21
  • 1
    Possible duplicate of [difference between these 2 ways of initializing an simple array](http://stackoverflow.com/questions/19658624/difference-between-these-2-ways-of-initializing-an-simple-array) – Dana Feb 06 '17 at 07:26
  • @yasereftekhari That's true. My bad. – BudwiseЯ Feb 06 '17 at 07:32

2 Answers2

1

There is no difference between the two. The first one is just more readable and with less typing.

yaser eftekhari
  • 235
  • 1
  • 6
0

There is no difference at all. Both objects are immutable, because they cant be changed after declaration.

String[] names = {"Max", "Sam", "Ram"};

String[] names = new String[]{"Max", "Sam", "Ram"};

In first variant java machine implicitly adds those part:

new String[]

So the both ways are allowed.