File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Scope in methods 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 "Scope in methods" Watch "Scope in methods" New topic
Author

Scope in methods

Adam Vinueza
Ranch Hand

Joined: Apr 16, 2001
Posts: 76
Consider:
Class Widget
{
private static void doStuff( int i, int j )
{
while ( i < 2 )
{
j = 7;
i++;
}
}
private static void main( String[] args )
{
int num1 = 1;
int num2 = 3;
doStuff( num1, num2 );
}
}
When I call doStuff, num1 is given the value 2 after incrementing, and num2 is given the value 7. But once doStuff is finished, the values return to 1 and 3 respectively. My question is, Why? It seems an awfully annoying thing. I know we can just avoid making methods like this, but wouldn't it be nice if ... ?
Is there some awfully important reason why Java is this way? Or is it a byproduct of some other awfully important feature?
Any enlightenment on this issue would be very welcome.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
I'm fairly new to java myself but I'll give it a shot...
primitives in Java are passed by value, so when you pass num1 and num2 to the method your just sending the value of them to the method where i and j get those values. In the method you manipulate the values of i and j, not num1 and num2. As opposed to C++ where you can pass a reference then the receiveing variable gets the address of the memory location that holds the variable. Then any changes made will affect (or is it effect) the underlying value at that memory location.
If your looking to be able to change the values of num1 and num2 then declare them outside of the methods:
Class Widget {
int num1, num2;
private static void doStuff( ){
while ( num1 < 2 ){
num2 = 7;
num1++;
}
}
private static void main( String[] args ){
int num1 = 1;
int num2 = 3;
doStuff();
}
}
now they are instance variables and any changes made to them in doStuff() will change their value for that instance.
Hope that was what you were looking for.
Dave

Dave
Adam Vinueza
Ranch Hand

Joined: Apr 16, 2001
Posts: 76
Thanks Dave, that makes sense to me. I was thinking of i and j in doStuff as schemas for whatever variables I'd be using when I call the method, not as placeholders for values.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Scope in methods