src/java.base/share/classes/java/lang/String.java

Print this page

        

@@ -26,10 +26,11 @@
 package java.lang;
 
 import java.io.ObjectStreamField;
 import java.io.UnsupportedEncodingException;
 import java.nio.charset.Charset;
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.Formatter;
 import java.util.Locale;

@@ -358,20 +359,28 @@
     @Deprecated
     public String(byte ascii[], int hibyte) {
         this(ascii, hibyte, 0, ascii.length);
     }
 
+    private static void checkBounds(byte[] bytes, int offset, int length) {
+        checkBounds(bytes.length, offset, length);
+    }
+
+    private static void checkBounds(ByteBuffer bytes, int offset, int length) {
+        checkBounds(bytes.capacity(), offset, length);
+    }
+
     /* Common private utility method used to bounds check the byte array
      * and requested offset & length values used by the String(byte[],..)
      * constructors.
      */
-    private static void checkBounds(byte[] bytes, int offset, int length) {
+    private static void checkBounds(int lengthOfBytes, int offset, int length) {
         if (length < 0)
             throw new StringIndexOutOfBoundsException(length);
         if (offset < 0)
             throw new StringIndexOutOfBoundsException(offset);
-        if (offset > bytes.length - length)
+        if (offset > lengthOfBytes - length)
             throw new StringIndexOutOfBoundsException(offset + length);
     }
 
     /**
      * Constructs a new {@code String} by decoding the specified subarray of

@@ -449,10 +458,17 @@
             throw new NullPointerException("charset");
         checkBounds(bytes, offset, length);
         this.value =  StringCoding.decode(charset, bytes, offset, length);
     }
 
+    public String(ByteBuffer bytes, int offset, int length, Charset charset) {
+        if (charset == null)
+            throw new NullPointerException("charset");
+        checkBounds(bytes, offset, length);
+        this.value = StringCoding.decode(charset, bytes, offset, length);
+    }
+
     /**
      * Constructs a new {@code String} by decoding the specified array of bytes
      * using the specified {@linkplain java.nio.charset.Charset charset}.  The
      * length of the new {@code String} is a function of the charset, and hence
      * may not be equal to the length of the byte array.