Contact Ben Millionaire

Java: String.getBytes method sample program

String.getBytes

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

Description:
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. This method is risky and will throw UnsupportedEncodingException if named charset is not supported.

Here’s the sample program I developed:

public class StringByte {
 public static void main(String[] args) {
  String xxx = new String("abc\u00e7");
  
  byte[] xx;
  try
  {
      xx = xxx.getBytes("UTF8");
   for(int i=0;i<xx.length;i++)
   {
    System.out.println(xx[i]);
   }
   System.out.println("Length of " + xxx + " is: " + xx.length);
  }
  catch(Exception e)
  {
   
  }

                char[] yyy = xxx.toCharArray();

                for(int i=0;i<yyy.length;i++)
                    System.out.println("Char["+i+"] = " + yyy[i]);
 }
}

 

Output:

compile and run StringByte.java

compile and run StringByte.java

Tags: , , , ,

Leave a Reply



Thank you very much for visiting my website.
- Ben Billionaire Millionaire
  Ben Millionaire Author
Contact Ben Millionaire