When the Compilers Get Confused: Ambiguities in Java by@beardyweird

When the Compilers Get Confused: Ambiguities in Java

Kanav Arora HackerNoon profile picture

Kanav Arora

Ummm.... just a nerd coder

Java was founded in 1991, it has evolved a lot, but still, Java has some ambiguities. Ambiguities are the vagueness in some concepts. Some concepts are not well defined, and they have multiple interpretations.

Java is mainly derived from C++ and C. Unlike C++, Java is exclusively object-oriented. These ambiguities give different results when run on different compilers. This shows that while compiling, they all have different approaches for the same issues. Some of the ambiguities are mentioned below:

1. VarArgs in java

When using Varargs, method overloading is possible, but invoking an empty function compiler will give an ambiguity error.



prog.java:27: error: reference to testFun is ambiguous
  both method testFun(int...) in Test and method testFun(boolean...) in Test match
1 error

2. Varargs with other parameters

When using parameters with varargs while invoking a method may give an error in some cases.



prog.java:30: error: reference to testFun is ambiguous
                           + testFun(1, 4, 6, 8));
  both method testFun(int...) in Test and method testFun(int,int...) in Test match
1 error

In the above code, there are two methods with int as return type.

  • In the first method, varargs is the only parameter passed
  • In the second method, int and varargs are the parameters.

Now while invoking the method, e.g., testFun(4, 6, 8, 10), the compiler cannot identify whether the first parameter is from varargs or int. There is ambiguity, whereas the code will work perfectly fine if the first parameter is of a different data type.

3. Multiple Inheritance

Unlike C++ and python, java doesn’t support multiple inheritance because it leads to the Diamond problem. But Java does support multiple inheritance, but only with interfaces.



prog.java:26: error: '{' expected
public class D extends B, C {

4. Method Invocation

Method invocation may give an error of ambiguous reference of methods. Method invocation errors arise when there is both an inherited instance and a local instance at the time of invocation. Furthermore, the methods must be invoked with the widening conversion of parameters.



N.m(short x)
N.p(C x)

Outputs of these ambiguities may differ with different compilers. Java consists of some other ambiguities in core concepts such as security, multithreading, concurrency but they are advanced topics and are not covered in this article.

Show some ❤️ by following me, and if you like the article, please give it a clap. To connect with me on other platforms, visit my linktree: https://linktr.ee/kanavarora


Signup or Login to Join the Discussion


Related Stories