Encode String to UTF-8 in Java

April 28, 2017

In this short post, we will discuss the String encoding.

1. How do I encode a string to UTF-8?

You cannot.  String objects in Java do not have an encoding. Though, that’s not accurate enough because it’s encoding is UTF-16, and it cannot be changed in any way.

2. Where is encoding then?

The only thing you can use is a byte[]. It doesn’t have any encoding but array PLUS encoding, can give you a string. In simple words: need the UTF-8 data? You need the byte[]! Let’s see how to do this:

First, we converted our String to byte[] using the getBytes() method which took one of the standard charsets as an argument. After that, we created another String object using UTF_8. This code will print:

 

Click here to add a comment

Leave a comment: