Search code examples
javanullternary-operatorjava-6

Java 6: Constructor argument, null and the ternary operator


Just for curiousity...

Assume I have a Class with two constructors:

public Class(){}
public Class(int x){}

and I want to create a new class through with the following statement below:

 new Class( ( true ) ? 100 : null);

Would this be acceptable? Will null instantiate the Class with the empty/default constructor? If not, is there a way to accomplish this with the ternary operator?

Note that I am on Java version 6.


Solution

  • You can do this

    Class cl = flag ? new Class(100) : new Class();
    

    By definition, the type of a ? : is the same as the last argument. i.e. Object, you cannot make it type less and value less.