Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time of Strings Creation in Java

Tags:

java

string

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.

like image 977
Albus Dumbledore Avatar asked Aug 12 '10 09:08

Albus Dumbledore


People also ask

How do you find the time in a string?

Here is our string. String strTime = "20:15:40"; Now, use the DateFormat to set the format for date.

How are strings created in Java?

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”.

How long is a string in Java?

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.

How many string objects are created?

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.


1 Answers

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.

like image 140
Jon Skeet Avatar answered Sep 21 '22 17:09

Jon Skeet