• Post Reply Bookmark Topic Watch Topic
  • New Topic

calling a method that declares a return type but not assigning it to one  RSS feed

 
Brian Carlisle
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
looking at some exam prep code and came across this head scratcher...

I would think if you call a method that declares a return type and do not assign it the compiler would complain.

 
Paul Clapham
Sheriff
Posts: 22509
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But as you can see, it doesn't. That's because there is nothing seriously wrong with ignoring the value returned by a method.

And you're confused by methods which don't do anything? Sometimes the correct thing for a method to do is nothing.
 
Jayesh A Lalwani
Rancher
Posts: 2762
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How now, Brown Cow?

Yeah you don't have to get the return value. Sometimes, you don't care about the return value. For example, if you are reading a file line by line, and you want to skip the first 3 lines, you can call readLine() 3 times and not care about the return value




You can do this too, and I agree it looks bizzarre. I don't like doing it because it just makes it harder to read. THis is equivalent of



but it looks like it should do something like



which doesn't make sense in Java.. but this what my brain reads it as
 
Paul Clapham
Sheriff
Posts: 22509
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also: when you put your code into an IDE, you may find it gives you warnings when your code ignores the value returned by a method. This can occasionally be useful, by pointing out cases where you aren't using the method right or you didn't declare it right, but usually people know what they are doing (as in Jayesh's example) when they write code which ignores a returned value.
 
Brian Carlisle
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for the insight. Definately challenging to interpret as a newcomer. And they dont make it easy
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!