Ramki
Ramki

Reputation: 199

usage of direct strings vs creating a variable in local method

I'm trying to understand is there any difference (performance/best programming practice..etc) between using a direct string vs creating a temporary variable in side a method and used it exactly once. Here is an example

Class Sample {
   public boolean compareString(String str){
     String test = "Test";
     return test.equalsIgnoreCase(str);
           vs
     return "Test".equalsIgnoreCase(str);
   }
}

In my opinion, both are the same. Instead of creating a variable, one can directly use it. Please let me if there are any other differences and which one is preferred?

Upvotes: 0

Views: 696

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

No difference, because string literals (like "one", "two") are stored into String Pool and reused.

From your example:

String test = "Test";
// "Test" - string literal is stored in the StringPool
// test - reference to string literal "Test" from StringPool

return test.equalsIgnoreCase(str);
return "Test".equalsIgnoreCase(str);
// in both cases you use the same string literal stored in StringPool

P.S.

String str = new String("abc");
// "abc" - string literal is created (or reused) and stored in StringPool
// new String() - string object is stored in heap and contains (separate copy) of string literal "abc"
// str - reference to the string object in heap

In case you want to get a refernce to the string from StringPool:

String str1 = str.intern();
// str1 - reference to the string literal from the String Pool

Upvotes: 2

Ramki
Ramki

Reputation: 199

I was looking for any differences (peformance/programming practice.. etc) between 2 approaches and found that there are no differences.

2nd approach is better in best programming practice (it make sense to create a temporary variables if it is used in other places with in that method).

Upvotes: 0

WJS
WJS

Reputation: 40057

Here is the difference.

String str = null;
            
String test = "Test";
boolean a =  test.equalsIgnoreCase(str);
            
boolean b =  "Test".equalsIgnoreCase(str);

The bytecode

2  ldc <String "Test"> [16] // push the constant on stack
4  astore_2 [test]  // stores in internal list
5  aload_2 [test]   // retrieves constant, pushes on stack
6  aload_1 [str]    // target of comparison
7  invokevirtual java.lang.String.equalsIgnoreCase(java.lang.String) : boolean [18]
10  istore_3 [a]     // store boolean result

11  ldc <String "Test"> [16] // push the constant on stack
13  aload_1 [str]    // target of comparison
14  invokevirtual java.lang.String.equalsIgnoreCase(java.lang.String) : boolean [18]
17  istore 4 [b]     // store boolean result

Upvotes: 1

Related Questions