Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between String s = new String(s.getBytes("UTF-8"),"UTF-8"); and String s = new String(s.getBytes(),"UTF-8");

Tags:

java

What is difference between

String(s.getBytes("UTF-8"),"UTF-8"); 

and

String(s.getBytes(),"UTF-8");

With first code example some of the special characters are getting decoded why and what is the difference?

And will impact anything if I use double decoding with UTF-8 ?

like image 709
Jala Sureshreddy Avatar asked Feb 12 '26 06:02

Jala Sureshreddy


1 Answers

From the javadoc:

For getBytes():

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Whereas, getBytes(Charset) says:

Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

So the second version allows you to take full control, the first call relies on that platform default charset.

That is all there is to this.

For that "platform default", see here for example. And note that people are asking to make the default to simply be UTF-8 across the board (see here).

like image 96
GhostCat Avatar answered Feb 17 '26 23:02

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!