Java.lang.String.getBytes() Method
Advertisements
Description
The java.lang.String.getBytes() method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Declaration
Following is the declaration for java.lang.String.getBytes() method
public byte[] getBytes()
Parameters
NA
Return Value
This method returns the resultant byte array.
Exception
NA
Example
The following example shows the usage of java.lang.String.getBytes() method.
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials point";
// copy contents of str1 to a byte array.
byte[] val = str1.getBytes();
// create string str1 using the contents of the byte array
String str2 = new String(val);
// prints the byte array.
System.out.println("String '" + str2 + "' is equal to str1");
}
}
Let us compile and run the above program, this will produce the following result:
String 'tutorials point' is equal to str1