• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the best way to create a String  RSS feed

 
Ranch Hand
Posts: 62
Java Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Experts !

I came across one exercise in my book, which put me in difficulty. it said :

To create the string "Welcome to Java" you can use
1. String s = "test"; or

2.String s = new String("test");

Which one is better ? Why ?

I was thinking that the correct answer could be option 1. because in case that there will be another sting created like "test" , the JVM can take advantage of interned strings to improve efficiency and save memory.

What do you think ?

Thank you very much !

Kind regards,
marius
 
Bartender
Posts: 563
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're right. The only detail I'd add to your explanation is that the 2nd method ALWAYS creates a new String object. In the book, Effective Java, (2nd Edition), by Joshua Block, Item 5 is "Avoid creating unnecessary objects," and the author says to not use the second method when creating Strings or other immutable objects which could be reused.
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you put something like "this" in your code, the compiler tells the machine to put an String in a bag so it can be accessed anywhere "this" is written.



In this code, only one object is in memory, but 3 pointers to that object exist.

Your second option creates a copy of that string.
 
Marius Constantin
Ranch Hand
Posts: 62
Java Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very very much for you help guys !
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think option 1 is better,because the jvm has a constant pool .
 
Ranch Hand
Posts: 36
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think if you go for the first option then you can utilize the facility of String pooling in which only one String object is created in the pool and is reused according to the need but if you want to have the separate String Object then go for the second option, and also you can override the default functionality for your option one and for that you need to pass the arguments to the JVM.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!