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 a byte array, then the getBytes() method comes into the picture.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How does getBytes() work in Java?
Java getBytes() method works are based on string values in 3 ways:
- public byte[] getBytes()
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 a 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();Note: If the given data is not convertible, then it throws an UnsupportedEncodingException exception.
- public byte[] getBytes(Charset characterSet)
Syntax:
Byte[] byteArray=Str.getBytes(“ASCII”);
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 the 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 } } }
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).
The above is the detailed content of Java String getBytes. For more information, please follow other related articles on the PHP Chinese website!

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version
