0
Why the first one returns false???
public class Program { public static void main(String[] args) { String a =new String ("Morteza"); String b =new String ("Morteza"); System .out.println(a==b); System .out.println (a.equals(b)); } }
8 odpowiedzi
+ 2
Morteza Mohammadi
You can understand better here
https://code.sololearn.com/cZms6c3vg2w3/?ref=app
+ 1
String is reference type. Here you have created two separate objects with same content but at different location on the heap memory.
'==' checks for the reference whereas 'equals' checks for the content it has.
+ 1
Morteza Mohammadi because here you are not creating an object using the 'new' keyword. Here both the Strings are stored in the String Constant Pool (SCP). The SCP cannot contain duplicates so when you create 'Morteza' it is assigned to 'a' but when you try creating 'b' with the same string then it only returns the reference of 'a'. So here 'a' and 'b' both point to the same reference which has a single value 'Morteza'.
Read about SCP, == and equals.
0
What if it was integer ? Same result?
0
Integer is a wrapper Class which is again of reference type so yes it will give the same output.
0
Ok .
Thanks alot.
0
This one both returns true!
public class Program
{
public static void main(String[] args) {
String a="Morteza";
String b="Morteza";
System .out.println (a==b);
System .out .println (a.equals(b));
}
}
0
Useful clear explanations. Thank you.