In JAVA API why equality check using '==' rather than String.equals() method -


i going through api code found in java api

java.io.filepermission.getmask(string actions) {     int mask = none;      // null action valid?     if (actions == null) {         return mask;     }     // check against use of constants (used heavily within jdk)     if (actions == securityconstants.file_read_action) {         return read;     } else if (actions == securityconstants.file_write_action) {         return write;     } else if (actions == securityconstants.file_execute_action) {         return execute;     } else if (actions == securityconstants.file_delete_action) {         return delete;     } else if (actions == securityconstants.file_readlink_action) {         return readlink;     } .... .... ..... } 

can 1 tell me why have used '==' operator instead of .equlas() method. :?

it because of string interning. happens compiler interns string literals in memory @ compile time (this done save memory). when compare string literals ==, work because in same memory location.

i recommend read this answer, idea. here example (from answer) , explanation (mine):

1  // these 2 have same value 2  new string("test").equals("test") --> true 3    4  // ... not same object 5  new string("test") == "test" --> false 6    7  // ... neither these 8  new string("test") == new string("test") --> false 9   10 // ... these because literals interned  11 // compiler , refer same object 12 "test" == "test" --> true 13  14 // concatenation of string literals happens @ compile time, 15 // resulting in same object 16 "test" == "te" + "st" --> true 17  18 // .substring() invoked @ runtime, generating distinct objects 19 "test" == "!test".substring(1) --> false 

explanation:

why line 12 , 16 evaluate true? because of string interning. happens in these cases compiler interns string literals in memory @ compile time (this done save memory). in line 12 , 16 stringliterals beign compared in same memory location, comparison == operator returns true. however, not recommended unless want better performance (comparing memory addresses lot “cheaper” loop) , sure strings being compared interned literals.

remember those securityconstants strings.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -