Thursday, March 29, 2012

int compatibility problem

Java is a bit funny, where it allows this:

short x = 7;


And C# would allow this:
class Alien
{
 internal string invade(short ships) { return "a few"; }
 internal string invade(params short[] ships) { return "many"; }
}
 
 
class Program
{
 public static void Main(string[] args)
 {
  short x = 7;
  System.Console.WriteLine(new Alien().invade(7));
 }
}

C#'s output:
a few



Java does not allow this:
class Alien
{
 String invade(short ships) { return "a few"; }
 String invade(short... ships) { return "many"; }
}


class Main
{
 public static void main(String[] args)
 {
  short x = 7;
  System.out.println(new Alien().invade(7));
 }
}

As Java decided that 7 is an int when being passed to a method, and there's no matching method that accepts an int, hence the above code will not compile


Compilation error:
Main.java:13: cannot find symbol
symbol  : method invade(int)
location: class Alien
  System.out.println(new Alien().invade(7));
                                ^
1 error


Java lacks symmetry here. 7 can be assigned to short, but it cannot be passed to short. Might be by design, think component versioning issue. To fix the above problem. cast 7 to short:

System.out.println(new Alien().invade((short)7));

Output:
a few


Java is the odd one out, this would compile in C++:
#include <iostream>
using namespace std;

class Alien
{
    public: char* invade(short ships) { return "a few"; }
};


int main() 
{
    printf( (new Alien())->invade(7) );
    return 0;
}

No comments:

Post a Comment