File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "pass by value" Watch "pass by value" New topic

pass by value

Carolina Carvajal

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;
public static void max (int value1, int value2, int max)
{if (value1>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)" 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.
[ November 05, 2003: Message edited by: Carolina Carvajal ]
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
Java does not pass by 'reference' 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-
I agree. Here's the link:
subject: pass by value
It's not a secret anymore!