title: Which encoding does Java uses UTF-8 or UTF-16?
body: <p>I've already read the following posts:</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/9699071/what-is-the-javas-internal-represention-for-string-modified-utf-8-utf-16">What is the Java&#39;s internal represention for String? Modified UTF-8? UTF-16?</a></li>
  <li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/api/java/lang/String.html</a></li>
  </ol>
  
  <p>Now consider the code given below:</p>
  
  <pre><code>public static void main(String[] args) {
      printCharacterDetails("最");
  }
  
  public static void printCharacterDetails(String character){
      System.out.println("Unicode Value for "+character+"="+Integer.toHexString(character.codePointAt(0)));
      byte[] bytes = character.getBytes();
      System.out.println("The UTF-8 Character="+character+"  | Default: Number of Bytes="+bytes.length);
      String stringUTF16 = new String(bytes, StandardCharsets.UTF_16);
      System.out.println("The corresponding UTF-16 Character="+stringUTF16+"  | UTF-16: Number of Bytes="+stringUTF16.getBytes().length);
      System.out.println("----------------------------------------------------------------------------------------");
  }
  </code></pre>
  
  <p>When I tried to debug the line <code>character.getBytes()</code> in the code above, the debugger took me into the <code>getBytes()</code> method of String class and then subsequently into the <code>static byte[] encode(char[] ca, int off, int len)</code> method of StringCoding class. The first line of the encode method (<code>String csn = Charset.defaultCharset().name();</code>) returned "UTF-8" as the default encoding during the debugging. I expected it to be "UTF-16". </p>
  
  <p>The output of the program is:</p>
  
  <p>Unicode Value for 最=6700
  The UTF-8 Character=最  | Default: Number of Bytes=3</p>
  
  <p>The corresponding UTF-16 Character=�  | UTF-16: Number of Bytes=6</p>
  
  <p>When I converted it to UTF-16 explicitly in the program it took 6 bytes to represent the character. Shouldn't it use 2 or 4 bytes for UTF-16? Why 6 bytes were used?</p>
  
  <p>Where am I going wrong in my understanding?
  I use Ubuntu 14.04 and the locale command shows the following:</p>
  
  <pre><code>LANG=en_US.UTF-8
  </code></pre>
  
  <p>Does this mean that JVM decides which encoding to use on the basis of underlying OS or does it use UTF-16 only?
  Please help me understand the concept.</p>