Converting Numbers to Strings
The most common way to turn any number into a string is using String.valueOf(), though a quick "hack" is to concatenate the number with an empty string.
// Method 1: The standard way
int age = 25;
String s1 = String.valueOf(age);
// Method 2: The shortcut
int age = 25;
String s2 = age + "";
Converting Strings to Numbers
To turn a string back into a number, you use "Wrapper Classes" (like Integer or Double). These classes provide "parse" methods. Note: If the string contains non-numeric characters (like "25a"), Java will throw a NumberFormatException.
// To Integer
int i = Integer.parseInt(numericText);
// To Double
double d = Double.parseDouble("19.99");
Summary of Common Conversion Methods |
|
Target Type |
Conversion Method |
String |
String.valueOf(number) |
int |
Integer.parseInt(string) |
long |
Long.parseLong(string) |
double |
Double.parseDouble(string |
🎯 Simple Exam Definition
Number data types store numeric values used in calculations.
String data type stores text enclosed in double quotation marks.