Originally posted by atif toor:
can we pass an object to a method?If answer is yes. In which situation it is important(necessary) to pass an object to a method.Give any exmple.
Thanking in anticipation
The quick answer is 'Yes, you can'.
As to why you would, objects allow 'pass by reference' as opposed to 'pass by value'.
If you pass a primitive into a method (int, boolean etc) and the method changes the value then the variable remains UNCHANGED upon exiting the method.
If you pass an object into a method, if the method alters the object value, it's value remains changed once the method is completed.
There is an important addendum and that is immutable types. An example: a
String is an immutable type, so whenever you think you are altering it's value, what you are really doing is creating a NEW object.
The importance of this is that if you pass a String to a method, then that method changes the String, the method retains its reference to the new object but once the method exits the reference is to the ORIGINAL String since that reference wasn't changed, only the reference to the String object within the method.
Phew. Hope you got all that.
Dave.