Lets pretend you are doing a math word problem where all of the words are written out like this:
CODE
If two rabbits produce four rabbits per week, how many rabbits will there be after ten weeks?
Well when you go to do the math, you automatically convert those words (Strings) into numbers (int, double, etc.)
However your computer isn't smart enough to do that yet, so you need to help it!
Lets pretend, for some reason your computer wants you to enter your name and age (in years) at the command line so it can return how old you are in seconds.
CODE
public class HowOldAreYou
{
public static void main(String[] args)
{
//confirm that both name and age are supplied.
if(args[1] == null)
{ System.out.println("Please enter your first name and age.");
System.exit(1);
}
//No conversion needed here. Our main function recieves an array
//of Strings named args and thats what we are using.
String name = args[0];
//uh-oh.. how do we use the String as a number that we can use to
//calculate how many second we are? Like this!
int ageInYears = Integer.valueOf(args[1]);
int ageInSeconds = ageInYears * 365 * 24 * 60 * 60;
System.out.println("You are " + ageInSeconds + " seconds old. Don't your feel ancient?");
}
}
You can also convert between the different number types, but using an even easier method!
CODE
int fifteen = 15;
char fifteenToo = (char) fifteen;
double heyMeToo = (double) fifteenToo;
float dontForgetMe = (float) heyMeToo;
So there you go.
PS: I made this mostly because I just reviewed casting and what not because I posted incorrectly on how to convert an integer into a string.
You use:
CODE
String string = "34";
int number = Integer.parseInt(string);
int numberToo = Integer.valueOf(string);
Not:
CODE
Integer.getInteger(string)