This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills: The software developer's life manual and have John Sonmez on-line!
See this thread for details.
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return Value Not Captured But Still Runs

 
James Gordon
Ranch Hand
Posts: 106
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
String str = "A";
str.toLowerCase();
When I compile the above, no warnings/errors given! What's the reason for that as the second line is actually returning a String and its not captured.

Thanks in advance.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Errr... that's because you didn't capture the return value. Try:
String str2 = str.toLowerCase();
 
James Gordon
Ranch Hand
Posts: 106
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Perhaps I'm not that clear in my 1st posting but actually what I want to know is whether there is any specific reasons as to why Java allow that to happen.
s1.toLowerCase();
The statement above doesn't really has any effect unless we store the return value in a variable or print it out. And btw, where the return value
goes for the statement above (aren't we expecting a value from that)?

Thanks.
 
Ron Newman
Ranch Hand
Posts: 1056
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java doesn't care whether or not you use the return value from a method. This is a dubious legacy from C.
 
Philip Shanks
Ranch Hand
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perl also allows this to happen... I suppose it has it's uses in some cases, but I can't think of any good ones.
PCS
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes you *want* to ignore the return value.
For example, StringBuffer.append is returning the StringBuffer itself, so that you can write statements like:
strBuff.append(x).append(y).append(z);
If the compiler would force you to somehow use the return value, you had to write
strBuff = strBuff.append(x).append(y).append(z);
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the compiler's point of view, it can't tell the difference between methods like String's toUpperCase() and StringBuffer's append(). It would take a very sophisticated compiler to identify those methods which had no other side effects and which therefore should only be used by capturing a return value.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic