File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Boxing & Widening Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Boxing & Widening" Watch "Boxing & Widening" New topic

Boxing & Widening

Chris Judd

Joined: Feb 25, 2007
Posts: 23
Can anyone explain why this code outputs 3 4?

I don't understand why it would widen to Number and not to Long?


class Eggs {
int doX(Long x, Long y) { return 1; }
int doX(long... x) { return 2; }
int doX(Integer x, Integer y) { return 3; }
int doX(Number n, Number m) { return 4; }
public static void main(String[] args) {
new Eggs().go();
void go() {
short s = 7;
System.out.print(doX(s,s) + " ");
} }
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
I think you mean 4 3.

When a short is sent to a method that expects an object reference, then that short can be boxed into a Short.

Long is not a superclass of Short.

Number is a superclass of Short.

So (short,short) will match (Number,Number).
Chris Judd

Joined: Feb 25, 2007
Posts: 23
That's great. Thanks so much for clearing that up.

I agree. Here's the link:
subject: Boxing & Widening
It's not a secret anymore!