aspose file tools*
The moose likes Beginning Java and the fly likes pass by value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "pass by value" Watch "pass by value" New topic
Author

pass by value

Carolina Carvajal
Greenhorn

Joined: Nov 05, 2003
Posts: 1
Im really confused by the whole pass by value thing.
Take this example from my book:
public class ch4question6
{
public static void main (String [] args)
{
int max=0;
max(1,2,max);
System.out.println(max);
}
public static void max (int value1, int value2, int max)
{if (value1>value2)
max=value1;
else
max=value2;
}
}
I know it means that a copy of the value outside the method is being passed on. So does this mean that "max(1,2,max)" is being passed on to the parameter "(int value1,int value2,max)"
k...im starting to realize this is a dumb question. let me know if im right.
ALSO, why is "int max=0" there? Whats the point of that statement? The program cant run without it, thats for sure.
THANKS!
[ November 05, 2003: Message edited by: Carolina Carvajal ]
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
Java does not pass by 'reference'...it ONLY passes by value. What this means is that when a method (in your example 'max()') changes a variable, it is NOT changing the original variable...only a copy of it. So, if you were to watch this program run in a debugger, you should see the method 'max' create a new variable to represent the value that was passed ( the 0 assigned to max ). After the method completes, this second 'variable' is destroyed, which is why this program prints a '0'. If Java were to pass by 'reference', then the method would be allowed to operate directly on the original variable/memory slot, thus altering the only copy of the value. Visual Basic.NET and others allow you to choose how you will pass a variable/object. Java does not.
Also, the reason for the 'int max = 0' line is, of course, to declare and initialize the variable 'max'. If you take out the '=0' part, you will get an error stating that 'variable 'max' may not have been initialised'. If you take out the whole line, you will get a compiler error that 'variable max not found in class ch4question6'. Anyway, hope that helps!


David Crossett
-nothing important to say, but learnin' plenty-
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: pass by value