6

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 on line "doInt(99)".

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

Can someone explain why it's giving me the error.

4

5 回答 5

7

In java, the default type of an integer number is an int. Java will automatically upcast (eg from short to int), but will issue a warning with downcasting (eg from int to short) because of possible loss of data.

The fix for your code is this:

doInt((short)99);

This explicit downcast changes the 99 (which is an int) to a short, so there's no (further) possible loss of data.

于 2012-06-16T13:57:53.610 回答
4

Try

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

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

Java thinks that all literals (such as 99 or 100) in your program is int.

If you pass big number, 12345678 for example, it will be cutted to fit to short value. Java cannot cut number without you, so you must do it yourself. That way you see that you casting int to short

于 2012-06-16T13:57:35.303 回答
1

You need to cast 99 to a short. Please try the following

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

   public short doInt(short s)  { 
      return 100;
   }   
} 
于 2012-06-16T13:58:10.883 回答
1

int data type is generally the default choice unless there is a reason.

And hence 99 is treated as an int.

Read more details on Primitive Data Types

You need explicit casting when required.
Change doInt( 99 ) to doInt( ( short ) 99 ) and it should be working.

于 2012-06-16T14:00:24.330 回答
1

The main cause of error is

You cannot implicitly convert nonliteral numeric types of larger storage size to short

So change your code to following.

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

   public short doInt(short s)  { 
      return (short)100;
   }   
}
于 2012-06-16T14:00:51.053 回答