Friday 13 June 2014

String (byte[] bytes, String charsetName)

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

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

class StringConstructor7{
 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, charSet);
  System.out.println(s1);  
 }
}

Output
abcdefghijklmnopqrstuvwxyz

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

class StringConstructor7Unsupport{
 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, 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 java.lang.String.<init>(String.java:479)
        at StringConstructor7Unsupport.main(StringConstructor7Unsupport.java:17)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment