This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
hi there, hope u ppl r doing fine.i m having problem in methods in which 2 things r making trouble for me ,given below: 1.pass by value 2.pass by reference i want u to defines these terms with examples. i will be really greatful to u. take care with regards kumar abhay
Java always passes parameters by value. More specifically, Java passes all method arguments by passing a copy of the argument value. There are two types of variables, primitive variables and reference variables A primitive variable holds a primitive value. Some examples: int i = 5; byte b = 12; boolean bool = true; float f = 3.0f; etc. The other kind of variables are reference variables. They hold references to objects. String myString = "Hello"; myString is a reference variable. It contains a reference to the object on the right side of the expression. here's another one: Object myObjectReference = new Object(); Again, here we have an object being created on the right, and a reference to this new object is being stored in the reference variable on the left. myObjectReference references the new object; it is not the object itself. For example, here's a second variable: Object mySecondObjectReference = myObjectReference; This second reference variable references the same object as the first one; we have only created ONE object. A final example... int myArrayReference = new int; Here, on the right, we are actually creating a new object of type 'int array'. A reference to the object is being stored in the variable on the left. Now...as for passing these variables to methods. When you pass a variable to a method, what you are passing is merely a copy of the value of that variable.
The println() above always prints hi12. The reason that the foo method didn't change the values of the string or the int is that you only passed copies of their values to the method. You passed a copy of the value of variable anInt, which was 12. And you passed a copy of the value of variable aString, which is a reference to a string object. In the method, these values you have passed are assigned to local parameter variables myString and myInt. Then it changes the object refereneced by myString, and changed the value of myInt. But since you only passed copies of the values to the method, the original values before the method call have not changed. Some programming languages have pass-by-reference...but just remember that java does not. It only has pass by value. And if you remember you are actually passing a copy of the value, it should make it very clear what is happening when you call a method with parameters. Good luck.