+ 2

Why does x.equals(y) throw an error in Java?

Why does this program throw an error? public class Program { public static void main(String[] args) { int x=5; int y=8; System.out.println(x.equals(y)); } }

28th Nov 2019, 4:38 PM
Konsel
Konsel - avatar
3 odpowiedzi
+ 5
Konsel equals() method is a method which is inherited from the Object class. int, char, double and so on are primitive datatypes. Here you can use == to compare them. But all of them have a wrapper class. int -> Integer char -> Character double -> Double and so on... You can do this: Integer x = 5; Integer y = 8; System.out.println (x.equals (y));
28th Nov 2019, 5:24 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Thank you very much! Sorry didn't realize that they wrote "Integer" instead of int... And thanks for the explanation! Now it works!
28th Nov 2019, 5:47 PM
Konsel
Konsel - avatar
+ 1
But according to tutorialspoint it is as well made for int, double,... https://www.tutorialspoint.com/java/number_equals.htm
28th Nov 2019, 4:56 PM
Konsel
Konsel - avatar