Java - Variable - Casting

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);




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

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.