File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable Arguments In Java

 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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


------------------
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
 
Roseanne Zhang
Ranch Hand
Posts: 1953
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And don't forget that you can (in recent versions of Java) create on-the-fly arrays, which can often serve the same purpose:
'
 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roseanne,
i dont want it for a specific purpose like println or print it should work for any function.
 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai cindy,
hey u r writing the overloaded constructors i think its a most inefficient way of doing this problem
 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 154
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 602
7
Mac OS X Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks STEVE and MICHAEL,
thanks for your reply.
Praveen
 
praveen ankireddy
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 193
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks peter for the JSR
 
Henrik Bengtsson
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic