Reputation: 13
Is Option 1 and 2 same do I need to create String inputString I making udpServer so I was wonder if it is okay do like option 2 or are they disadvantage that way.
Option 1
String inputString = "Hello World!";
byte[] byteArrray = inputString.getBytes();
Option 2
byte[] byteArrray = "Hello World!".getBytes();
Upvotes: 0
Views: 40
Reputation: 102795
They are the same. As in, byte for byte same bytecode other than the linenumber table. But, they are both extremely suspect - getBytes()
will use platform default encoding, and you really don't want that. It's somewhat unlikely to matter as your string in this example is all ASCII, but your platform default could conceivably be UTF-16.
You need to specify what encoding is used. The go-to answer tends to be UTF8. Thus:
someString.getBytes(StandardCharsets.UTF8)
is what you're looking for, and to go from a byte array back to a string, new String(byteArr, StandardCharsets.UTF8)
.
Upvotes: 3