I have a byte:
byte STX = 0x02;
Printing it as it is with printf
returns 0x02
which is what I want:
System.out.printf("0x%02X", STX);
However, I want to concatenate it with strings like below or similar:
System.out.println("Found " + STX + " at " + i);
But it returns the integer value. How can I therefore print a byte and concatenate it with a string?
Unfortunately this is effectively a copy of an existing answer, which was downvoted... but as your comment now indicates that you'd welcome such an option...
You can use printf
to format your whole string:
System.out.printf("Found 0x%02X at %d%n", STX, i);
Here the 0x%02X
is the part you already know; the %d
is the format specifier for i
; the %n
is the platform-specific newline.
I find it clearer to use one style of formatting throughout a statement: either printf
/String.format
formatting or string concatenation, rather than a mixture of the two.
If you find yourself wanting the formatting without printing to the console, just use String.format
instead:
String text = String.format("Found 0x%02X at %d", STX, i);
(That's assuming you don't want the line separator in that case.)
See the Formatter
documentation for all the options in format strings.
See more on this question at Stackoverflow