Java printing a String containing an integer

前端 未结 9 899
执笔经年
执笔经年 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:26

      System.out.println("M"+number+1);
    

    String concatination in java works this way:

    if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String.

    try

     System.out.println("M"+(number+1));
    

    In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"

提交回复
热议问题