I am writing an app for J2ME devices and pretty much care about unnecessary String creation. As working with Strings is built-in, i.e. it is not necessary to create them explicitly, I am not sure if I understand it right.
For instance returning a String (just by using the double quotes) creates the string when it is being returned, i.e. if I have several return statements returning different Strings, only one of the would be created. Is that right?
Also when using Strings for printing messages with Exceptions, these Strings never get created, if the Exception doesn't get thrown, right?
Sorry to bother you with such a newbie question.
Here is our string. String strTime = "20:15:40"; Now, use the DateFormat to set the format for date.
There are two ways to create a String object: By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”.
Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.
The answer is: 2 String objects are created. str and str2 both refer to the same object. str3 has the same content but using new forced the creation of a new, distinct, object.
I'm not at all sure about the answers you've received so far. If you're just returning a string literal, e.g.
return "foo";
then those values are embedded into the class file. The JVM makes sure that only one instance of that string is ever created (from the literal) - but I don't think there's any guarantee that it won't create strings for all the constants in a class when the class itself is loaded.
Then again, because the string will only be created once (per string constant) it's unlikely to be an issue.
Now, if your code is actually more like this:
return "foo" + new Date();
then that is dynamically creating a string - but it will only be created if the return statement is actually hit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With