This example shows how to convert byte to String in Java using the toString and + operator. It also shows what is the best way to convert byte to string.
How to convert the byte to String in Java?
There are several ways in which primitive byte type can be converted to a String in Java.
1) Using the Byte wrapper class
Use the toString
method of the Byte wrapper class to convert.
1 |
public static String toString(byte b) |
This method returns a string representation of the byte value passed as a parameter.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.basic; public class ByteToStringExample { public static void main(String[] args){ byte b = 42; String strNumber = Byte.toString(b) System.out.println("String value: " + strNumber); } } |
Output
1 |
String value: 42 |
2) Using String concatenation
String concatenation can be indirectly used to convert any Java primitive values to String as given below.
1 2 3 4 |
byte b = 42; String strNumber = "" + b; System.out.println("String value: " + strNumber); |
Output
1 |
String value: 42 |
What is the best way to convert byte to String?
The toString
method of the Byte wrapper class is more efficient in terms of the performance. String concatenation should be avoided mainly for the conversion purpose because,
a) It is difficult to visually understand that the purpose of the code statement is to conversion.
b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using the append
method of the StringBuilder or StringBuffer class. So the code,
1 |
String strNumber = "" + b; |
Will run like,
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(b); String strNumber = sb.toString(); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.