Java .getBytes()

AshutoshVJTI's avatar
Published Mar 27, 2023
Contribute to Docs

The .getBytes() method encodes a string into an array of bytes that represents the characters in the string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

byte[] byteArray = str.getBytes();
  • byteArray is a byte array that stores the byte representation of the string.
  • str is the string being converted to bytes.

Example

The example below demonstrates the use of the .getBytes() method:

// Example.java
import java.util.*;
public class Example {
public static void main(String[] args) {
String myStr = "codeacademy.com";
byte[] myByteArray = str.getBytes();
System.out.println(Arrays.toString(byteArray));
}
}

This outputs the following:

[99, 111, 100, 101, 97, 99, 97, 100, 101, 109, 121, 46, 99, 111, 109]

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours