• Post Reply Bookmark Topic Watch Topic
  • New Topic

return keyword  RSS feed

 
Bron Czimes
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you return more than one variable from the same method?
for example, a boolean and an Integer???
 
Paul Santa Maria
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No - you can only return a primitive (such as an int or a boolean), or an object reference.

One solution might be to declare a class (one which contains your int and your boolean as methods), then have your method return a new instance of that class.

Another possibility is to revisit your design. If your method needs to return "two different things", perhaps it might be better to refactor your code into two separate methods.

Hope that helps .. PSM
 
Bron Czimes
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah it does, thanks Paul
 
clio katz
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i agree with paul's comment.

in some cases you can also modify attributes of objects passed in the parameter list. a java api example might be the 'getSize' method of Component:


Stores the width/height of this component into "return value" rv and return rv. If rv is null a new Dimension object is allocated. This version of getSize is useful if the caller wants to avoid allocating a new Dimension object on the heap.

Parameters:
rv - the return value, modified to the components size
Returns:
rv


this is a commonly used technique in older languages like C, where global scope variables are frowned-upon, and pointers abound. and it reflects a different approach to programming (top-down). it appears to be used less often in java.

java lang restrictions apply: you could only modify (i.e. "return") *objects* if modify-access to obj is permissible, and that support manipulation by reference (i.e. not wrapper classes like Integer).

would appreciate corrections or hearing from java gurus as to whether these notions 'violate the spirit' of the language
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may return an array of objects of same type, or an ArrayList of two objects - which excludes primitive types like boolean and int, till autoboxing gets released in 1.5 .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!