-5

An interviewer asked me to explain this code. What does it do?

public class Test {
    public void methodOne(Object obj) {
        System.out.println("Object as Parameter");
    }

    public void methodOne(String str) {
        System.out.println("String as parameter");
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.methodOne(new Object());
        t.methodOne("");
        t.methodOne(null);
    }
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
  • You know, for how frequently this seems to show up in interview questions I could never quite figure out why this would be useful. – awksp Jun 14 '14 at 05:22
  • 4
    This question appears to be off-topic because it is about an interview question and not a real programming issue you are facing. – Jeremy J Starcher Jun 14 '14 at 05:25
  • I'm not sure about his intention here. But I wanted to know how the JVM will behaves here!!! – user3739737 Jun 14 '14 at 05:27
  • What are your thoughts on the matter? – Michael Petrotta Jun 14 '14 at 05:28
  • I'm getting the output like this Object as Parameter String as parameter String as parameter then I tried to add another method public void methodOne(Integer str){ System.out.println("Integer as parameter"); } here, when I'm calling the method with null parameter I'm getting compilation error java.lang.Error: Unresolved compilation problem: My question here is, why I'm not getting same compilation error for my first program? – user3739737 Jun 14 '14 at 05:34
  • 3
    It should take about 5 seconds to find out by running the program... – jahroy Jun 14 '14 at 05:37
  • I'm thinking "it's a trap" because the code looks trivially easy to be a serious question on an interview. – apxcode Jun 14 '14 at 06:26
  • 1
    Possible duplicate of [Method Overloading for NULL parameter](http://stackoverflow.com/questions/5229809/method-overloading-for-null-parameter) and [Using null in overloaded methods in Java](https://stackoverflow.com/questions/13041042/using-null-in-overloaded-methods-in-java). – jww Jun 14 '14 at 07:00

1 Answers1

0
$ java -version
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

And:

$ javac Test.java 
$ java Test
Object as Parameter
String as parameter
String as parameter
jww
  • 97,681
  • 90
  • 411
  • 885