Converting other datatypes to String


1. You can get the value of other primitive data types as a String using one the String class's valueOf methods.

For example:
 
int i = 42;
String string = String.valueOf(i);
//string now equals "42”.
 
This method is also overloaded for other datatypes, such as float, double, boolean, and even Object.

2. You can also get any other Object (any instance of any class) as a String by calling .toString on it. For this to give useful output, the class must override toString(). Most of the standard Java library classes do, such as Date and others.

For example:
 
Foo foo = new Foo(); //Any class.
String stringifiedFoo = foo.toString().
 
Here stringifiedFoo contains a representation of foo as a String.

You can also convert any number type to String with short notation like below.

int i = 10;
String str = i + "";
 
Or just simple way is
 
String str = 10 + "";

Conversion to / from bytes

To encode a string into a byte array, you can simply use the String#getBytes() method, with one of the standard character sets available on any Java runtime

  byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);
 
and to decode:
 
  String testString = new String(bytes, StandardCharsets.UTF_8);
 
you can further simplify the call by using a static import:
 
  import static java.nio.charset.StandardCharsets.UTF_8;
  ...
  byte[] bytes = "test".getBytes(UTF_8);
 
For less common character sets you can indicate the character set with a string:
 
  byte[] bytes = "test".getBytes("UTF-8");
 
and the reverse:
 
  String testString = new String (bytes, "UTF-8");
 
this does however mean that you have to handle the checked UnsupportedCharsetException.

The following call will use the default character set. The default character set is platform specific and generally differs between Windows, Mac and Linux platforms.

byte[] bytes = "test".getBytes();
 
and the reverse:
 
String testString = new String(bytes);

Note that invalid characters and bytes may be replaced or skipped by these methods. For more control - for instance for validating input - you're encouraged to use the CharsetEncoder and CharsetDecoder classes.


Getting a String from an InputStream

A String can be read from an InputStream using the byte array constructor.

import java.io.*;
 
public String readString(InputStream input) throws IOException {
     byte[] bytes = new byte[50]; // supply the length of the string in bytes here
     input.read(bytes);
     return new String(bytes);
}

This uses the system default charset, although an alternate charset may be specified:

return new String(bytes, Charset.forName("UTF-8"));

Basic Programs