0
short s1 = 4500, s2 = 9800;
short s3;
s3 = s2 - s1;
System.out.println("The difference is:- " + s3);

I ran this code and it is showing an error but work perfectly when I declare s3 as int. Why is this happening? The error it is showing is as follows :- ''' Main.java:15: error: incompatible types: possible lossy conversion from int to short s3 = s2 - s1; ^ 1 error '''

I tried running the code and I thought the code would run. But in mathematical operations it shows error and suggests that instead of short, byte variable use int variable.

Utkarsh
  • 1
  • 1
  • When asking questions related to errors, always show us the errors. If they are build errors, then copy-paste (as text) the full and complete build log from a [mre] (which you should also copy-paste) into the question. If you get dialogs or other messages when running post a screenshot. If you get an uncaught exception then use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to catch it and tell us all the details. – Some programmer dude Aug 10 '23 at 09:55
  • Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], and read [ask]. Then also read about [how to write the "perfect" question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), especially its [checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And lastly please learn how to [edit] your questions to iprove them. – Some programmer dude Aug 10 '23 at 09:58

1 Answers1

1

In Java, when you perform arithmetic operations on primitive data types, like shorts in this case, the resulting value is automatically promoted to at least an int before the operation is performed. This is known as "integer promotion." This is done to prevent potential loss of data or precision that might occur if the operation was performed directly with smaller data types like shorts or bytes.

Try this:

    short s1 = 3, s2 = 4;
    short s3;
    s3 = (short)(s2 - s1);

By adding (short) before the subtraction, you are telling Java to perform the subtraction as an int, and then explicitly cast the result back to a short. Just be aware that if the result of the subtraction is outside the range of a short, you may lose data or encounter unexpected behavior.

Akin
  • 11
  • 5