aspose file tools*
The moose likes Java in General and the fly likes Variable Arguments In Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Variable Arguments In Java" Watch "Variable Arguments In Java" New topic
Author

Variable Arguments In Java

praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
I want to implement the variable arguments the one present in c and C++ in java can any one suggest a method or any help from API to implement this.Hope everybody knows about variable arguments.for those who dont know it is as follows.
im explaining this in context of c:
in c for example take printf() funciton or scanf().
it accepts any number of arguments.
the same way i want it in java is there any method plz
let me know
Thanks
PRaveen Ankireddy


------------------

P Ankireddy
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
print and println can take any number of arguments as long as you concatenate them with the + sign.
public static void main(String args[]){
int i = 2;
int j = Integer.parseInt(args[0]);
//etc.
System.out.print(i + " " + j);
}


"JavaRanch, where the deer and the Certified play" - David O'Meara
Roseanne Zhang
Ranch Hand

Joined: Nov 14, 2000
Posts: 1953
I don't think Java can do c like variable arguments. But you can get around it by String concatenation in println(), using InputStrean to replace scanf.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
And don't forget that you can (in recent versions of Java) create on-the-fly arrays, which can often serve the same purpose:
'


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
hai cindy,
I think u didnt understand my question i asked how to implement variable arguments not the printf and scanf.
The problem is like this
Assume there is a method call ADD()
it should accept any number of arguments and return there sum.
like if v give ADD(1,2,3) it has to give 6
if v give ADD(2,3) the reslut should be 5
hope u got the problem
Regards
PRaveen
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
Roseanne,
i dont want it for a specific purpose like println or print it should work for any function.
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
Frank,
can u do the same thing for this problem
The problem is like this
Assume there is a method call ADD()
it should accept any number of arguments and return there sum.
like if v give ADD(1,2,3) it has to give 6
if v give ADD(2,3) the reslut should be 5
hope u got the problem
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
OK. I'd kinda hoped you would be able to work it out from my other example, but here it is:

[This message has been edited by Frank Carver (edited February 09, 2001).]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Franks method is the elegant way to do it, however if you want to do it the hard way, or if you have special handling depending on how many arguments you take in you can have a class with multiple constructors, each handling a specific number of arguments as input. Of course with this method there is a limit because the class will only handle as many arguments and you got around to creating constructors for.
Tejas Kansara
Ranch Hand

Joined: Dec 14, 2000
Posts: 38
Originally posted by praveen ankireddy:
I want to implement the variable arguments the one present in c and C++ in java can any one suggest a method or any help from API to implement this.Hope everybody knows about variable arguments.for those who dont know it is as follows.
im explaining this in context of c:
in c for example take printf() funciton or scanf().
it accepts any number of arguments.
the same way i want it in java is there any method plz
let me know
Thanks
PRaveen Ankireddy


Tejas Kansara
Ranch Hand

Joined: Dec 14, 2000
Posts: 38
Hi friend,
I think the following code will help you out.
Just compile this program and execute it by giving the following :-
java CmdArgu 2 4 6
OR
java CmdArgu 1 2 3 4 5 6
and so on.
----------------------------------------------------------------
class CmdArgu
{
public static void add(String[] store)
{
int sum=0;
for(int i=0;i<store.length;i++)
{
sum += Integer.parseInt(store[i]);
}
System.out.println(sum);
}

public static void main(String args[])
{
add(args);
}
}
----------------------------------------------------------------
Tejas Kansara
Ranch Hand

Joined: Dec 14, 2000
Posts: 38
I think this will help you out.
Just compile the file and pass following at command line:-
java CmdArgu 1 2 3
OR
java CmdArgu 10 30 50 20
and so on.
_______________________________________________________________
class CmdArgu
{
public static void add(String[] store)
{
int sum=0;
for(int i=0;i<store.length;i++)
{
sum += Integer.parseInt(store[i]);
}
System.out.println(sum);
}

public static void main(String args[])
{
add(args);
}
}
______________________________________________________________
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
hai cindy,
hey u r writing the overloaded constructors i think its a most inefficient way of doing this problem
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
hai frank,
thanks for ur reply.i can understand both of the replies u have given but here u r creating a array,but any user doesnt create an array and send it as an argument.right hope u understood my problem.
Regards
praveen ankireddy
Grant Crofton
Ranch Hand

Joined: Nov 08, 2000
Posts: 154
I'm pretty sure there is no equivalent of C-style 'variable number of arguments' functions in Java.
If you want to create that effect you'd have to use arrays, overloaded methods or something similar.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I thought I did understand your problem, and gave what I hoped was a valid solution. What is preventing you from using this approach? Is the interface to your method specified by someone else, and if so, how precisely have they specified it?
Steve Fahlbusch
Bartender

Joined: Sep 18, 2000
Posts: 561
    
    7

Basically the answer is no java does not have an equivalent to var-args. The problem with arrays is:
1) var-args is great in that args are not homogenious, and
2) do not require the user of the method to encapulate parameters
in the arrays.
Of course this can be countered with an array of Objects. Not as easy or straight forward, and a little more (not much) work
on the back end.
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Praveen,
Oh, I agree with you, that is a lousy way to do it, but then Frank already gave you the good way to do it.
Why doesn't any user create an array and send it in???
If it is another programmer using your class, they darn well better be able to send in an array.
If it is an end user inputting the values, the input comes in already as an array of Strings. Am I missing something???
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Since how to approach Praveen's problem with a solution has been answered, I thought I'd give the doom answer like Steve. NO. You can't do it.
The compiler distinguishes among all methods in a class by their signature. Part of that signature is the parameter list itself. And the parameter list is materially important in the number, order, and type of arguments presented.
Passing in an argument list that is arbitrarily long is not possible, therefore, unless the parameter type itself holds an arbitrary number of objects. An array is in fact a viable answer because arrays in Java can be sized at runtime.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
[This message has been edited by Michael Ernest (edited February 19, 2001).]


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
Thanks STEVE and MICHAEL,
thanks for your reply.
Praveen
praveen ankireddy
Greenhorn

Joined: Feb 07, 2001
Posts: 22
hai cindy,
First let me xplain how it is done in c
add(*,"arg1,arg2,......)
{
// code goes here
}
this is how it looks in c u can just access it this way
add(arg1,arg2,......)

the thing in the double quotes is taken as a string and the using the pointer v can separate the arguments.Ok hope u got how its handled in c.
Now coming to ur question
Y cant a user send a array.
Ofcourse my dear he can ,dont u think its not a tedious method of creating arrays and passing them instead of just passing arguments separated by commas.I think theres no solution in java like c.U better go through the replies of Steve and Michael.ok
Any how thanks for your reply
Praveen
Elisabeth Van
Ranch Hand

Joined: Feb 09, 2001
Posts: 42
Is there just a serious case of array-phobia going on around here? I find it hard to see why an array would be any more difficult to handle than a list of comma-separated arguments.
If you look at Michael's answer, I believe he's agreeing with Cindy on this one--that an array IS the solution.
An array is in fact a viable answer because arrays in Java can be sized at runtime.

rehan hamid
Greenhorn

Joined: Feb 13, 2001
Posts: 16
In addition to all, think about main(String argv[]), you can see, main exhibits variable arguments in-take from command line. This has been implemented by Arrays that is one of the best solution for this problem.
This was just to share my thoughts as solution has been unveiled by many here
Software Engg
Greenhorn

Joined: Feb 19, 2001
Posts: 10
hai Elisabeth,
I think u r not understanding praveens point of view.Ofcourse arrays is one of the solution but do u create arrays and send them as arguments in c for printf and scanf sort of functions you dont right.he wants the solution in that way.So Praveen theres no solution as v have in C
So try to understand the topic instead of giving the same answers again and again
Elisabeth Van
Ranch Hand

Joined: Feb 09, 2001
Posts: 42
I understand that Praveen is saying that you can't pass the arguments in the same way that it can be done in C. Java is not C, so people are offering solutions that will accomplish the same results in Java as were possible in C. It just appeared to me that Praveen was rejecting solutions that didn't work exactly the way things do in C.
If I misunderstood, I certainly apologize.
Raghvendra Sharma
Ranch Hand

Joined: Oct 09, 2000
Posts: 82
Dear Friends,
I think i have just read one of the most educating discussions on JavaRanch.
I think all the probable solutions given by either cindy, or frank doesn't address the main issue. The issue is not "omplementing" variable argument behaviour, but it is "actually passing" variable arguments. What is happening in the available solutions is that you people are creating arrays of objects and then passing that "single" object as the argument, effectively passing a fixed number of argument, that is one.
So, i think the core issue remains unanswered, how to pass variable number of arguments. Of course method overloading is a solution but praveen is quite correct in saying that it is very ineffecient.
The approach given by Michael Ernest is quite digestable, since the compiler cannot accept undefined lenght of parameter list.
I want to put up a qustion related to this, Why cannot compiler accept the whole parameter list as an array and then parse it at runtime. This way the variable number of arguments shall be available to the programmer but the compiler shall be able to manage this as a single parameter call.
Hope to get some type of answer.
regards
Raghav..
Software Engg
Greenhorn

Joined: Feb 19, 2001
Posts: 10
S i agree with ragav,
Answering your question.I dont know y the compiler cant handle this variable arguments,but i think the people who have developed compiler has not considered this issue while developing.May b somebody should change and develop a new one.I think so if something wrong in my opinion plz forgive me
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I don't quite understand why anyone would thing that the syntax of creating a new array on the fly somehow limits the number of elements that array may contain. When creating an array like this I am free to put 1, 10 or even 1000 elements in it (if I can be bothered to type them). Java creates an array which is precisely the right size for the number of elements I supply - there is no knowledge or dependency in the method which I am calling on how many elements the array must contain.
As far as I can see, the main difference between this syntax for variable argument passing and the style used in C and C++ is the extra typing required to say "new Object[] {" before the argument list, and "}" after it. Is this really so bad? It gives lots of benefits which the C/C++ version doesn't: you can count the arguments, you can pass in object types and not just primitives, you can call one "variable-args" method from another without headaches (try that in C/C++!) and so on ...
Can anyone propose a real-world example where this syntax for variable parameters would not be a valid solution. I'm fascinated to see why so many people seem to think it is not acceptable.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Software Engg:
Answering your question.I dont know y the compiler cant handle this variable arguments,but i think the people who have developed compiler has not considered this issue while developing.May b somebody should change and develop a new one.I think so if something wrong in my opinion plz forgive me

Ah, but somebody already is. Sun, to be precise
It has already been mentioned that the C-style variable length argument list is just an array - just like Java - with some syntactic sugar to make it look like any other argument list. There is currently a Java Specification Request in the expert group stage that should give Java almost the same sugar topping:

The only difference to C/C++ are the curly braces indicating an array. The JSR proposes that the compiler interpret this as an Object[] array and automatically boxes primitive types (e.g. int) inside objects (java.lang.Integer).
Do have a look at the URL! It covers everything that has been discussed in this thread and more.
HTH
- Peter
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Frank Carver:
I don't quite understand why anyone would thing that the syntax of creating a new array on the fly somehow limits the number of elements that array may contain.

Neither do I. Especially seeing that C/C++ are supposed not to suffer from this problem, while under the hood they use the same method.
As far as I can see, the main difference between this syntax for variable argument passing and the style used in C and C++ is the extra typing required to say "new Object[] {" before the argument list, and "}" after it. Is this really so bad?

Not only do you have to say "new Object[]", but you also have to explicitly box primitives into their object counterparts. Instead of
f(new Object[] { new Integer(5), new Float(1.3) });
wouldn't it be much nicer to just say
f({5, 1.3});
- Peter

[This message has been edited by Peter den Haan (edited February 21, 2001).]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Wow!! We missed the Chained Method approach! Thank you Peter for the link.
So how do we find out if this has been approved? Since the editing was closed 5-3-2000 does that mean it IS approved? And how do we find out what release of Java this will be in???
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

I'm about as excited for this JSR as I was about inner classes. Who really *needs* this kind of sugar added to the language? Is it really that life-sapping to create an array and pass it ourselves?
Code maintainers in my experience prefer code that does not make them guess at the 'hidden feature' support.
Just my crabby $0.02
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
Graeme Brown
Ranch Hand

Joined: Oct 13, 2000
Posts: 193
Praveen
Thanks for sparking off a really interesting discussion.
I agree with Michael on this one. The benefits of the new reduced syntax are minimal, and there is potential for error. By having to explicitly create the array it makes the intentions of the original programmer clear and makes for simpler maintenance.
There is also a question of consistency with existing code, Java programmers are quite used to passing object arrays into methods where variable argument lists are not required. To have two different ways to achieve exactly the same result only adds a layer of unnecessary complexity.
Software Engg
Greenhorn

Joined: Feb 19, 2001
Posts: 10
thanks peter for the JSR
Henrik Bengtsson
Greenhorn

Joined: Oct 30, 2001
Posts: 2
FYI: Check out my com.braju.format.Parameters class which provides variable number of arguments like this
Parameters p = new Parameters();
Format.printf("%d bytes in %d seconds (%.2f KB/s)\n",
p.add(nbytes).add(seconds).add((double)nbytes/1024/seconds));
Henrik


Henrik Bengtsson<P>M.Sc. Computer Science<BR>Ph.D. student in Statistics<BR>Lund University, Sweden<BR>h e n r i k b @ b r a j u . c o m
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variable Arguments In Java