But i am getting the o/p of str1 as 'blank'in the public static void main (String args) method. Since i have assigned the str1 = str2 ,so i am supposing that str1 =100 also. Please tell me the reason, why i am getting the value of str1 as blank. Its very urgent .Please provide me the solution...if anybody can...... [ November 06, 2007: Message edited by: hamraj happy ]
Keith, I'm not sure how you got the "st1 has: " line. When I ran it, I got the output I expected from looking at the code:
Here's the reason why st1 is still empty after the Method() call ends: the reassignment of st1 in Method() does not affect the st1 in main(). When you pass a parameter to a Java method, you're passing only a copy of the parameter value or reference. Any changes you make to that copy within the method will not affect the original variable in the calling code. So in your program, the value of st1 in main() never changes after being initialization, i.e. it always refers to an empty Stack.
It's easier to recognize the problem if you use different names for Method's formal parameters: Renaming a formal parameter makes absolutely no difference to the program if you change the name consistently within the method body. Thus the above program is completely equivalent to the one you posted. Hopefully this version makes the issue clearer.
By the way, it's a pretty common trick on mock exams (and probably also the real one) to give formal parameters the same name as the calling method's local variables. Don't fall for this! Just remember that if they do have the same name, you should regard it as nothing more than a coincidence--changing one variable does not directly affect the other.