Site icon TechVidvan

Java String getBytes() Method

A string is an object representing a number of character values for Java. The Java string object is made up of a separate character value for each letter in the string. The char class represents the characters in Java. An array of char values can be written by users, which means the same thing as a string.

Example : String s=”HelloWorld”;

String getBytes() in Java

The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes.

Signature

There are three variants of the getBytes() method. The signature or syntax of string getBytes() method is given below:

Parameters

charset / charsetName – The name of a charset the method supports.

Returns

Sequence of bytes

Exception Throws

UnsupportedEncodingException:
It is thrown when the mentioned charset is not supported by the method.

Internal implementation

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

Java String class getBytes() Method Example

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

Output:
65
66
67
68
69
70
71

String.getByte() Method in Java

In Java, getBytes() encodes a string into a sequence of bytes using the named character set and storing the result into a new byte array. This function can be implemented in two ways. Both ways are discussed below as follows:

Let us discuss and implement the first use case, which is as follows:

Java String getBytes()

This function takes no arguments and uses the default charset to encode the string into bytes. getbytes() function in Java is used to convert a string into a sequence of bytes and returns an array of bytes.

Syntax

public byte[] getBytes()

Java String getBytes(Charset charset)

Now let us implement and accept the charset according to which string has to be encoded while conversion into bytes. There are many charset defined and are discussed below.

Syntax

public byte[] getBytes(Charset charset);

Advantages of String

Disadvantages of String:

Conclusion

The getBytes() function is an inbuilt method of Java.

The getBytes() function converts a string into a sequence of bytes and returns a byte array.

getBytes() function takes optional parameters as charset or string.

The getBytes() function throws UnsupportedEncodingException due to the wrong encoding charset value passed.

Exit mobile version