Home » Java programming language

Java String getBytes() Method with Example

Java String getBytes() Method: Here, we are going to learn about the getBytes() method with example in Java.
Submitted by IncludeHelp, on February 08, 2019

String getBytes() Method

getBytes() method is a String method in java and it is used to get the byte values of a given string.

Syntax:

    byte[] String.getBytes();

It accepts String and returns byte array.

Example:

    Input: "IncludeHelp"

    Output:
    73
    110
    99
    108
    117
    100
    101
    72
    101
    108
    112

Code:

public class Main
{
    public static void main(String[] args) {
        try{
            
            String str = "IncludeHelp";
            
            byte[] arr = str.getBytes();
            
            //printing byte array (each elements in nubers)
            System.out.println("Byte values of each character...");
            for(int i =0; i<str.length(); i++)
                System.out.println("arr[" + i +"] = " + arr[i]);
        }
        catch(Exception ex){
            System.out.println("Error: " + ex.toString());
        }
    }
}

Output

Byte values of each character...
arr[0] = 73
arr[1] = 110
arr[2] = 99
arr[3] = 108
arr[4] = 117
arr[5] = 100
arr[6] = 101
arr[7] = 72
arr[8] = 101
arr[9] = 108
arr[10] = 112



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.