1
votes

We already know that the return type of Math.lang() function in java is double.

class Lossy {
    public static void main(String args[]) {
        int sum;
        sum=Math.pow(2,3);
        System.out.println (sum);
    }
}

Now this statement results in possible lossy conversion error because the variable is of type int and Math.pow() return a double value i.e. 8.0 which is fair enough.

Now look at the code below with some changes.

class Lossy {     
    public static void main(String args[]) {
        int sum=2;
        sum+=Math.pow(2,3);
        System.out.println (sum);
    }
}

Now if we compile this code we don't get an error of possible conversion error, which we should get because we are storing a double value in an integer variable. Moreover, when we are printing the value it shows an integer value. Why?

1

1 Answers

1
votes

In the first code, you are assigning a double value to a integer variable. since double value needs 8 bytes whereas integer needs only 4 bytes of memory. We cant store a 8 bytes value into a 4 bytes variable. That's why it shows possible loss of conversion error.

class Lossy
  {
   public static void main(String args[])
  {
    int sum;
    sum=Math.pow(2,3);   //Assigning double value to a int variable. its an Error
    System.out.println (sum);
 }
 }

In the second example you are not simply or directly assigning a value to a integer variable. but you used an add and assign operator(+=), which functions as follows:

sum+=Math.pow(2,3) is equal to sum = sum + Math.pow(2,3);

When you do like the above one, JVM performs Automatic Type Conversion(double to int) or Parsing for the function Math.pow() and it converts the return value of the function to int while compilation. So it works fine. I hope you understand. Thanks!