Can (a==1 && a==2 && a==3) evaluate to true in Java?

后端 未结 8 734
梦如初夏
梦如初夏 2020-11-29 15:01

We know it can in JavaScript.

But is it possible to print \"Success\" message on the condition given below in Java?

if (a==1 && a==2 &&am         


        
8条回答
  •  春和景丽
    2020-11-29 15:29

    Since this seems to be a follow-up of this JavaScript question, it’s worth noting that this trick and similar works in Java too:

    public class Q48383521 {
        public static void main(String[] args) {
            int aᅠ = 1;
            int ᅠ2 = 3;
            int a = 3;
            if(aᅠ==1 && a==ᅠ2 && a==3) {
                System.out.println("success");
            }
        }
    }
    

    On Ideone


    But note that this isn’t the worst thing you could do with Unicode. Using white-space or control characters that are valid identifiers parts or using different letters that look the same still creates identifiers that are different and can be spotted, e.g. when doing a text search.

    But this program

    public class Q48383521 {
        public static void main(String[] args) {
            int ä = 1;
            int ä = 2;
            if(ä == 1 && ä == 2) {
                System.out.println("success");
            }
        }
    }
    

    uses two identifiers that are the same, at least from the Unicode point of view. They just use different ways to encode the same character ä, using U+00E4 and U+0061 U+0308.

    On Ideone

    So depending on the tool you’re using, they may not only look the same, Unicode enabled text tools may not even report any difference, always finding both when searching. You may even have the problem that the different representations get lost when copying the source code to someone else, perhaps trying to get help for the “weird behavior”, making it non-reproducible for the helper.

提交回复
热议问题