by Dinesh Thakur

The String class also provide methods for extracting characters from a string in an array of bytes. This is achieved using the getBytes () method in the String class. This method converts the original string characters into the character encoding used by the underlying operating system which is usually ASCII . For example : The statement,

byte[] txtArray = s1.getBytes();

extracts character from the String object s1 and stores them in the byte array txtArray. There are many other forms of getBytes () available.

public class GetBytesMethods

{
       public static void main(String[] args)
       {
           String sl = "Hello Java" ;
           byte[] txtArray = sl.getBytes();
           for( int i=0 ;i<txtArray.length; i++)
              System.out.println("txtArray["+i+"] = " + txtArray[i]);
       }
}

String getBytes() Method in Java Example