Why the first one returns false??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)); } }

10th Jan 2021, 11:00 AM
Morteza Mohammadi
Morteza Mohammadi - avatar
8 Answers
10th Jan 2021, 1:32 PM
A͢J
A͢J - avatar
+ 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.
10th Jan 2021, 11:06 AM
Avinesh
Avinesh - avatar
+ 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.
10th Jan 2021, 11:23 AM
Avinesh
Avinesh - avatar
0
What if it was integer ? Same result?
10th Jan 2021, 11:08 AM
Morteza Mohammadi
Morteza Mohammadi - avatar
0
Integer is a wrapper Class which is again of reference type so yes it will give the same output.
10th Jan 2021, 11:09 AM
Avinesh
Avinesh - avatar
0
Ok . Thanks alot.
10th Jan 2021, 11:10 AM
Morteza Mohammadi
Morteza Mohammadi - avatar
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)); } }
10th Jan 2021, 11:15 AM
Morteza Mohammadi
Morteza Mohammadi - avatar
0
Useful clear explanations. Thank you.
10th Jan 2021, 11:25 AM
Morteza Mohammadi
Morteza Mohammadi - avatar