Why doesn't my equality comparison using = (a single equals) work correctly in Java?

梦想的初衷 提交于 2019-11-28 13:00:15

问题


I have a syntax error in the following line. However I can't understand what is the reason of this error.

if (address1.compareTo(address2) = 1)
        System.out.println(address1 + " is greater than " + address2);

What I want to achieve is printing proper message if and only if compareTo returns 1.


回答1:


You should compare (==) instead of assigning (=). It can be very dangerous! To avoid such situations you can use Yoda notation so instead of comparing

address1.compareTo(address2) == 1

You can compare:

1 == address1.compareTo(address2)

In case of missing =, there will be comparation error.

In your case, it would be better to compare:

address1.compareTo(address2) > 0



来源:https://stackoverflow.com/questions/39385382/why-doesnt-my-equality-comparison-using-a-single-equals-work-correctly-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!