简体   繁体   中英

Java String generation at compile time or runtime

Given this code:

if(somecondition) {
    String one = "one";
    //print one;
}

This string will only be generated when that condition is true?

Appreciate any help.

Edit:

With String pooling, is it safe to say that String one will be added to the pool regardless of a condition.

So, if a variable needs to be resolved from an object, what will happen?

Say,

String hello = "Hello Mr " + user.firstName();

How will this be added to String pool? And when it does get added to String pool, it will not create new String literals right (unless user.firstName() changes).

The string is generated at the time you typed it; but, for that answer to make sense, we need to walk it's life through the transformations in the build and launch of the application.

  1. First you typed it into the *.java file.
  2. Then the compiler copied it into the *.class file as part of the constant pool entries.
  3. Then the program was run, and the class was requested, which triggered the class loader to copy the file from disk to RAM, triggering a object meta-data entry being created to wrap the constant in the constant pool.

So, there's multiple places where it could be "created" depending on your definition of which kind of "creation" you wish to use.

Now, in your first example, the String object isn't realized when you use the string, but when you use the *.class file. However, it's not reference by the running program until you enter the method.

Finally, with String pooling, every time a string is about to be created, the existing pool of strings is searched, and if a matching entry is found, the matching entry is used instead of creating a new string. This reduces the number of strings in a runtime, at the cost of a lot of string searching.

Due to the details of your code, you have three different strings that are eligible for pooling ("Hello Mr ", the value of user.firstName() , and the string combining them both). "Hello Mr " would be pooled with the class loading (assuming pooling is being done). The value of user.firstName() would have happened when the value for the return was originally created. The resulting combined string would be pooled just before the assignment (or reference from the pool, if it already exists in the pool).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM