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. Any other string, for example "yes" or "1", becomes false (no exception is thrown).
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 NumberFormatExceptionA decimal string such as "12.5" is also invalid for Integer.parseInt() and throws a NumberFormatException: use Double.parseDouble() for decimals.
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 - ElsePractice on your own: Online Java compiler