Home >>Java String Methods >Java String getBytes() method

Java String getBytes() method

Java String getBytes() method

Java method getBytes() in java string returns the string's byte array. In other words, it returns byte sequence.

Internal implementation

public byte[] getBytes() 
{  
        return StringCoding.encode(value, 0, value.length);  
    }  

Signature

public byte[] getBytes()  
public byte[] getBytes(Charset charset)  
public byte[] getBytes(String charsetName)throws UnsupportedEncodingException 
String getBytes() method example 1

public class StringGetBytesExample
{  
public static void main(String args[])
{  
String n1="UVWXYZ";  
byte[] barr=n1.getBytes();  
for(int i=0;i<barr.length;i++)
{  
System.out.println(barr[i]);  
}  
}
}  

Output
85
86
87
88
89
90
String getBytes() Method Example 2

public class StringGetBytesExample2 
{
	public static void main(String[] args) 
	{
		String n1 = "UVWXYZ";
		byte[] barr = n1.getBytes();
		for(int i=0;i<barr.length;i++)
		{
			System.out.println(barr[i]);
		}
		String n2 = new String(barr);
		System.out.println(n2);
	}
}


Output
85
86
87
88
89
90
UVWXYZ

No Sidebar ads