Java String getBytes() Method
What is String?
In Java, an string class is a series of characters that are interpreted literally by a script. An object called a string represents a string of characters. Java.lang is used. A string object is made using the String class.
- Strings in Java are immutable, which means that once you create a string object, its value cannot be changed.
To know more about String Class in java read the complete article.
String Getbytes() Method:
The getBytes method of the Java programming language converts a string into a series of bytes and returns a byte array.
When this string cannot be encoded in the supplied charset, this method’s behaviour is undefined. When further control over the encoding process is necessary, the CharsetEncoder class should be utilised.
- The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java.These methods help us to perform operations on String objects such as trimming, concatenating, converting, comparing, replacing strings etc.
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The Charset Encoder class should be used when more control over the encoding process is required.
Syntax:
public byte[] getBytes()
Let’s look at a string-related Java program where the Java String getbytes() method is used to perform an operation on the given string.
Examples : Java String Getbytes Method
public class Main { public static void main(String[] args) { String str = "Hello World!"; byte[] bytes = str.getBytes(); for (byte b : bytes) { System.out.print(b + " "); } } }
Output
72 101 108 108 111 32 87 111 114 108 100 33
Examples 2 : Java String Getbytes Method
public class Main{ public static void main(String[] args) { String original = "Hello World!"; byte[] bytes = original.getBytes(); String converted = new String(bytes); System.out.println("Original string: " + original); System.out.println("Converted string: " + converted); } }
Output
Original string: Hello World! Converted string: Hello World!
Examples 3: Java String Getbytes Method
import java.io.UnsupportedEncodingException; public class Main { public static void main(String[] args) throws UnsupportedEncodingException { String original = "Hello World!"; byte[] bytes = original.getBytes("UTF-16BE"); String converted = new String(bytes, "UTF-16BE"); System.out.println("Original string: " + original); System.out.println("Converted string: " + converted); } }
Output
Original string: Hello World! Converted string: Hello World!
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment