Forums Register Login

Return Value Not Captured But Still Runs

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Errr... that's because you didn't capture the return value. Try:
String str2 = str.toLowerCase();
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Java doesn't care whether or not you use the return value from a method. This is a dubious legacy from C.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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);
+Pie Number of slices to send: Send
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.
You don't like waffles? Well, do you like this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 676 times.
Similar Threads
Deserialise SOAP Response
Calendar / Date arithmetic
Total Objects created ....
editable JCombobox need help getting text from user
Urgent! Pls Help! How to debug a Web Service?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:55:27.