In a function can we pass void string(null) if the method is overloaded???

Dani AI

Generated

's phrase mixes two different ideas. In Java void is a return type and cannot be used as a parameter or value. The literal null can be passed to any parameter declared with a reference type (for example String) but not to primitive parameters like int. Overload resolution is done at compile time: the compiler selects the most specific applicable method, or reports an ambiguous call if two unrelated reference-typed overloads both accept null.

Example (most-specific wins):

class C {
    void m(String s) { System.out.println("String"); }
    void m(Object o) { System.out.println("Object"); }
}
new C().m(null); // prints "String" because String is more specific than Object

Example (ambiguous):

class C {
    void m(String s) { }
    void m(Integer i) { }
}
new C().m(null); // compile-time error: reference to m is ambiguous

Also note that null cannot be converted to a primitive, so an overload with a primitive parameter is not applicable when the call supplies null (the reference overload will be chosen if present). This expands on the brief points from and the other replies; see the Java Language Specification on overload resolution and the "most specific" rule for the formal details (JLS 15.12.2.5).

Recommended Answers

All 4 Replies

Stop posting your homework/quiz questions.

a String is never void.
And you can never pass a method.

Utter non-sense.

why cant you give a try

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.