Alex Rivera | Logout

Java printing a String containing an integer

Asked 2012-11-18T19:41:05.137
12

I have a doubt which follows.

public static void main(String[] args) throws IOException{
  int number=1;
  System.out.println("M"+number+1);
}

Output: M11

But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.

Requesting you to help me how to print it properly.

Edit
Report

1 Answer

2

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));

answered 2012-11-18T19:47:33.043

Your Answer