• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

pass by value

Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
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)"
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.
[ November 05, 2003: Message edited by: Carolina Carvajal ]
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic