6

How many string objects will be created in constant pool

 2 years ago
source link: https://www.codesd.com/item/how-many-string-objects-will-be-created-in-constant-pool.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How many string objects will be created in constant pool

advertisements

Consider following statement and log level is set to ERROR. Logging API being used is log4j. How many strings will be created given above information?

if (logger.isDebugEnabled()) {
    logger.debug("Executing SQL query [" + sql + "]");
}

Other question is

if (logger.isDebugEnabled()) {
     StringBuilder sBuilder = new StringBuilder("Executing SQL query [");
     sBuilder.append(sql);
     sBuilder.append("]");
     logger.debug(sBuilder.toString());
}

How many string will be created in above case ?

My question is will compiler create strings even if logger is not enabled for debug ?


logger.debug("Executing SQL query [" + sql + "]");

Two strings

"Executing SQL query [" 

"]"

created at compile time.

And then, in Runtime,

"Executing SQL query [" + sql + "]"

(+) operator JVM returns new StringBuilder(string...).toString() which creates a new String instance in heap memory.

Append operation will happen with StringBuilder.toString ,If debug enable.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK