How to encode a given String into a sequence or Array of bytes using the getBytes() method
How to encode a given String into a sequence or Array of bytes using the getBytes() method
In this video, let’s talk about the Java getBytes() method, which we can use to encode a given String into a sequence of bytes. When evaluated, this method will return an array of bytes.
There are two ways to use this method
In the first example I will show you how to encode a given String using the default charset method
String str = “I love programming”;
Since the method returns an array of bytes, we will declare an array of byte
byte[] array_bytes = str.getBytes();
and then we will print the content of the array like this
for(byte content : array_bytes) {
System.out.println(content);
}
In the second example, I will show you how to encode a given String using a specified charset method
String str = “I love programming”;
Since the method returns an array of bytes, we will declare an array of byte and specify the charset method
bytes[] array_bytes = str.getBytes(“UTF-16”);
and then we will print the content of the array like this
for(byte content : array_bytes) {
System.out.println(content);
Note that, the method will throw an exception if the charset method is not supported
bytes[] array_bytes = str.getBytes(“UF-16”);
and then we will print the content of the array like this
for(byte content : arry_bytes) {
System.out.println(content);
The result of this, will throw an exception
So, you need to make sure that you are passing the right charset method
such as the UTF-16 , UTF-16LE , UTF-16BE , UTF-8 , ISO-8859-1 , ISO-ASCII
#codingriver
#java
#programming
Видео How to encode a given String into a sequence or Array of bytes using the getBytes() method автора Программирование для всех
Видео How to encode a given String into a sequence or Array of bytes using the getBytes() method автора Программирование для всех
Информация
5 декабря 2023 г. 9:50:22
00:05:59
Похожие видео