This example shows how to convert short to String in Java using the toString, valueOf, and + operator. It also shows the best way to convert short to string.
How to convert short to String in Java?
There are several ways in which primitive short can be converted to a string in Java.
1) Convert short to String using the Short wrapper class
Use the toString
method of the Short wrapper class to convert.
1 |
public static String toString(short s) |
This method returns a string representation of the short value passed as a parameter.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.basic; public class ShortToStringExample { public static void main(String[] args){ short s = 436; String strNumber = Short.toString(s) System.out.println("String value: " + strNumber); } } |
Output
1 |
String value: 436 |
2) Using string concatenation
String concatenation can be indirectly used to convert Java primitive values to a string as given below.
1 2 3 4 |
short b = 436; String strNumber = "" + s; System.out.println("String value: " + strNumber); |
Output
1 |
String value: 436 |
What is the best way to convert?
The toString
method of the Short wrapper class is more efficient in terms of 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 is to convert.
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 = "" + s; |
Will be executed like,
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(s); 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.