Wednesday, May 27, 2009

Convert a String to int

Use the static method parseInt of the Integer class to convert
a String to an int as below:
 
public void convertStringToInt() {
String sValue = "5";
int iValue = 0;
try {
iValue = Integer.parseInt(sValue);
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}
 
 
 
 
 
Alternatively you can pass a String to the Integer class constructor
and call the intValue-method of the object:
 
 
public void convertStringToInt() {
String sValue = "5";
int iValue;
try {
iValue = new Integer(sValue).intValue();
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}

Convert an int value to String

This code example shows how to convert an int value to a String object.
Actually there are a few possible ways of doing this and three of the most common methods of doing so is presented here.
First we use the static method toString() of the Integer class which takes an integer as argument and returns a String.
The second way of converting from int to String is to instantiate the Integer class and pass the int value to the constructor, and then call the toString() method on the object.
Finally the easiest way of converting from datatype int to String is to simply concatenate the int value to an empty String. That way the value will automatically be converted and appended to the String.
After every conversion the converted value along with the method of which it was converted is printed out to show that the object returned is really an instance of the String class.
 
 
 
/*
* Main.java
*
* @author chintan patel
*/
public class Main {
/*
* This method converts an int value to a String object.
*/
public void convertIntToString() {
int intToConvert = 50;
//One way of converting from int to String
String convertedValue = Integer.toString(intToConvert);
System.out.println(convertedValue + " : " + Integer.toString(intToConvert).getClass());
//Another way of converting from int to String
convertedValue = new Integer(intToConvert).toString();
System.out.println(convertedValue + " : " + new Integer(intToConvert).toString().getClass());
//A third way of converting from int to String
convertedValue = "" + intToConvert;
System.out.println(convertedValue + " : " + ("" + intToConvert).getClass());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertIntToString();
}
}

Convert String to byte

This example shows how to convert a String to a byte.
The String can only contain digits (or start with the - sign) and the number has to be within the byte range, otherwise a NumberFormatException will be thrown.
The output from the code below is:
65
Tried to convert an invalid value
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a String to a byte
*/
public void convertStringToByte() {
try {
String s = "65";
byte b = Byte.valueOf(s);
System.out.println(b);
//Causes a NumberFormatException since the value is out of range
System.out.println(Byte.valueOf("129"));
} catch (NumberFormatException ex) {
System.out.println("Tried to convert an invalid value");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByte();
}
}

Convert String to character array

This example shows how to do a String to character array conversion. The String class has a neat method for doing this, toCharArray().
In the code example below the String is converted to a char array and each element of the array is printed out.
 
 
/**
* Main.java
*
* @author chitnan patel
*/
public class Main {
/**
* Converts a String to a character array
*/
public void convertStringToCharArray() {
String str = "Abcdefg";
char[] cArray = str.toCharArray();
for (char c : cArray)
System.out.println(c);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToCharArray();
}
}
The output from the executed code:
 
A
b
c
d
e
f
g

Character array to String conversion

This java code example shows how to convert an array of characters to a String.
To accomplish this we can utilize one of the String class many contructors, which takes an array of characters as parameter.
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* Converts an array of characters to a String
*/
public void convertCharArrayToString() {
char[] charArray = new char[] {'a', 'b', 'c'};
String str = new String(charArray);
System.out.println(str);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertCharArrayToString();
}
}

Convert byte to String

This example shows three ways of converting a variable of datatype byte to a String.
The first example uses the wrapper class Byte and it's static method toString to convert the byte.
The second example just concatenates the byte with an empty String, and the value is automatically casted to a String.
The final example creates a byte array which is passed to the constructor of the String class.
The output of the code below is:
65
65
A
 
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a byte to a String.
*/
public void convertByteToString() {
byte b = 65;
//Using the static toString method of the Byte class
System.out.println(Byte.toString(b));
//Using simple concatenation with an empty String
System.out.println(b + "");
//Creating a byte array and passing it to the String constructor
System.out.println(new String(new byte[] {b}));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertByteToString();
}
}

Convert Boolean to String

To convert a boolean value to a String you need to use the wrapper class of the boolean datatype.
It has the same name as the datatype boolean, but it begins with the captial B - Boolean.
To convert a boolean value you create an instance of the wrapper class sending the boolean value as argument to the constructor.
Then you simply call the toString() method which will return a String representation of the boolean value.
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* Boolean to String conversion
*/
public void convertBooleanToString() {
boolean theValue = true;
//Do the boolean to String conversion
String theValueAsString = new Boolean(theValue).toString();
System.out.println(theValueAsString);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertBooleanToString();
}
}

Convert String to Boolean

There's actually two ways to do a string to boolean conversion. Either you can create an instance of the wrapper class Boolean with a string value as argument to the constructor and call the method booleanValue(), or you can do as in the example below:
call the static method parseBoolean() of the wrapper class to convert the string value to a boolean.
Either way, the string value sent in has to be either 'true' or 'TRUE' to result in a boolean with the value of true, but it doesn't have to be 'false' to result in a false boolean value.
It actually makes sense that any other string value than 'true' or 'TRUE' will result in a return value that is set to false.
 
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* String to boolean conversion
*/
public void convertStringToBoolean() {
String strBoolean = "true";
//Do the String to boolean conversion
boolean theValue = Boolean.parseBoolean(strBoolean);
System.out.println(theValue);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToBoolean();
}
}

Convert String to byte array

This little code example shows a String to byte array conversion.
The String class has a method called getBytes which returns an array of bytes.
In the example the length of the array is printed out to illustrate that the length of the array is the same as the number of characters in the String.
/**
*
* @author chintan patel
*/
public class Main {
/*
* This method converts a String to an array of bytes
*/
public void convertStringToByteArray() {
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
System.out.println(theByteArray.length);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByteArray();
}
}

Convert byte[ ] array to String

Making a byte array to String conversion in Java is very simple since one of the String class constructors takes an array of bytes as argument.
We simply create the object with our array as argument to convert the byte array to a String, and then print out the value.
/*
* Main.java
*
* @author chintan patel
*/
public class Main {
/*
* This method converts an byte array to a String object.
*/
public void convertByteArrayToString() {
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
System.out.println(value);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertByteArrayToString();
}
}