This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pass by value

 
Carolina Carvajal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic