简体   繁体   中英

can't print string and boolean value together in java

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

why only false is getting printed instead of the whole print statement.

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

The problem lies in this statement -

 System.out.print("All man are created equal:"+man1==man2); 

here a new string (say s1 ) is generated with the concatenation of All man are created equal: and man1 .
Now you have 2 references of string s1 and man1 .
Later these two string references - s1 and man2 are compared.

both references( s1 and man2 ) are different and you are getting false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM