Friday, 13 June 2014

String (byte[] bytes, int offset, int length, Charset charset)

public String(byte bytes[], int offset, int length, Charset charset )
Constructs a new String by decoding the specified subarray of bytes using the specified charset.

import java.nio.charset.*;
import java.util.*;

class StringConstructor5{
 public static void main(String args[]){
  byte data[] = new byte[26];
  String s1;
  int count = 0;
  
  for(byte b = 97; b < 123; b++){
   data[count] = b;
   count++;
  }
  
  Charset charset = Charset.forName("UTF-8");
  s1 = new String(data, 5, 10, charset);
  System.out.println(s1);  
 }
}

Output
fghijklmno

1. Throws IndexOutOfBoundsException if the offset and length arguments index characters outside the bounds of the bytes array.

import java.nio.charset.*;
import java.util.*;

class StringConstructor5IndexOut{
 public static void main(String args[]){
  byte data[] = new byte[26];
  String s1;
  int count = 0;
  
  for(byte b = 97; b < 123; b++){
   data[count] = b;
   count++;
  }
  
  Charset charset = Charset.forName("UTF-8");
  s1 = new String(data, 5, 30, charset);
  System.out.println(s1);  
 }
}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 35
        at java.lang.String.checkBounds(String.java:373)
        at java.lang.String.<init>(String.java:450)
        at StringConstructor5IndexOut.main(StringConstructor5IndexOut.java:16)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment