File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Cattle Drive and the fly likes Printing in void method vs returning a  value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "Printing in void method vs returning a  value" Watch "Printing in void method vs returning a  value" New topic

Printing in void method vs returning a value

Eviano Afiemo

Joined: Mar 20, 2001
Posts: 21
Question based on Nitpick for Assignment4
given the following example
class DoStuff
public static void main( String[] args )

System.out.println( doSomething(param) ) ;
static int doStuff(int param)


return value ;
}//How about if you just print it instead of returning it."(nitpicker's comment)
Since it's been suggested that I print the value out in the doStuff() method,
there's obviously a good reason for doing this.
What I'd like to know is what this reason is.
Does this imply thatit is more efficient to use void methods rather than methods which return values?

Thanks in advance
Johannes de Jong

Joined: Jan 27, 2001
Posts: 5089
Without seeing the actual code, the only reason that I can think of is that you do it, the print, where it logically belongs.
Adam Vinueza
Ranch Hand

Joined: Apr 16, 2001
Posts: 76
I can see what one of my nitpicks will be on Say(a) now; ironically, I originally used a void method, but then changed it to a String method. The nitpick seems reasonable, so I guess I'll be changing it back.
My own two cents is that if you're going to do something with a string after you've called someMethodOrOther() on it--say, if you need to compare the return value of someMethodOrOther() with another string--the method should return the string. But if all you're going to do with it is print it after someMethodOrOther() has done what you wanted it to do, you might as well let the method be void and insert a print command into it.
Eviano Afiemo

Joined: Mar 20, 2001
Posts: 21
Thanks for the reponses.
I guess it makes sense to print immediately if nothing else is to be done with the String in question.
I'll put Adam's suggestion in my list of things to watch out for, unless someone else thinks otherwise.
Pauline McNamara

Joined: Jan 19, 2001
Posts: 4012
Hi Evi,
I found the following thread to be a very informative discussion about "printing on the go" as opposed to creating String variables:
Hope it helps you as it did me,
I agree. Here's the link:
subject: Printing in void method vs returning a value
It's not a secret anymore!