title: Checking if string from database is utf-8 encoded in Java
body: <p>For 2 days now, I've been searching for ways to check if a value from the database is utf-8 encoded or not in Java. So far, I've read that strings in Java are using unicode (utf-16) encoding. I've tried following the suggested answer from <a href="https://stackoverflow.com/questions/28890907/implement-a-function-to-check-if-a-string-byte-array-follows-utf-8-format">here</a> and <a href="https://stackoverflow.com/questions/21866231/checking-if-a-string-is-utf-8-compatible-for-mysql">here</a> but neither seem to work properly. The first one always returns false while the second one would always return true.</p>
  
  <p>An example of strings I try to check are as follows wherein everything except the last string is utf8 encoded: </p>
  
  <blockquote>
    <p>ABCDEF, ｋａｔａｋａｎａ, カタカナ and �K�{�`�F�b�N�G���[</p>
  </blockquote>
  
  <p>One idea that I've been trying is to get the bytes of the string using utf-8 encoding then also get the bytes of the string using the default encoding then compare like so:</p>
  
  <pre><code>byte[] utf8byte = str.getBytes("UTF-8");
  byte[] bytes = str.getBytes();
  if(utf8byte.length == bytes.length) {
     return true;
  }
  </code></pre>
  
  <p>However given this logic, only the first string would return true. From my understanding, this is because not all characters use only 1 byte.</p>
  
  <p>So what is the best approach you can suggest to check whether a string from the database is utf-8 encoded or not? I'd really appreciate any idea. Thanks in advanced.</p>