0

I wrote a simple program in java for finding out whether a number is a dudeney number or not :

import java.util.Scanner ;
public class dudeney_number
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in) ;
        System.out.print("Enter a number : ") ;
        int n = sc.nextInt() ;
        int temp = n ;
        int sum = 0 ;
        while(temp!=0)
        {
            sum+=temp%10 ;
            temp/=10 ;
        }
        
        if(sum==Math.cbrt(n))
        {
            System.out.println("Dudeney number") ;
        } else {
            System.out.println("Not a dudeney number") ;
        }
    }
}

I create a Scanner object (sc), input a number from the user (n) and find out the sum of the digits in the entered number (sum). I then check for equality between the sum of the digits and the cube root of the number entered using Math.cbrt(n) .

sum is an integer value with datatype int . Math.cbrt(n) returns a double value.
Why does the compiler not return an error when a 32-bit and a 64-bit value is compared ?

  • Why do you think it should? – Scott Hunter Aug 11 '23 at 17:35
  • if the value of the 64-bit datatype value is larger than the limit of the 32-bit datatype value, then comparison should not be possible... – Super Coder Aug 11 '23 at 17:37
  • Why not? Can't you just tell the 64-bit value is bigger without actually even knowing what the 32-bit value is? – Scott Hunter Aug 11 '23 at 17:44
  • What answer do you expect other than "Because the JLS doesn't say that it should"? – Sören Aug 11 '23 at 17:46
  • @ScottHunter but it equalises for some values like 512 – Super Coder Aug 11 '23 at 17:49
  • @Sören Then consider my question as "Why does the JLS not say that it should ?" – Super Coder Aug 11 '23 at 17:52
  • Because no on wrote it in there. Unless one of the authors of the JLS pitches in, this question is impossible to answer. – Sören Aug 11 '23 at 17:56
  • @SuperCoder Java is smart and it is performing type coercion behind the scene. This makes all sorts of comparisons possible, e.g. `int` to `long`, `byte` to `float` etc. – Shovel_Knight Aug 11 '23 at 17:57
  • @Shovel_Knight so it typecasts to a similar datatype. What datatype is it typecasting both of the variables to ? `int` or `long` ? – Super Coder Aug 11 '23 at 18:00
  • @SuperCoder not every `double` can be converted into a valid `int`, but every `int` can be converted into a valid `double`, so I would assume that in your case Java is casting `int` to `double` before actually comparing them. – Shovel_Knight Aug 11 '23 at 18:05
  • 3
    Under JLS 15.21.1 "Numerical equality operators", "...binary numeric promotion is performed on the operands" (5.6) - this leads to "widening primitive conversion" which states "If either operand is of type double, the other is converted to double.". – Computable Aug 11 '23 at 18:12

0 Answers0