What is the difference between Object Data Type & Primitive Data Type? [closed]

I’m a newbie to Java. And I have recently come to know that we can initialize same primitive data type as below:

Object name="Surendra";
Object age=27;

instead of

String name="Surendra";
int age=27;

What is the difference between these two definition and why/when should we use which one?.

Also, when we should int primitive data type and the Integer wrapper class.

Appreciate it if you can explain it in layman terms.

Answer

When you do this:

Object name = "Surendra";
Object age = 27;  // Actually Integer here, not int

You are casting String and Integer to Object, which totally safe, since String is of course an Object, so is Integer. However, the following code won’t compile, because even though name stores a String, java compiler have no idea about it. The compiler searches for a method called trim in Object class, and found nothing, so it refuses to compile. It’s the same for age.

name.trim();  // Won't compile
age.longValue();  // Won't compile

When to use Object? When you have no idea about the type as well. For example:

public static void foo(Object o) {
    if (o instanceof String) {
        String s = (String) o;
        // ...
    }
    if (o instanceof Integer) {
        Integer i = (Integer) o;
        // ...
    }
}

You can do an instanceof check and determine which operation to perform.

Talking about Integer and int, they are completely different. Integer is an Object, but int is not. int is a primitive type. You convert int to Integer by boxing and convert Integer to int by unboxing. Modern java compilers will do the boxing or unboxing for you. You mostly use Integer as a generic type parameter, such as List<Integer>. You can’t use List<int> in java, since a type parameter must be an Object. Sometimes you also use Integer when you want null to be an valid value. Notice that when java performs auto unboxing on null, it will throw an NullPointerException. Be aware.

// These 2 are identical
Integer o1 = 0;  // Auto boxing
Integer o2 = Integer.valueOf(0);  // Boxing

// These 2 are identical
int i1 = o1;  // Auto unboxing
int i2 = o2.intValue();  // Unboxing

Integer o3 = null;  // Works
int i3 = null;  // Won't compile