Because methods perform actions, and sometimes you need the results. Here is an example:
public string GetUserName(int userID)
What good would a method called GetUserName be if it didn't return the username?
2007-03-18 17:17:23
·
answer #1
·
answered by Rex M 6
·
0⤊
0⤋
You start out with your main method. Then you use that to do a little work BUT it should primarily call other methods. These methods will, in turn, call other methods and bring information back to your main method. Or they may call other methods and require information (i.e. return values) back.
Two major purposes of this is code organization and splitting up work between different people. Let's say you have to write a program that is a menu with two different options on it. You would write your main method like usual. You "could" just write everything in that main method but it would get very cluttered. So you might want to make a method called display_menu(). This method with give you your two options (and presumably an "exit" option). Then you would write a method to perform the actions required by the first option, and another method to do the actions for option two.
2007-03-19 00:25:27
·
answer #2
·
answered by hatevirtual 3
·
0⤊
1⤋
You need a method to return a value that is local to that method so that it can pass the value to the calling method. The calling method might use the value for other purpose.
For example
class Test
{
public static void main(String args[])
{
int result = sum(3, 5); // sum(3, 5) is the calling method
// the value that is return from the method sum() will be
// stored in the variable result
// then we can use the value for other purpose:
// e.g. calculate the middle value
int mid = result / 2;
System.out.println("Result: "+result);
System.out.println("Middle: " +mid);
}
public static int sum(int a, int b)
{
int x = a + b; // variable x is local to method sum
return x; //we return the value in variable x to the calling method
}
}
2007-03-19 00:23:40
·
answer #3
·
answered by Liviawarty J 2
·
0⤊
1⤋
Ya.. it wouldnt be much of an OO language if functions couldnt return values.
You could, of course, always declare void functions and have them edit public global variables.
ie.
class NoobProgrammer
{
public int var1;
public void changeVar(int i)
{
var1=i;
}
}
then use the object like so:
NoobProgrammer nP = new NoobProgrammer();
nP.changeVar(2)
System.out.println(nP.var1);
This is bad programming style though.. it would be much easier to declare the function with an int datatype then truncate the usage to one line:
System.out.println(nP.changeVar(2));
2007-03-19 00:27:42
·
answer #4
·
answered by thomas p 2
·
0⤊
1⤋