Ok, I'm around 1/2 of the way through chapter 4 on Head First Java 2nd Edition. I really am having a hard time understanding returning values and what it's used for. I got the book around a week and a half ago, I've been studying Java in general for about a month. I never understand what returning values is for.
I understand what it means, for example, if you put "void" in the method name you can't return a value. Otherwise you can return values that have been declared.
Can someone explain to me, what this does exactly, why do you use it, when do you know to use it?
You use a "return" whenever... you need to return something. If you're performing a calculation or transformation, creating an object, anything. Sometimes you'll return an object you pass in. Sometimes you'll return the instance the method belongs to.
It's arguable that essentially all functions should return something (functional programming) rather than depending on side effects to do useful work.
your method is the behavior of class means it will perform something, Now how to see this behavior
1. By doing the calculation/operations/processing and returning the values.
2. By doing the calculation/operations/processing and returning nothing as void return type.
3. By passing the reference types as the parameter and processing it in the method and see the changed object where you called
it all depends the situations and what thins are available with you.
for example if you are using/making any utility method like "valueOf" then you need to return values from method.
if you are writing method for your own class needed in you module then you can go for 2nd or 3rd option.
Ben, the "return" is used to get the result of a method.
In it's simpilist form, you could have a method that let's say adds 2 to a number entered by the user. Of course something this simple could be done in the "main" method of the code, but as your programs get larger, you will want the "main" to be as concise and small as possible. So you will keep the methods seperate, and call them from the "main". Because methods are kept seperate from the main, you may need to "return" the result.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com