Type Casting Part 2
Part of the Fundamentals section of Coddy's Java journey — lesson 14 of 73.
It is also possible to convert number and booleans to string and vice versa. To convert a value to string we can use the String.valueOf() function:
int number1 = 789;
double number2 = 789;
boolean isValid = true;
String text1 = String.valueOf(number1); // becomes "789"
String text2 = String.valueOf(number2); // becomes "789.0"
String text3 = String.valueOf(isValid); // becomes "true"To convert a string to a different type is a bit more complicated:
String to Integer:
String numberText = "123";
int number = Integer.parseInt(numberText); // becomes 123String to Double:
String decimalText = "45.67";
double decimal = Double.parseDouble(decimalText); // becomes 45.67String to Boolean:
String boolText = "true";
boolean bool = Boolean.parseBoolean(boolText); // becomes trueparseBoolean will convert any case-insensitive string that has the value “true”. For example True, tRue, TRUE will all become true
Trying to convert a string to an invalid type will result in an error:
String invalidNumber = "abc";
int number = Integer.parseInt(invalidNumber); // This will cause a NumberFormatExceptionCheat sheet
Convert values to string using String.valueOf():
int number = 789;
String text = String.valueOf(number); // becomes "789"Convert string to integer:
String numberText = "123";
int number = Integer.parseInt(numberText); // becomes 123Convert string to double:
String decimalText = "45.67";
double decimal = Double.parseDouble(decimalText); // becomes 45.67Convert string to boolean:
String boolText = "true";
boolean bool = Boolean.parseBoolean(boolText); // becomes trueparseBoolean accepts case-insensitive "true" values. Invalid string conversions will cause a NumberFormatException.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else