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 internsstring
literals in memory @ compile time (this done save memory). in line 12 , 16string
literals beign compared in same memory location, comparison==
operator returnstrue
. however, not recommended unless want better performance (comparing memory addresses lot “cheaper” loop) , surestring
s being compared interned literals.
remember those securityconstants
strings.
Comments
Post a Comment