Java.Com.ing

Программирование на Java

5497f1e3
5 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java string getbytes

Java String getBytes Method

The Java String.getBytes method is one of the Java String Methods, which is to encode the given string into a sequence of bytes using the user-specified Charset and return Byte array.

In this article, we will show how to write the Java String getBytes method with an example. The syntax of the string.getBytes in Java Programming language is as shown below.

Java String getBytes syntax

The following Java String getBytes method will not accept any argument and encode the given string into a sequence of bytes using the default charset.

Below Java getBytes method will accept Charset as an argument and encode the given string into a sequence of bytes using the user-specified Charset. It means we are allowing the user to specify the Charset (dynamic).

The following Java String getBytes method will accept Charset’s name as an argument and encode the given string into a sequence of bytes by invoking the specified charset name. It means we are calling the required Charset name (static).

Return Value

The Java String getBytes Method encodes this string into a sequence of bytes using the user-specified Charset, and it will store the result in a byte array.

TIP: Java String.getBytes Method throws UnsupportedEncodingException. So, it is always advisable to use Try catch block.

Java String getBytes Example 1

The Java String.getBytes method encodes the given string into a sequence of bytes and returns a byte array. In this Java program, We are going to encode the string using the platform default charset.

OUTPUT

TIP: Please refer to the ASCII Table to understand the byte values.

ANALYSIS

Within the Java String getBytes example, First, we declared two String variables str, str1, and assigned corresponding values using the following statement.

The following String getBytes statements will call the public byte [] getBytes () method to encode the above-specified string (str & str1) into a sequence of bytes. From the above screenshot, you can observe that both these statements are using the platform default charset.

The following statement is to print the Byte array elements to the output.

When the compiler reaches the above statement, the compiler will jump to the following function. From the below code snippet, you can observe that we used the Foreach Loop to iterate the Byte Array. Then we are printing every array element using the System.out.println statement.

Java String getBytes Example 2

In this Java program, we are going to encode the string using the available standard charsets (Prov >

OUTPUT

ANALYSIS

First, we declared a String variable str and assigned non-Unicode text using the following statement.

The following statements will call the public byte [] getBytes () method to encode the above-specified string (str) into a sequence of bytes. It is using the platform default charset.

Читать еще:  Ошибка 651 модем или другое устройство

It will call the public byte [] getBytes (Charset charset) method to encode the above-specified string (str) into a sequence of bytes using standard charset UTF-8.

The following String getBytes statements will call the public byte [] getBytes (Charset charset) method to encode the above-specified string (str) into a sequence of bytes using standard charset ISO-8859-1.

The following String getBytes statement is to convert the Byte array to string

NOTE: From the above screenshot, you can observe that the default charset and the standard charset ISO-8859-1 are returning the same result.

Java String getBytes Example 3

In this Java program, We are going to encode the string by calling the available standard charsets names (Static functionality).

OUTPUT

ANALYSIS

Within the String getBytes example, First, we declared a String variable str and assigned non-Unicode text.

It will call the public byte [] getBytes (String Charset_name) method to encode the above-specified string (str) into a sequence of bytes. It is calling the standard charset name UTF_16BE.

It will call the public byte [] getBytes (String Charset_name) method to encode the above-specified string (str) into a sequence of bytes. It is calling the standard charset name UTF_8.

Within the below Java String getBytes statement, we are assigning the default charset name.

The following statement is to convert the Byte array to string.

Java – String getBytes() Method

This method has following two forms:

  • getBytes(String charsetName): Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
  • getBytes(): Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.

Here is the syntax of this method:

Here is the detail of parameters:

  • charsetName — the name of a supported charset.

This method returns the resultant byte array

This produces following result:

Share this:

Related Posts

Types of Web Services

Expert in Java Web and Desktop Application

Java – String replace() Method

@Resource Annotation in JSR-250 with Spring Framework

Java – String split() Method

Java – String compareTo() Method

About The Author

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Читать еще:  Arraylist contains java

Java String getBytes

Introduction to Java String getBytes

getBytes() method in Java is defined as “converting the string into a byte of array”. getBytes() method returns byte[] array. getBytes() method in Java is applied with Strings only. Every string value in a byte array is converted into its equivalent ASCII (American Standard Code for Information Interchange) values. We can say it is an encoded form of the data to protect from unknown actions on the data.

Real-time Application: When we want to convert the string into byte array then the getBytes() method comes into the picture.

Web development, programming languages, Software testing & others

How does getBytes() work in Java?

Java getBytes() method works is based on string values in 3 ways:

Syntax:

String str=”Some String”;
Byte[] byteArray=Str.getBytes();

  • public byte[] getBytes(String string) throws UnsupportedEncodingException. The standard supporting Charset in the java application are mentioned below:
  • US-ASCII: It is 7-bit ASCII characters.
  • ISO-8859-1: It is ISO (Indian Standard Organization) Latin-alphabet.
  • UTF-8: It is an 8-bit Universal Coded Character Set format.
  • UTF-16BE: This is 16-bit Universal Coded Character Set format by big-endian order.
  • UTF-16LE: This is 16-bit Universal Coded Character Set by little-endian order.
  • UTF-16: 16-bit Universal Coded Character Set format.

Syntax:

String str=”UTF-16”;
Byte[] byteArray=Str.getBytes();

  • public byte[] getBytes(Charset characterSet)

Syntax:

Examples of Java String getBytes

Given below are the examples of Java String getBytes:

Example #1

public byte[] getBytes()

Code:

package com.getbytes;
public class GetBytesOfNames <
public static void main(String args[]) <
String name = «Paramesh»; /// defining a string
byte[] nameByteArray = name.getBytes(); // converting string into byte array
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
>
>

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent ASCII code by applying getBytes() method.

Example #2

public byte[] getBytes()

Code:

package com.getbytes;
public class GetBytesOfSpaceValues <
public static void main(String args[]) <
String name = «This is Amardeep»; /// defining a string
byte[] nameByteArray = name.getBytes(); // converting string into byte array
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
>
>

Читать еще:  Java thread states

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent ASCII code by applying the getBytes() method.
  • Even space also has an ASCII value.

Example #3

public byte[] getBytes(String string)

Code:

package com.getbytes;
import java.io.UnsupportedEncodingException;
public class GetBytesString <
public static void main(String args[]) <
String name = «Amardeep»; // defining a string
byte[] nameByteArray;
try <
nameByteArray = name.getBytes(«UTF-8»);
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
> catch (UnsupportedEncodingException e) <
// TODO Auto-generated catch block
e.printStackTrace();
> // converting string into byte array
>
>

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent UTF-8 code by applying the getBytes() method.

Example #4

public byte[] getBytes(String string)

Code:

package com.getbytes;
import java.io.UnsupportedEncodingException;
public class GetBytesOfNames <
public static void main(String args[]) <
String name = «Amardeep is smart»; // defining a string
byte[] nameByteArray;
try <
nameByteArray = name.getBytes(«UTF-8»);
System.out.println(«=========Coverting String into byte[] array========»);
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
String string=new String(nameByteArray);//converting byte array into string
System.out.println(«=========Coverting byte[] into original string========»);
System.out.println(string);
> catch (UnsupportedEncodingException e) <
// TODO Auto-generated catch block
e.printStackTrace();
> // converting string into byte array

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent UTF-8 code by applying the getBytes() method.
  • UTF-8-byte array again converted into the original string. It concludes original information can’t be lost.

Example #5

public byte[] getBytes(Charset characterSet)

Code:

package com.getbytes;
import java.nio.charset.Charset;
public class GetBytesCharSet <
public static void main(String args[]) <
String name = «Hello»; // defining a string
byte[] nameByteArray = name.getBytes(Charset.forName(«ASCII»));
System.out.println(«=========Coverting String into byte[] array========»);
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
>
>

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent ASCII code by applying the getBytes() method.

Example #6

public byte[] getBytes(Charset characterSet)

Code:

package com.getbytes;
import java.nio.charset.Charset;
public class GetBytesOfCharSetAndString <
public static void main(String args[]) <
String name = «Hello Amardeep»; // defining a string
byte[] nameByteArray = name.getBytes(Charset.forName(«ASCII»));
System.out.println(«=========Coverting String into byte[] array========»);
for (int i = 0; i » + nameByteArray[i]);// displaying values
>
String string=new String(nameByteArray);
System.out.println(«=========Coverting String into byte[] array========»);
System.out.println(string);
>
>

Output:

Explanation:

  • As you can see in the output corresponding character gives its equivalent ASCII code by applying the getBytes() method.
  • ASCII code byte array again converted into the original string. It concludes original information can’t be lost.

Conclusion

String can be converted into its equivalent ASCII code, UTF code, ISO code based on getBytes(), getBytes(String string) and getBytes(Charset characterSet).

Recommended Articles

This is a guide to Java String getBytes. Here we discuss the introduction, examples and how does getBytes() work in Java? You may also have a look at the following articles to learn more –

Java Training (40 Courses, 29 Projects, 3 Quizzes)

Ссылка на основную публикацию