Java printing a String containing an integer

前端 未结 9 876
执笔经年
执笔经年 2021-01-02 02:54

I have a doubt which follows.

public static void main(String[] args) throws IOException{
  int number=1;
  System.out.println(\"M\"+number+1);
}
9条回答
  •  春和景丽
    2021-01-02 03:29

    It has to do with the precedence order in which java concatenates the String,

    Basically Java is saying

    • "M"+number = "M1"
    • "M1"+1 = "M11"

    You can overload the precedence just like you do with maths

    "M"+(number+1)
    

    This now reads

    • "M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"

提交回复
热议问题