File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes default arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "default arguments" Watch "default arguments" New topic

default arguments

fred cook

Joined: Jun 13, 2001
Posts: 8
First of all, is there such a thing in Java called default arguments or default parameters. If so, how do you do it? Tell me if this would be correct usage of a default argument (if there is one):
public void myMethod (int myDefault = 0)
Matthew Phillips
Ranch Hand

Joined: Mar 09, 2001
Posts: 2676
I haven't seen a method definition like that, but let me see if I understand what you want to do. If you want your method to accept a parameter, but be able to run without it then you need to overload the method. Overloading the method allows you to define several methods with the same name, but different parameters. For example:

By overloading the method you allow an outside source to call it with a parameter or without. If it is called without a parameter, a default value will be set and then the method with the parameter will be called with that default method.
Matthew Phillips

[This message has been edited by Matthew Phillips (edited June 13, 2001).]

Matthew Phillips
fred cook

Joined: Jun 13, 2001
Posts: 8
The main reason I ask this is because I know you can do it in C, but I don't want to overload my function (too much repeated code). If anyone else knows for sure whether or not Java has default arguments let me know.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
No, you need to overload the method to achieve that. It is ONLY 4 lines of code there is nothing of substance repeated. Whats the big deal?

[This message has been edited by Cindy Glass (edited June 13, 2001).]

"JavaRanch, where the deer and the Certified play" - David O'Meara
fred cook

Joined: Jun 13, 2001
Posts: 8
OK, yes that works...but I just need to know whether there is such a thing as default arguments, or do I HAVE to do that.
[This message has been edited by fred cook (edited June 15, 2001).]
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Method headers and method calls must agree in number, type and order of parameters and arguments.

So I think the answer is no, and yes.

No, there are no default parameter values in Java, and Yes, you have to do that (overload).
Conrad Kirby
Ranch Hand

Joined: Jun 17, 2001
Posts: 178
Thanks you guys! (this is the same person as 'Fred Cook')
I agree. Here's the link:
subject: default arguments
jQuery in Action, 3rd edition