Java printing a String containing an integer

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

    Try this:

    System.out.printf("M%d%n", number+1);
    

    Where %n is a newline

    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2021-01-02 03:28

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

    Here You are using + as a concatanation Operator as Its in the println() method.

    To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:

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

    0 讨论(0)
  • 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"
    0 讨论(0)
  • 2021-01-02 03:30

    If you perform + operation after a string, it takes it as concatenation:

    "d" + 1 + 1     // = d11 
    

    Whereas if you do the vice versa + is taken as addition:

    1 + 1 + "d"     // = 2d 
    
    0 讨论(0)
  • 2021-01-02 03:31

    Try

    System.out.println("M"+(number+1));
    
    0 讨论(0)
提交回复
热议问题