int a=2; a=Math.pow(a,a); 

Here is the code. He does not work. I do not see any mistakes. But the compiler swears: "Error: (199, 45) error: incompatible types: possible lossy conversion from double to int" As you understood, at the output it should turn out that a = 4.

    2 answers 2

    Java prohibits and non-omitted due to the fact that the method of the class Math's pow method returns you double and you want an int . The compiler also tells you that you can lose it this way.

    So you need to either cast the result to an int so

     int a=2; a=(int)Math.pow(a,a); 

    Or declare a variable as a double so

     double a=2; a=Math.pow(a,a); 
    • Thank. But why the compiler did not think that if you make pow of two integers, the result will also be integer? - Egor Randomize
    • one
      @EgorRandomize, because the compiler thinks he is more stupid than man. Those. he believes that you know about the type of the return value of the method and you know what you get at the output double. But at the same time declare the variable as int. The compiler got confused due to the fact that the programmer is not mistaken by default and, therefore, we asked him to explain to him better what you want from him. - Yuriy SPb
    • one
      technically, because Java does not have a return type polymorphism. Those. methods of int pow(int, int) and double pow(int, int) cannot be simultaneously declared - Roman Bortnikov

    I think you quite clearly wrote. Math.pow() returns a fractional number ( double ), it is obvious that you cannot assign it directly. Write for example:

     a=(int)Math.pow(a,a); 

    And by the way, this is not square and to the degree a . Be careful with int overflow.