简体   繁体   中英

Why can I pass a String and a StringBuilder references to the '+' opereator, but not other objects

I have a Person object.If I try to pass this object along with a reference to an Integer wrapper class to the '+' operator, I get an error because they arent of the same dataype. But if I have a String and a StringBuilder references. Each reference points to a valid value and I pass this to the + operator, it prints the concatenated value.My question is arent String and StringBuilder 2 DIFFERENT classes? (Just like Person and Integer), why am i not getting the compiler error in this case?

    public static void main(String[] args) {
        Double d1=new Double(23);
        Integer i1=new Integer(5);

      //  System.out.println(new Pers()+d1);//compiler error
        System.out.println(new StringBuilder("abc")+ new String("zyz"));
    }
}

I am trying to understand these strange things happening in the language and want to be a better programmer. Any help appreciated. Thanks!

The reason is that the string concatenation operator + kicks in only if atleast one of the operands is a CharSequence , which String and StringBuilder are. If there is no CharSequence , the attempt is to perform an actual addition.

When you give Pers and Double , the compiler is not able to guess that you want string concatenation. It is first trying to compute the value of the operation and then trying to convert to string.

So, "" + new Pers() + d1 will work.

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