0

Why primitive 1 consider as object and null as String here

public class Sample7 {

    public void getName(String s) {
        System.out.println(s + "string");
    }

    public void getName(Object o) {
        System.out.println(o + "object");
    }
}

class Test {
    public static void main(String args[]) {
        Sample7 s = new Sample7();
        s.getName(null);
        s.getName(1);
    }
} 

Output:

nullstring

1object

what is the logic behind the output ??

Anton Petrov
  • 316
  • 2
  • 10
user2155454
  • 95
  • 3
  • 12

2 Answers2

2

Primite values will be autoboxed to their object representations, so 1 will become Integer. But you don't have overloaded method for Integer, so it will match the Object, because Integer is an Object, but not a String.

null case on the other hand is a little bit more interesting. null can be any type of object, so in this case the most narrow type is String. This is why it matches String instead of Object.

If you add another method getName(Integer i), the compiler will throw Amgibigous method call error when calling s.getName(null) because of the same reason - null can be both String and Integer

CuriousGuy
  • 1,545
  • 3
  • 20
  • 42
1

Why is null considered a String:

Any variable/value in Java can be null, which is why you have nullstring given that you passed a String to getName(String s).

Why primitive 1 consider as an object

getName(Object o) Because your method does not have an explicit signature that accepts an Integer, all values in Java is an instance of Object, this is why getName(int) is mapped to getName(Object). 1 is an Object. Java does an implicit type conversion for primitive types [ String, int, double, float, boolean ] declared as Object. which is why you get the value 1.

Ndifreke
  • 732
  • 1
  • 8
  • 13