can't print string and boolean value together in java

前端 未结 2 888
忘掉有多难
忘掉有多难 2021-01-29 12:43
public class Main
{
    public static void main(String[] args) {
        final String man1=\"All man are created equal:27\";
        final String man2=\"All man are crea         


        
2条回答
  •  离开以前
    2021-01-29 13:38

    Because of Operator Precedence

    == is below +, so first it will evaluate the string concatenation (+) and then their equality (==)

    The order will be:

    1. +: "All man are created equal:" + man1 => "All man are created equal:All man are created equal:27"
    2. ==: "All man are created equal:All man are created equal:27" == man2 => false
    3. System.out.println(false)

    Bonus use equals to compare strings (objects)

    public static void main(String[] args) {
        final String man1 = "All man are created equal:28";
        final String man2 = "All man are created equal:" + man1.length();
    
        System.out.println(("All man are created equal:" + man1) == man2);
        System.out.println("All man are created equal:" + (man1 == man2));
        System.out.println("All man are created equal:" + man1.equals(man2));
    }
    

    Output

    false
    All man are created equal:false
    All man are created equal:true
    

提交回复
热议问题