I have the following code
public static void main(String... args) {
String s = "abc";
System.out.println(s.hashCode());
String s1 = " abc ";
System.out.println(s1.hashCode());
String s2 = s.trim();
System.out.println(s2.hashCode());
String s3 = s1.trim();
System.out.println(s3.hashCode());
System.out.println();
System.out.println(s == s1);
System.out.println(s == s2);
System.out.println(s == s3);
}
OP:
96354
32539678
96354
96354
false -- Correct
true -- This means s and s2 are references to the same String object "abc" .
false -- s3=s1.trim()... which means s3="abc" yet s==s3 fails.. If the above conditon were to be considered (s==s2 is true..) , this should also be true..
Why am i getting "false" when i check s==s3 ?..
The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".
strip() - Removes the white space from both, beginning and the end of string.
To trim leading and trailing whitespace from a string in JavaScript, you should use the String. prototype. trim() method. The trim() method removes leading and trailing whitespace characters, including tabs and newlines.
STRIP function - removes all leading and trailing blanks. TRIM function - removes all trailing blanks.
becuase s1.trim()
will return a new instance. Strings are immutable so every time a function applied on Strings then a new instance will be returned and You are using ==
which compares the instance equality
Edit: As suggested By Chris Hayes and R.J.
trim
is smart and returns this
if there's no whitespace to trim. So in second case you have ' abc ' white spaces so in this case it is not returning this
but a new instance of string.
source code of trim method
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
As you can see in your case(System.out.println(s == s2);
) this
is returned which is pointing to same reference which is why you get true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With