File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Associate Certification (OCAJP 7/8) and the fly likes Question regarding var-args Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Associate Certification (OCAJP 7/8)
Bookmark "Question regarding var-args" Watch "Question regarding var-args" New topic

Question regarding var-args

Deepa Chandrashekar

Joined: Oct 16, 2012
Posts: 24
Hi guys,

While studying for the certification, i came across this " Two methods with the same name, return type, access modifier but one contain int var-args and an other contain int[] and THEY ARE NOT DIFFERENT" so i tried to write a simple program for this which is,

The error on Line 15 is "The method arrays(int[]) in the type VarargsArray is not applicable for the arguments (int)"...
Q1) So does it mean i cannot call a method with argument int.
Q2) if i change the second method to private int arrays(int... var)
then will the program execute or will the method be overloading?
Please advise and Thanks in advance!

Greg Charles

Joined: Oct 01, 2001
Posts: 2968

First, please UseCodeTags.

Now, this code wouldn't even compile because two methods have the same name and signature. For the purpose of signatures, yes, int ... values, and int [] values are the same. However, there's a difference in how you call those two methods. In the first case, you can call it with a comma separated list of int values, where a single int value can be thought of as a list with just one value. When you define the parameter as a integer array though, then you must call it with an integer array argument. In either case, you would treat the parameter values as an int array within the method. So varargs are the same as arrays of args in some ways, and different in others.
Deepa Chandrashekar

Joined: Oct 16, 2012
Posts: 24
Thanks for the answer!
My question is if i change the access modifier and return type of second method will it be overloading?
Since var-args are similar to arrays but they cannot be interchangeable.

Please advise

Roel De Nijs

Joined: Jul 19, 2004
Posts: 8393

What's the rule of a valid overload? You MUST change the argument list, you may change return type, access modifier,...

So just changing access modifier and/or access modifier will not be a valid overload. That's something you can easily confirm using Notepad and javac (or using an editor).

Have a look at this thread.

SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
I agree. Here's the link:
subject: Question regarding var-args
It's not a secret anymore!