Reading Overloading Methods - java

I saw a question online that asks if you are given the print statements,
System.out.println(M.m(4.0, 5));
System.out.println(M.m(4, 5.0));
I understand that a double can be used as an int, so the first method will be printed. i.e 40.0.
But for the second print statement, wouldn't the same logic be used, and the first method be printed again? Java is saying the second print statment is 60.0.
public static double m(int a, int b) {
return a * b;
}
public static double m(double a, int b) {
return a * b * 2;
}
public static double m(double a, double b) {
return a * b * 3;
}

Actually, for the first print, the second overload will be used, because the parameter types match exactly: double and int.
For the second print, the third overload will be used, because double is not automatically promoted to int. The only method whose second parameter is promotable from double is the third overload - and that will force the first parameter to be promoted to double.

Since there's only one method that accepts double as the second parameter, the first parameter is going to be coerced into a double, so it would be called as M.m(4.0, 5.0) instead, thus falling into the third method.

Related

How would I use a wrapper class to call methods within a main?

public static void main(String[] args) {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
Given the main method above, how would I create a static method (as opposed a set of overloaded methods) which in turn would could successfully call the methods within the main?
Thanks in advance!
write a single static method (not a set of overloaded methods) which
can be called successfully by all the methods in main.
It is very basic, you can simply do that by creating a new static add() method (a single method contains the code for all calls to different overloaded add methods) as below:
public static void main(String[] args) {
add();
}
public static void add() {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
OK. I think I understand what your teacher wants, despite the wrong terminology he's using. He wants you to write a unique static add() method. And the code should compile and run after this unique add() method is being added to the code.
Since the method is called with arguments that are of type int, Integer, Double and double, the argument types must be a parent class of all these types (after boxing/unboxing). For example Number, or Object.
Since the returned value is assigned to a variable of type Double, Number and double, the return type must be a common class or subclass subclass of all this (after boxing/unboxing).
A candidate would thus be, for example:
private static double add(Object i, Object i1) {
return 0;
}
Of course, the ansX variables need to be renamed to answerX, too, otherwise the code will never compile.
I guess we can also safely assume that add() should add the arguments. I leave that as an exercise for your.
In order for the add method to be called successfully by the main method, you need to figure out what types to use for the return value and the parameters.
Here's a template:
private static ??? add(??? a, ??? b) {
return a + b;
}
As you can see, main calls add with all kinds of arguments, and it stores the result in different types of variables as well.
If you analyze the main method, you will see that the add method must be able to accept the following types of parameters:
(int, int)
(Integer, Double)
(int, double)
It can be deduced that an int, a double, an Integer and a Double can be implicitly converted to the parameters' type. If you do a little bit of thinking, you will know that double is one of the types that satisfy this requirement. This means that the parameters can be of tyoe double!
And it must be able to return a value that's compatible with the following types:
Double
double
Number
It can be deduced that the return type must be able to be implictly converted to Double, double, or Number. double also satisfy this requirement. This means that the method returns a double as well!
Here's the completed method:
private static double add(double a, double b) {
return a + b;
}

Overloaded function throws an error for float arguments

This is my Java program code. I overloaded the add function for the data types int and float, but the call add(2.3, 2.4) throws an error, instead of calling add(float, float).
public class Main {
public static void main(String[] args) {
// This calls add(int, int) as expected
System.out.println(add(2,4));
// This call throws an error
System.out.println(add(2.3,3.4));
}
public static int add(int a, int b){
return (a + b);
}
public static float add(float a, float b){
return (a + b);
}
}
You defined the overloaded methods correctly!
What you got wrong is the way you call the methods. You are calling add(2.3,3.4). 2.3 and 3.4 are all doubles. That's why they can't be directly put into a method that accepts floats.
"What? Why are they doubles?" you might ask.
By default, all number literals without a . or e are considered to be ints. And all number literals that has either or both a . or e are considered to be doubles.
To create a float literal, add f to the end of the numbers. i.e. these are all floats:
1f
1000f
1.1f
-9f
1e99f
So you should call your method like this
add(2.3f,3.4f)
There are add methods for int and float, while literal 2.3 has type double. There two ways to fix this:
Use float literals, i.e. 2.3f and 3.4f (notice the f suffix).
Define add method for doubles.

Overloaded Method calling in Java

Let's say I have 2 methods as such:
1 public int sum(int a, int b) { return a + b; }
2 public double sum(double a, double b) { return a + b; }
If I call sum, like so: sum(2, 3)
The first method will be executed
If I call sum, like so: sum(2.5,3.5)The second method is executed
However, if I call sum like such: sum(2.5,3), the second method is executed, but not the first, why is that?
Also, would this also be the case if sum was called as such: sum(3,2.5)?
The compiler will make the int into a double, calling the second method It is because, an int can be typecasted into a double, but not vice versa.
This will apply for all the primitive types going to the right. You can't go to the left, unless you explicitly typecast, which you aren't doing. If you wanted the first method to be executed, you could just typecast into an int, so that it doesn't widen into a double. Java is very specific about these things:
SO, in conclusion, when you call the method without typecasting the int, doing this:
sum(int, double);
is actually translating to this:
sum(double, double);
and to avoid this, you must typecast your int as an int.
Because, integers can be as floating-point numbers in Math.
So, sum(3,2.5) - here worth method signature is sum(double, double)!

Overloading methods

I saw below question posted on this site.
"What happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param".
I thought I understood the concept and wrote this code:
public class TestClass {
public static void main(String args[])
{
TestClass t=new TestClass();
t.sum(1/4);
}
void sum(double d)
{
System.out.println("Double==="+d);
}
void sum(int i)
{
System.out.println("Integer==="+i);
}
void sum(short s)
{
System.out.println("Short==="+d);
}
}
According to my understanding explained on this site (as mentioned above), I thought it will print Short===0, but to my surprise it prints Integer===0. Can any one explain this to me?
First of all, these are overloaded methods, not overridden methods.
1 and 4 are integers. Therefore 1/4 is an integer division, returning 0.
Therefore, the method being called is sum(int i).
sum(short s) would never be called for an int parameter, since that would require a narrowing primitive conversion (JLS 5.1.3), that may cause data loss, and is not allowed in method invocation conversion (JLS 5.3). Such a conversion can be done with an explicit cast.
If you remove the int version, sum(double d) would be called, and if you remove the double version, the code won't compile.
In order to call the short version, you must cast the parameter to short :
t.sum ((short)(1/4));
If you don't explicitly tell the compiler what are the types of 1 and 4, it assumes they are of type int. Then, / operator will apply integer division and will produce another int (which will be 0.)
After that, the method with the most specific to integer parameter type will be invoked. In your case, this will be sum(int i).
If you want to invoke some of the other overloaded methods, you will have to explicitly:
do a cast. For example, sum((short) (1/4)); will invoke sum(short s) due to the cast.
point the type of the operands. For example, sum(1d/4) will invoke sum(double d), since 1d/4 will result to double
For integer number, the type int is a default choice. So, although 1 and 4 can be defined as both int or short, since you did not defined anything, the compiler identified 1 and 4 as int and therefore it entered into the function for 1/4 division (0), which took the parameter int.

Why is Java picking this overload over the other

Could anyone explain to me why Java is picking the second overload instead of the first?
public static void foo (int a, double b, double...c) {}
public static void foo (double...a) {}
public static void bar ()
{
// this is the second
foo(1);
}
I thought when I pass 1 as the argument, Java would have picked the first argument because int is more specific than double?
Thanks
The second method is the only one that can match. You have only 1 argument. The first foo has at least two required: an int and a double, so that can't match.
The second foo matches because any number of numbers can match. Java will implicitly promote your int 1 to a double so it can match, with method invocation conversion.

Categories