Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

getBytes()

Example

Convert a string into a byte array:

String myStr = "Hello";
byte[] result = myStr.getBytes();
System.out.println(result[0]);

Definition and Usage

The getBytes() method converts a string into a byte array.

The encoding of the bytes relies on the charset argument.

If the charset argument is omitted, the bytes will be encoded using the system’s default character set.

Syntax

“Choose one from the following options:”

public byte[] getBytes(Charset charset)

 

public byte[] getBytes()

Parameter Values

Parameter

Description

charset

“This parameter is optional. It’s a Charset object specifying the character set to be used for encoding the string into bytes.”

Technical Details

Returns:

byte array representing the bytes of the string with a specific encoding.

Java version:

“The charset parameter, introduced in version 1.6, can be of any type.”