Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Object. Clarification needed

Say i have the following line in my program:

jobSetupErrors.append("abc");

In the case above where jobSetupErrors is a StringBuilder(), what i see happen is:

  1. New String Object is created and assigned value "abc"
  2. value of that String object is assigned to the existing StringBuilder object

If that is correct, and I add 1 more line ...

jobSetupErrors.append("abc");
logger.info("abc");

In the above example are we creating String object separately 2 times?

If so, would it be more proper to do something like this?

String a = "abc";
jobSetupErrors.append(a);
logger.info(a);

Is this a better approach? Please advise

like image 941
James Raitsev Avatar asked Dec 18 '22 00:12

James Raitsev


1 Answers

In the above example are we creating String object separately 2 times?

No, because in Java String literals (anything in double-quotes) are interned. What this means is that both of those lines are referring to the same String, so no further optimization is necessary.

In your second example, you are only creating an extra reference to the same String, but this is what Java has already done for you by placing a reference to it in something called the string pool. This happens the first time it sees "abc"; the second time, it checks the pool and finds that "abc" already exists, so it is replaced with the same reference as the first one.

See http://en.wikipedia.org/wiki/String_interning for more information on String interning.

like image 157
danben Avatar answered Dec 19 '22 14:12

danben