Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with casting and short parameters in Java

Tags:

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 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.

like image 884
Alan2 Avatar asked Jun 16 '12 13:06

Alan2


2 Answers

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.

like image 132
Bohemian Avatar answered Nov 10 '22 09:11

Bohemian


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

like image 27
alaster Avatar answered Nov 10 '22 09:11

alaster