### Question:
CharsetHelper { @Nonnegative public static int getUTF8ByteCount (@Nullable final String s) { return s == null ? 0 : getUTF8ByteCount (s.toCharArray ()); } private  CharsetHelper(); @Nonnull static Charset getCharsetFromName(@Nonnull @Nonempty final String sCharsetName); @Nullable static Charset getCharsetFromNameOrNull(@Nullable final String sCharsetName); @Nullable static Charset getCharsetFromNameOrDefault(@Nullable final String sCharsetName, @Nullable final Charset aDefault); @Nonnull @ReturnsMutableCopy static ICommonsOrderedMap <String, Charset> getAllCharsets(); @Nullable static String getAsStringInOtherCharset(@Nullable final String sText,
                                                  @Nonnull final Charset aCurrentCharset,
                                                  @Nonnull final Charset aNewCharset); @Nonnegative static int getUTF8ByteCount(@Nullable final String s); @Nonnegative static int getUTF8ByteCount(@Nullable final char [] aChars); @Nonnegative static int getUTF8ByteCount(final char c); @Nonnegative static int getUTF8ByteCount(@Nonnegative final int c); @Nonnull static InputStreamAndCharset getInputStreamAndCharsetFromBOM(@Nonnull @WillNotClose final InputStream aIS); @Nonnull static InputStreamReader getReaderByBOM(@Nonnull final InputStream aIS, @Nonnull final Charset aFallbackCharset);  }### Answer:
@Test public void testGetUTF8ByteCount () { assertEquals (0, CharsetHelper.getUTF8ByteCount ((String) null)); assertEquals (0, CharsetHelper.getUTF8ByteCount ((char []) null)); assertEquals (2, CharsetHelper.getUTF8ByteCount ("\0")); assertEquals (2, CharsetHelper.getUTF8ByteCount ("ä")); assertEquals (2, CharsetHelper.getUTF8ByteCount ('ä')); assertEquals (0, CharsetHelper.getUTF8ByteCount ("")); assertEquals (3, CharsetHelper.getUTF8ByteCount ("abc")); assertEquals (9, CharsetHelper.getUTF8ByteCount ("abcäöü")); assertEquals (3, CharsetHelper.getUTF8ByteCount ("\ud7ff")); assertEquals (0, CharsetHelper.getUTF8ByteCount ("\udfff")); assertEquals (0, CharsetHelper.getUTF8ByteCount ("\ue000")); assertEquals (0, CharsetHelper.getUTF8ByteCount ("\uffff")); try { CharsetHelper.getUTF8ByteCount (0x110000); fail (); } catch (final IllegalArgumentException ex) {} try { CharsetHelper.getUTF8ByteCount (0x10000); fail (); } catch (final IllegalArgumentException ex) {} }
@Test @Ignore ("doesn't work reliably") public void testGetUTF8ByteCountRandom () { final Random aRandom = new Random (); for (int i = 0; i < 1000; i++) { final int nStringLen = 20; final StringBuilder aSB = new StringBuilder (); for (int x = 0; x < nStringLen; ++x) { final int c = aRandom.nextInt (Character.MIN_HIGH_SURROGATE); aSB.append ((char) c); } final int nCounted = CharsetHelper.getUTF8ByteCount (aSB.toString ()); assertTrue (nCounted >= nStringLen); final byte [] b = aSB.toString ().getBytes (StandardCharsets.UTF_8); assertTrue (b.length >= nStringLen); assertEquals (Arrays.toString (b), nCounted, b.length); } }