String To Byte Array In Java

Chapter: String Handling Last Updated: 04-08-2016 20:06:46 UTC

Program:

            /* ............... START ............... */
                
public class JavaStringToByteArray {
	public static void main(String[] args) {

		String content = "Welcome To JavaScan.com";
		byte[] bytes = content.getBytes();
		System.out.println("String: " + content);
		for (int x : bytes) {
			System.out.println((char) x + ": " + x);
		}
	}

}

                /* ............... END ............... */
        

Output

String: Welcome To JavaScan.com
W: 87
e: 101
l: 108
c: 99
o: 111
m: 109
e: 101
 : 32
T: 84
o: 111
 : 32
J: 74
a: 97
v: 118
a: 97
S: 83
c: 99
a: 97
n: 110
.: 46
c: 99
o: 111
m: 109

Notes:

  • The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String , depending upon the chosen charset. You can use String.getBytes() which returns the byte[] array.

Tags

String To Byte Array, Java

Similar Programs Chapter Last Updated
String Length Implementation Java String Handling 02-12-2019
Java StringBuffer CharAt String Handling 27-05-2017
Java StringBuilder EnsureCapacity String Handling 27-05-2017
Java StringBuffer Capacity Example String Handling 27-05-2017
Java Character At Particular Index String Handling 16-05-2017
Java Convert String To Array Example String Handling 16-05-2017
Java String Trim Method String Handling 15-05-2017
Java String Character Case Check String Handling 15-05-2017
Java Find All Substrings Of String String Handling 14-05-2017
Java String Conversion Using ValueOf String Handling 30-03-2017
Immutable String In Java String Handling 24-03-2017
Java Float To String Using toString() String Handling 05-11-2016
Java Program To Convert Integer To String Using toString() String Handling 05-11-2016
Java Reverse String Using Stack String Handling 24-10-2016
Java Integer To String Conversion String Handling 21-10-2016
Java Program To Check Isomorphic Strings String Handling 19-10-2016
Java String Unicode Code Point Example String Handling 28-08-2016
Concatenate Strings In Java Example String Handling 21-08-2016
String Optimization In Java String Handling 21-08-2016
Java String Split Example String Handling 20-08-2016
Java String Search String Handling 20-08-2016
Java String Replace String Handling 20-08-2016
Java String Remove Character Example String Handling 20-08-2016
Java String Last Occurance String Handling 20-08-2016
Java String Compare Example String Handling 20-08-2016
String Initialization In Java Example String Handling 20-06-2016
StringBuffer SubString In Java String Handling 09-05-2016
StringBuffer Reverse In Java String Handling 09-05-2016
StringBuffer Insert In Java String Handling 09-05-2016
StringBuffer Append In Java String Handling 09-05-2016

1 2 3