.getBytes()
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.
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.javaimport 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]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours