Nishant Kumar
Nishant Kumar

Reputation: 6093

Method overloading in Java

import java.lang.Math;
class Squr
{
    public static void main ()
    {        
        Squr square = new Squr();
        System.out.println ("square root of 10 : " + square.mysqrt(10));
        System.out.println (" Square root of 10.4 : "+ square.mysqrt(10.4));         
    }

    int mysqrt ( int x)
    {
        return Math.sqrt(x);
    }

    double mysqrt (double y)
    {
        return Math.sqrt(y);
    }
}

When we compile it then it's giving error

possible loss of precision
found :double
required :int

I have written this program for calculating square root of int or double type values by method overloading concept.

How can I fix my error so I can find the square root of an int and a double?

Upvotes: 0

Views: 1293

Answers (3)

Bozho
Bozho

Reputation: 597402

My eclipse gives:

Type mismatch: cannot convert from double to int

Whatever the message is, you fix this by: return (int) Math.sqrt(x);

This has nothing to do with overloading though.

By the way, a square root of an integer can be double, so by having a return type int you are truncating possibly important information.

Hence I'd advise for simply using Math.sqrt(..) without making any additional methods. If you need the whole part, you can use Math.floor(..) or Math.round(..)

Upvotes: 2

Nishant
Nishant

Reputation: 55886

http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#sqrt%28double%29

returns double. Casting in int will loose precision. Don't you think so?

JLS has something to say on conversions. See this http://java.sun.com/docs/books/jls/third_edition/html/conversions.html

The following 22 specific conversions on primitive types are called the narrowing primitive conversions:

* short to byte or char
* char to byte or short
* int to byte, short, or char
* long to byte, short, char, or int
* float to byte, short, char, int, or long
* double to byte, short, char, int, long, or float 

Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision.

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103847

I don't think this is anything to do with method overloading - it's actually quite simple.

Math.sqrt() returns a double, but in your first class method, you're trying to return this directly from a method that returns int. This would be a lossy conversion, and you'd need to perform it manually.

In particular - when you call mysqrt(5), which integer do you expect the answer to be? 2? 3? Some "warning, not a whole number" value like -1? I suspect that perhaps you meant to return double for both methods, and differ only in the type of the arguments.

Upvotes: 4

Related Questions