Let's see how to use casting in JAVA in a simple tutorial.
Let's see an example of casting variabless in JAVA, with String.valueOf() and Integer.valueOf() methods:
public class Main { /** * @param args */ public static void main(String[] args) { int theNumber = 12; String theString = new String(); int anotherNumber; theString = String.valueOf(theNumber); anotherNumber = Integer.valueOf(theString); theString = theString + 1; anotherNumber = anotherNumber + 1; System.out.println("theNumber = " + theNumber); System.out.println("theString = " + theString); System.out.println("anotherNumber = " + anotherNumber); } }
Result:
theNumber = 12 theString = 121 anotherNumber = 13
Indeed, theNumber is equal to 12 and if we transform it in a string with String.valueOf() method, we can add another character after the 2 of 12. So the "12" string is now "121".
But as the anotherNumber is an Integer, if we add 1 to 12, it will be transformed to 13.
Note that casting works with all JAVA variable types.
Add new comment