java byte []b = (i+"").getBytes()
where i
is int
int i = 8;
byte []b = (i+"").getBytes();
I have seen this lines of code and cant understand what is the meaning of (i+"") thing.
java byte []b = (i+"").getBytes()
where i
is int
int i = 8;
byte []b = (i+"").getBytes();
I have seen this lines of code and cant understand what is the meaning of (i+"") thing.
i + ""
demonstrate that String concatenation with int
.
If you expand that a bit. It's equals to
String s = i+"";
byte []b = s.getBytes();
However that's almost a hack to do so. Do not prefer concatenation unless you really need it.
Use overloadded method valueOf(int i)
instead.
byte []b = String.valueOf(i).getBytes();
That gives you more readability and clean.
You want to get bytes
from the String
representation of an int
value.
So you need a String
.
You convert the int
to a String
by concatenating the int
value with a empty String
that produces a String
and then you can invoke String.getBytes()
to encode the String
into a byte array.
15.18.1. String Concatenation Operator +
if only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
A more efficient and elegant way would be :
byte[] b = String.valueOf(i).getBytes();
(i + "")
It's just a way to convert an int to a String, it's equivalent to :
String.valueOf(i)