2

when I do this code:

public class TryingOutReturn {
   public static void main (String[] args) {
      float numa = 2;
      float numb = 3;
      System.out.println(addition(numa, numb));
   }
   
   public static int addition (float num1, float num2) {
      float sum = num1 + num2;
      return sum;
   }
}

It gives me the

 ----jGRASP exec: javac -g TryingOutReturn.java
TryingOutReturn.java:10: error: incompatible types: possible lossy conversion from float to int
      return sum;
             ^
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

Why does java have difficulty returning me a value in float? I don't understand what it means by possible lossy conversion what does lossy even mean?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
ewe
  • 159
  • 1
  • 7
  • 1
    Just make public static ```float``` addition return type or cast it to int like that ```return (int)sum;```. Java cannot downcast types automatically. Check this out https://stackoverflow.com/questions/380813/downcasting-in-java – Antaaaa Jul 14 '20 at 19:07
  • 2
    You're not getting it _adding_ the floats, you're getting it _when trying to treat a float as an int_. – chrylis -cautiouslyoptimistic- Jul 14 '20 at 19:11

1 Answers1

3

"Lossy" in this context means you get a truncation and lose information. Like 1.11 (float) will become 1 (int), and you lose 0.11. Java is very strict about types (unlike many other language), which can be annoying.

To fix this error change your function return type to float like this:

public static float addition (float num1, float num2) {
  float sum = num1 + num2;
  return sum;
}

Also, to be consistent, re-declare your numbers to be float:

float numa = 2.0f;
float numb = 3.0f;
Dennis Kozevnikoff
  • 2,078
  • 3
  • 19
  • 29
  • oh so public static ... the next part specifies what type the returned variable should be? – ewe Jul 14 '20 at 19:21
  • When i try your suggestion I get error ```TryingOutReturn.java:3: error: incompatible types: possible lossy conversion from double to float float numa = 2.0; ^ TryingOutReturn.java:4: error: incompatible types: possible lossy conversion from double to float float numb = 3.0; ^ 2 errors ``` – ewe Jul 14 '20 at 19:24
  • 1
    ```float numa = 2.0f; float numb = 3.0f;``` A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d. – Antaaaa Jul 14 '20 at 19:26
  • 1
    yes, the part after static specifies what type to return – Dennis Kozevnikoff Jul 14 '20 at 19:29
  • 1
    Thank you too! @DennisKozevnikoff – ewe Jul 14 '20 at 19:30
  • *"... which can be annoying"* - And the flip-side is that it can be a life-saver if you didn't realize that your code could (essentially) mangle values due to a type mismatch in the return statement. It all depends what you want from the programming language. – Stephen C Jun 06 '21 at 13:16