Tutorial by Examples

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 ...
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.U...
Occasionally you will find the need to encode binary data as a base64-encoded string. For this we can use the DatatypeConverter class from the javax.xml.bind package: import javax.xml.bind.DatatypeConverter; import java.util.Arrays; // arbitrary binary data specified as a byte array byte[] bi...
String to a primitive numeric type or a numeric wrapper type: Each numeric wrapper class provides a parseXxx method that converts a String to the corresponding primitive type. The following code converts a String to an int using the Integer.parseInt method: String string = "59"; int p...
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); ...
You can convert a numeric string to various Java numeric types as follows: String to int: String number = "12"; int num = Integer.parseInt(number); String to float: String number = "12.0"; float num = Float.parseFloat(number); String to double: String double = "1...

Page 1 of 1