Java printing a String containing an integer

Harish Raj picture Harish Raj · Nov 18, 2012 · Viewed 66k times · Source

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.

Answer

Óscar López picture Óscar López · Nov 18, 2012

Try this:

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

Where %n is a newline