Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not instantiate a string object with a constructor?

Tags:

java

In Java, apparently, String s = "foo" is preferred over String s = new String("foo").

Why? Isn't a new string object created in both cases? Why would the first case preclude calling a constructor?

like image 927
dangerChihuahua007 Avatar asked Jun 23 '12 23:06

dangerChihuahua007


1 Answers

Why?

Because the second approach results in two string objects (the original due to the string literal, plus an explicit copy).

like image 50
Oliver Charlesworth Avatar answered Oct 24 '22 11:10

Oliver Charlesworth