What is the result?

Given:

class Overloading {
void x (int i) {
System.out.println(“one”);
}
void x (String s) {
System.out.println(“two”);
}
void x (double d) {
System.out.println(“three”);
}
public static void main(String[] args) {
new Overloading().x (4.0);
}
}

What is the result?

Given:

class Overloading {
void x (int i) {
System.out.println(“one”);
}
void x (String s) {
System.out.println(“two”);
}
void x (double d) {
System.out.println(“three”);
}
public static void main(String[] args) {
new Overloading().x (4.0);
}
}

What is the result?

A.
One

B.
Two

C.
Three

D.
Compilation fails

Explanation:
In this scenario the overloading method is called with a double/float value, 4.0. This makes the third overload method to run.
Note:
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists. Overloaded methods are differentiated by the number and the type of the arguments passed into the method.



Leave a Reply 4

Your email address will not be published. Required fields are marked *


Jazz

Jazz

“C”

As 4.0 is considered as Float/Double , we have x(double){…} so it results “three”

James

James

The Answer is C.

Code like this will compile as long as the methods are properly overloaded by having different argument types. Changing the return type or access modifiers won’t overload a method. To overload a method, you must have different argument types, number of arguments, or order of arguments. It’s the argument types that matter, not their names.

James

James

Also, overloaded methods must have the exact same names.