Friday, 13 June 2014

String (byte[] bytes, int offset, int length, String charsetName)

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

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

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

Output
fghijklmno

1. Throws UnsupportedEncodingException, if the named charset is not supported.
import java.nio.charset.*;
import java.util.*;
import java.io.UnsupportedEncodingException;

class StringConstructor6Unsupport{
 public static void main(String args[])throws UnsupportedEncodingException{
  byte data[] = new byte[26];
  String s1;
  String charSet = "abcd";
  int count = 0;
  
  for(byte b = 97; b < 123; b++){
   data[count] = b;
   count++;
  }
  
  s1 = new String(data, 5, 10, charSet);
  System.out.println(s1);  
 }
}

Output
Exception in thread "main" java.io.UnsupportedEncodingException: abcd
        at java.lang.StringCoding.decode(StringCoding.java:190)
        at java.lang.String.<init>(String.java:414)
        at StringConstructor6Unsupport.main(StringConstructor6Unsupport.java:17)

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

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

class StringConstructor6Indexout{
 public static void main(String args[])throws UnsupportedEncodingException{
  byte data[] = new byte[26];
  String s1;
  String charSet = "UTF-8";
  int count = 0;
  
  for(byte b = 97; b < 123; b++){
   data[count] = b;
   count++;
  }
  
  s1 = new String(data, 25, 10, 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:413)
        at StringConstructor6Indexout.main(StringConstructor6Indexout.java:17)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment