1

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.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Raj
  • 173
  • 2
  • 8

3 Answers3

3

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

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();
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 3
    "Getting the bytes from an int value" is a pretty ill-defined description of what's going on: you're not getting the 4-byte representation of the int, which is one interpretation of that. You're getting the ASCII value for each of the characters of the string representation of the int in base 10. – Andy Turner Jan 02 '18 at 09:00
  • @Andy Turner, Right. It was not correctly formulated. I Updated – davidxxx Jan 02 '18 at 09:06
1

(i + "") It's just a way to convert an int to a String, it's equivalent to :

String.valueOf(i)
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140