Credits

Monday, March 23, 2009

Java's Data Type Cast

When we read from the keyboard, it is by default that we enter the inputs as a string. Thus, it makes a problem if we need to perform computations or calculations on this input.

This can be however remedied using type cast. Type cast function allows us to convert a given value to another data type.

We can convert an input or constants from int to char, float, byte, long and vice versa.

For instance:

[+/-] show/hide


char x='3',y='4';
int total;
String xtotal;
xtotal=x+y;
System.out.print("The sum of x and y"+xtotal); //this gives us a result of xy
total=int(x)+int(y);
Systm.out.print("the total is "+total); // this however results to 7
//where char is converted to int

In an IDE mode, if a text fields which are strings in values, are used for x and y and we perform the operation above and assign it to another text field defined as Result, it will appear as:

int total;
total=Integer.parseInt(x.getText())+Integer.parseInt(y.getText()); //converts the string to integer type
Result.setText(total+""); //displays the result of total


AddThis