Need an explanation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Need an explanation

public class Program { public static void main(String[] args) { String a = "a"; String b = "b"; String c = a + b; String d = "ab"; if (c==d) { System.out.println(1); } else { System.out.println(0); } } } Output: 0 Why?

26th Oct 2018, 1:41 PM
IntelliJr
3 Answers
+ 4
Operator == in Java compares objects, but you need to compare just values of this objects. So to get correct result use .equals() method of String.
26th Oct 2018, 2:30 PM
Dmytro
+ 3
== is used in java for reference comparsion. c and d in your code are different references.
27th Oct 2018, 5:16 PM
Sharofiddin
Sharofiddin - avatar
+ 1
you need to compare strings using .equals()
27th Oct 2018, 10:27 PM
Ana Maludze
Ana Maludze - avatar