java - assignment operator String object -
i new java programming. have read in book
string a="hello"; string b="hello"; system.out.println(a==b);
this should return false & b refer different instances of string objects.
bcoz assignments operator compares instances of objects still getting true.
using eclipse ide.
example in book goes this:
string s = "s"; string stoo = "s"; system.out.println(a == b); system.out.println(s == stoo);
that bit of code prints “false” s == stoo. that's because s , stoo references different instances of string object. so, though have same value, not equal in eyes of equality operators. also, s == “s” prints false, because string literal produces yet instance of string class.
name of book: java 7 absolute beginners
this optimisation called string pooling in compile-time constant strings (aka known identical at compile time) can set such same object in memory (saving space 1 of used types of object). or in words of docs;
"all literal strings , string-valued constant expressions interned."
note applies strings defined @ compile time, following print false.
string a="hello"; string b=new string("hello"); system.out.println(a==b); //prints false because new string forced
or
string a="hello"; string b1="he"; string b2="llo"; string b=b1+b2; system.out.println(a==b); //prints false because b wasn't know "hello" @ compile time not use string pooling
n.b. possible cause second snippet print true making b1 , b2 final, allowing b1+b2 known @ compile time. in need careful , treat string==string considerable respect, in vast majority of cases want string.equals(string) in behaviour not exist.
Comments
Post a Comment