Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JAVA Documentation Methods returns

 
momo mom
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the java online documentation related to SE7 classes (like the class StringBuilder) you can notice that the methods may have 3 types of return :

1) Return new Object : public String substring(int start)
2) Retrun a refrence to the object : public StringBuilder insert(int offset, String str)

3) Return this object : public StringBuilder replace(int start, int end, String str)

My question is what are the differences and similarities between these 3 types of returns.

Thanks



 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
momo mom wrote:1) Return new Object : public String substring(int start)
2) Retrun a refrence to the object : public StringBuilder insert(int offset, String str)
3) Return this object : public StringBuilder replace(int start, int end, String str)
My question is what are the differences and similarities between these 3 types of returns.

Well first of all, there are only two, since both 2 and 3 return this. And if you're quoting the docs verbatim, #1 returns "The new string".

The fact is that most methods return something; and in the case of StringBuilder, since its business is to build new Strings, and it's mutable, the fact that most of them return the StringBuilder they just modified allows you to chain operations, viz:

  System.out.println( new StringBuilder().append("World!").insert(0, "Hello ").toString() );

HIH

Winston
 
momo mom
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your clarification, that helped me a lot since i was not able to understand why 2 and 3 were different .

But someone can always ask you, why Oracle puts such confusing #3 return type in the above mentioned case ?
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
momo mom wrote:But someone can always ask you, why Oracle puts such confusing #3 return type in the above mentioned case ?

I have to admit it's not the best. When a method returns the object it's working on, I usually just put
Returns: this

However, the best programmers aren't always the best documenters (more's the pity).

Winston
 
this is supposed to be a surprise, but it smells like a tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!