004 Conditionals In java JAVA中的条件句

For example:

//Test004.java

public class Test004 {
    public static void main(String[] args) {
        int a =8;
        int b =8;
        if(a==b){
            System.out.println("a is equal to b.");
        }
        else{
            System.out.println("a is not equal to b.");
        }

        /*
         * == and equals
         *The operator == works a bit different on objects than on primitives. 
         When we are using objects and want to check if they are equal, the 
         operator == wiil say if they are the same, if you want to check if 
         they are logically equal, you should use the equals method on the object. 
         For example:
        */

        String person_a=new String("gavin");
        String person_b=new String("gavin");
        String person_c=person_a;


        System.out.println(person_a==person_b);//这里会输因为false,
        //因为person_a和person_b不是一个对象,分配的物理空间的地址不一样

        System.out.println(person_a.equals(person_b));//这里会输出true,
        //因为person_a和persion_b的逻辑值一样,都是gavin

        System.out.println(person_a==person_c);//这里会输出true,
        //因为person_a和person_b实际上是同一个对象
    }

}

上述代码中的第6行中,a=b就是条件句。在java中,条件句返回的结果必须是boolean类型的值。

原文地址:https://www.cnblogs.com/tantanjishu/p/4868733.html