[ACCEPTED]-String constructor with null value-string

Accepted answer
Score: 12

Normally, when you call a constructor or 18 method for which multiple overridden versions 17 might apply, Java will choose the most specific 16 constructor or method. Section 15.12.2 of the Java Language 15 Specification explains this in detail.

Suppose 14 you have two overloaded methods, like this:

public void method(Object o) {
    // ...
}

public void method(String s) {
    // ...
}

When 13 you call method(null), both these methods apply. Java 12 chooses the most specific one, which is 11 in this case the second method, that takes 10 a String - because String is a more specific type than 9 Object.

However, sometimes the most specific constructor 8 or method cannot be determined. If we look 7 at the constructors of class String that take 6 one argument:

String(byte[] bytes)
String(char[] value)
String(String original)
String(StringBuffer buffer)
String(StringBuilder builder)

Note that there is no hierarchy 5 between the types byte[], char[], String, StringBuffer and StringBuilder, so it's not 4 possible to say that one of these constructors 3 is more specific than the others. So, the 2 Java compiler doesn't know which constructor 1 to choose and will give you an error.

Score: 11

Because, compiler couldn't figure out which 4 constructor to call. See here that how many one-argument-constructor 3 it has.

[Edited] You said, if there is another reason. So 2 why not try out yourself. Do something like 1 this,

byte[] b = null;
String s = new String(b); // complier should be fine with this

char[] c = null;
String s = new String(c); // complier should be fine with this

.... // you can try other constructors using similar approach.
Score: 3

Just to add more clarity to the solution:

Take 10 this example:

public class Test {
public Test(Object obj) {
    System.out.println("Object");
}
public Test(String obj) {
    System.out.println("String");
}
public static void main(String[] args) {
    new Test(null);
}

}

It will not throw any compile 9 time error as compiler will choose the most 8 specific constructor of available same types. However, if 7 I change the class to:

public class Test {
public Test(Long lg){
    System.out.println("Long");
}
public Test(Object obj) {
    System.out.println("Object");
}
public Test(String obj) {
    System.out.println("String");
}
public static void main(String[] args) {
    new Test(null);
}
}

It will throw compile 6 time error. As two separate constructor 5 hierarchies are involved here and compiler 4 has no way to make a decision. One hierarchy 3 is: Object-->String and second is Object-->Long 2 so no way to choose between Long or String 1 type constructors.

Score: 1

String has many constructors. null is available 2 for them.

Edit: String has 5 one-argument-constructor, in 1 Java 6. Thanks BoltClock and Adeel Ansari!

More Related questions