+ 1

== and .equals difference?

Sololearn told me to use == to test if something was equal to something. But a error happened so I asked chatgpt and it said I should use .equals? If(variable == (1)) is wrong! It was, if(variable.equals (1))

24th Jun 2025, 6:51 PM
Pou
3 Antworten
+ 4
== checks the equality of a reference in memory; equals() checks the equality of values. provide the complete code and task instruction.
24th Jun 2025, 7:05 PM
Lisa
Lisa - avatar
0
Be careful, if the variable is of type Object, such as String or Integer, then equals() is recommended. // try Integer x,y; x=128; y=128; System.out.println(x == y); x=127; y=127; System.out.println(x == y);
25th Jun 2025, 6:53 PM
zemiak
0
== compares the memory address .equals() compares its content For example, assume the user enters "a" as input ``` Scanner sc = new Scanner(System.in); String userInput = sc.nextLine(); if (userInput == "a"){ System.out.println("Doesn't print anything because this compares the addresses"); } if (userInput.equals("a"){ System.out.println("This prints because the contents are being compared and both are equal"); } ```
26th Jun 2025, 5:46 AM
Vaibhav
Vaibhav - avatar