Custom problems and short options in Java

I am trying to understand the following code:

public class A {
   private void doTask()  {    
      doInt(99);
   }   

   public short doInt(short s)  { 
      return 100;
   }   
}

The code gives a compiler error in the line "doInt (99)".

The method doInt(short) in the type A is not applicable for the arguments (int)

Can someone explain why he gave me an error.

+5
source share
5 answers

In java, the default integer type is int. Java will automatically rise (for example, from shortto int), but it will issue a warning with a decrease (for example, from intto short) due to possible data loss.

The fix for your code is:

doInt((short)99);

This explicit downcast changes 99(which is int) to short, so there is no (optional) possible data loss.

+7
source

Try

public class A {
   private void doTask()  {    
      doInt((short)99);
   }   

   public short doInt(short s)  { 
      return (short)100;
   }   
}

Java , (, 99 100) - int.

, , 12345678, , short. Java , . , , int

+4

99 . ,

public class A {
   private void doTask()  {    
      doInt((short) 99);
   }   

   public short doInt(short s)  { 
      return 100;
   }   
} 
+1

int , .

, , 99 int.

If necessary, forced casting is required. Change doInt( 99 )to doInt( ( short ) 99 )and it should work.

+1
source

The root cause of the error is

You cannot implicitly convert non-literal numeric types of a larger repository to short

So, change the code to the following.

public class A {
   private void doTask()  {    
      doInt((short)99);
   }   

   public short doInt(short s)  { 
      return (short)100;
   }   
}
+1
source

All Articles