title: How to verify whether an instance of CharSequence is a sequence of Unicode scalar values?
body: <p>I have an instance of <code>java.lang.CharSequence</code>. I need to determine whether this instance is a sequence of <a href="http://www.unicode.org/glossary/#unicode_scalar_value" rel="nofollow">Unicode scalar values</a> (that is, whether the instance is in UTF-16 encoding form). Despite the assurances of <code>java.lang.String</code>, a Java string is not necessarily in UTF-16 encoding form (at least not according to the latest <a href="http://www.unicode.org/versions/Unicode6.2.0" rel="nofollow">Unicode specification</a>, currently 6.2), since it may contain isolated <a href="http://www.unicode.org/glossary/#surrogate_code_point" rel="nofollow">surrogate code units</a>. (A Java string is, however, a <a href="http://www.unicode.org/glossary/#unicode_string" rel="nofollow">Unicode 16-bit string</a>.)</p>
  
  <p>There are several obvious ways in which to go about this, including:</p>
  
  <ol>
  <li>Iterate over the <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#codePointAt%28java.lang.CharSequence,%20int%29" rel="nofollow">code points</a> of the sequence, explicitly validating each as a Unicode scalar value.</li>
  <li>Use a regular expression to search for isolated surrogate code points.</li>
  <li>Pipe the character sequence through a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetEncoder.html" rel="nofollow">character-set encoder</a> that <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/CodingErrorAction.html#REPORT" rel="nofollow">reports encoding errors</a>.</li>
  </ol>
  
  <p>It seems as though something like this should already exist as a library function, however. I just can't find it in the standard API. Am I missing it, or do I need to implement it?</p>