Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoboxing not working in java

I have the following Java class:

public class HelloWorld{

    public static void main(String []args){

        String s = 23.toString();//compilation error is ';' expected
        s = s + "raju";
        System.out.println(s);
    }
}

but as per auto boxing 23.toString() must convert to new Integer(23).toString() and executes that line. So why am I still getting a compilation error?

like image 266
reddy Avatar asked Jan 27 '26 02:01

reddy


2 Answers

23 is of type int, not Integer. It is a primitive, not an object.

Integer.valueOf(23).toString();

This is better than using the constructor as the valueOf method will use cache values in the range -128 to 127.

You probably want to refer to this: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

like image 91
JamesB Avatar answered Jan 29 '26 15:01

JamesB


You're confused about when autoboxing is expected to work. In this case, you're trying to use an Object method on a plain old data type (an int).

Instead, try Integer.valueof():

public class HelloWorld{

    public static void main(String []args){
        // String s = 23.toString() will not work since a int POD type does not
        // have a toString() method.
        // Integer.valueOf(23) gets us an Integer Object.  Now we can 
        // call its toString method
        String s=Integer.valueof(23).toString();
        s=s+"raju";
        System.out.println(s);
    }
}

Autoboxing would work if you were passing that int to a method that expected an Integer as a parameter. For example:

List<Integer> intList = new ArrayList<>();
// Autoboxing will silently create an Integer here and add it to the list
intList.add(23);
// In this example, you've done the work that autoboxing would do for you
intList.add(Integer.valueof(24));
// At this point, the list has two Integers, 
// one equivalent to 23, one equivalent to 24.
like image 39
Bob Cross Avatar answered Jan 29 '26 16:01

Bob Cross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!