Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If int does not inherit Object, then why does "String.format(String, Object ...)" compile with int's?

Tags:

java

I read this post: Is int an object in Java?.

In the post it is argued that int is not inherited from Object. If so is the case, then why does the code below compile without any error? Given that int is not Object and the signature of format() method is public static String format(String format, Object... args) as shown in documentation: javadoc for String!

public class Testing {
    public static void main(String[] args) {
        int integer = 7;
        String str = String.format("%03d", integer);
        System.out.println(str);
    }
}

I have also read about "Autoboxing". What does this exactly mean? Are all the primitives replaced by appropriate Object's before compilation? If so, then is there any advantage of memory usage while using large array of int's (int[]) over Integer's (Integer[])? Similar arguments follow for double's etc.

Any insights are welcome.

like image 205
Sourabh Bhat Avatar asked Dec 15 '22 19:12

Sourabh Bhat


1 Answers

It is caused by Autoboxing.

Here is a small snippet from the linked Java documentation that explains it better than I could:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';

The rest of the examples in this section use generics. If you are not yet familiar with the syntax of generics, see the Generics (Updated) lesson.

Consider the following code:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(i);

Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(Integer.valueOf(i));
like image 178
mkobit Avatar answered May 20 '23 21:05

mkobit