• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

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

 
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.

 
Marshal
Posts: 24594
55
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.
 
Rancher
Posts: 2759
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
Marshal
Posts: 24594
55
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!