Does anybody have an idea why the Integer object value is not changed
here, eventhough it is passed by reference?
Program:
======
class int_to_Integer
{
static void changeInt(Integer intObj)
{
intObj = new Integer(25) ;
}
public static void main( String args[])
{
Integer intInMain = new Integer(10) ;
System.out.println( "Before change:" +intInMain.intValue() ) ;
changeInt(intInMain) ;
System.out.println( "After change:" +intInMain.intValue() ) ;
}
}
Output:
=====
E:>java int_to_Integer
Before change:10
After change:10
Robert Klemme - 27 Mar 2006 16:15 GMT
> Does anybody have an idea why the Integer object value is not changed
> here, eventhough it is passed by reference?
Because you don't change the object but you create a new object and
assign it to the parameter. And Java passes Object parameters as
references by value (i.e. there is a new storage location holding the ref).
Kind regards
robert
> Program:
> ======
[quoted text clipped - 22 lines]
> Before change:10
> After change:10
Patricia Shanahan - 27 Mar 2006 17:01 GMT
> Does anybody have an idea why the Integer object value is not changed
> here, eventhough it is passed by reference?
...
Because this is Java code, so NOTHING is ever passed by reference.
Instead, a reference expression was passed by value. A reference
expression in Java is either null or a pointer to an object.
Thinking of Java reference parameter passing as passing an object by
reference, rather than passing a pointer by value, gives incorrect
predictions for many programs such as your example.
Patricia
tom fredriksen - 27 Mar 2006 18:04 GMT
> Does anybody have an idea why the Integer object value is not changed
> here, eventhough it is passed by reference?
Succinctly, everything in java is always copied by value, even
references. So what you are doing is creating a copy of the reference,
which in java does not allow for changing the original reference to
point somewhere else.
/tom
James McGill - 27 Mar 2006 18:34 GMT
> class int_to_Integer
> {
> static void changeInt(Integer intObj)
> {
// If you ran methods on intObj here, intInMain would be the referenced
object
> intObj = new Integer(25) ;
// But you threw that away, now intObj is an unrelated new object, and
is disposed of.
> }