Search code examples
javacastingtypecast-operator

Use of type cast operator within print statement


I am having difficulty understanding why the following returns a syntax error in Java:

int integer1 = 5;
System.out.print("The value of integer1 is " + (String)integer1);

I've noticed that to bypass this error I could just create a new String variable initialized to the typecast value of integer1:

int integer1 = 5;
String cast = (String)integer1;
System.out.print("The value of integer1 is " + cast);

but this seems a bit unnecessary, especially if I'll only be displaying the value of the integer once.


Solution

  • You can only cast a primitive to another primitive or an object to a type it is an instance of. For example, you can cast a String to an Object and an int into a long. If you want an int in a string, use String.format or concatenation will handle the conversion automatically:

    System.out.print(String.format("The value of integer1 is %d", integer1));
    

    or

    System.out.print("The value of integer1 is " + integer1);
    

    BTW, An important thing in Java about primitives and casting is that you can't cast boxed primitives to other boxed types. For example if you have

    Integer foo = 1000;
    Long bar = foo;
    

    You'll get a ClassCastException, but

    int foo = 1000;
    long bar = foo;
    

    will work fine

    To do the same with boxed vesions:

    Integer foo = 1000;
    Long bar = foo.longValue();