understanding the java string with add operator

前端 未结 4 1876
轮回少年
轮回少年 2021-01-16 04:04

I am trying to understand how the compiler views the following print statements. It is simple yet a bit intriguing.

This prints the added value. Convincing enough.<

4条回答
  •  旧巷少年郎
    2021-01-16 04:33

    I also found this interesting. I haven't worked too much in java recently but I found out a little bit of info that might be helpful through playing with it.

    I think this has to do with automatic Type-casting that java does.

    System.out.println("1"+2+3);

    Prints 123 as you said. Since "1" is casted as string, Java assumes since the first one was a string, the ones following will be a string for concatenation unless otherwise noted

    Although, this result does print 15 when you define the type

    System.out.println("1" + (int)(2+3));

    In that case, it can complete the operation before concatenating.

    So I think java is assuming if the first one is a String, that the rest are going to be strings and to concatenate them.

    EDIT: you can see some info about automatic type-conversion on oracle's website here

提交回复
热议问题