Java printing a String containing an integer
Asked Answered
H

9

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.

Haemic answered 18/11, 2012 at 19:41 Comment(1)
you will need to do something like this: System.out.println("M"+(number+1))Phalanx
A
20

Try this:

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

Where %n is a newline

Asta answered 18/11, 2012 at 19:44 Comment(0)
L
13

Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.

System.out.println("M"+(number+1));
Liss answered 18/11, 2012 at 19:42 Comment(0)
S
6

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"
Stupidity answered 18/11, 2012 at 19:49 Comment(0)
S
3

Try

System.out.println("M"+(number+1));
Scutage answered 18/11, 2012 at 19:42 Comment(0)
H
2

Try this:

System.out.println("M"+(number+1));
Hexahydrate answered 18/11, 2012 at 19:43 Comment(1)
Oh, what a dump I am! Thanks a lot, Zaheer.Haemic
B
2

A cleaner way to separate data from invariants:

int number=1;
System.out.printf("M%d%n",number+1);
Buckeye answered 18/11, 2012 at 19:46 Comment(0)
G
2
  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"

Ghastly answered 18/11, 2012 at 19:46 Comment(0)
W
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));

Wellrounded answered 18/11, 2012 at 19:47 Comment(0)
S
0

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 
Safelight answered 23/12, 2018 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.