Passing object references to methods

i got the Foo class a few minutes ago from the other forum, despite passing the object reference to the baz method, it prints "2" and not "3" at the end.
but the Passer3 code seems to be different, "p" is passed to test() , and the changes to "pass" in the test method prints "silver 7".
so i'm totally confused about the whole call by reference thing, can anyone explain?
class Foo {
    public int bar = 0;
    public static void main(String[] args) {
            Foo foo = new Foo();
            foo.bar = 1;
            System.out.println(foo.bar);
            baz(foo);
            // if this was pass by reference the following line would print 3
            // but it doesn't, it prints 2
            System.out.println(foo.bar);
    private static void baz(Foo foo) {
        foo.bar = 2;
        foo = new Foo();
        foo.bar = 3;
class Passer2 {
     String str;
     int i;
     Passer2(String str, int i) {
     this.str = str;
     this.i = i;
     void test(Passer2 pass) {
     pass.str = "silver";
     pass.i = 7;
class Passer3 {
     public static void main(String[] args) {
     Passer2 p = new Passer2("gold", 5);
     System.out.println(p.str+" "+p.i);  //prints gold 5
     p.test(p);
     System.out.println(p.str+" "+p.i);   //prints silver 7
}

private static void baz(Foo foo) {
foo.bar = 2;
foo = new Foo();
foo.bar = 3;This sets the bar variable in the object reference by
foo to 2.
It then creates a new Foo and references it by foo
(foo is a copy of the passed reference and cannot be
seen outside the method).
It sets the bar variable of the newly created Foo to
3 and then exits the method.
The method's foo variable now no longer exists and
now there is no longer any reference to the Foo
created in the method.thanks, i think i followed what you said.
so when i pass the object reference to the method, the parameter is a copy of that reference, and it can be pointed to a different object.
is that correct?

Similar Messages

  • Passing object references via methods

    Why is the JFrame object not being created in the following code:
    public class Main {
      public static void main(String[] args) {
        Main main = new Main();
        JFrame frame = null;
        main.createFrame(frame);  // <-- does not create the "frame" object
        frame.pack();
        frame.setVisible(true);
      private void createFrame(JFrame frame) {
        frame = new JFrame("createFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Thanks.

    These explanations are great; real eye openers.
    OK. This could be a "way out in left field" question. I am just starting out with Java. But I want to ask:
    Objects are stored in the heap?
    Object references and primitives are stored on the stack?
    Adjusting heap size is straight-forward. A larger heap can store more/larger objects. What about stack sizes?
    C:\Dev\java -Xss1024k Main
    I assume this refers to method's stacks. But, what about object scoped, and class scoped, object references?
    public class Main {
      private static List list = new ArrayList(); // class scoped
      private JFrame frame = new JFrame();  // object scoped
      public static void main(String[] args) { ...... }
      private void createFrame() { .... }
    }How is the reference to list and frame stored, with regard to memory management?
    Do objects have stacks?
    Do classes have stacks?
    If not, how are the list and frame references stored (which helps me understand reference scoping).
    Would the overflow of a method stack (ex. via recurssion) also overflow the method's object and the method's class stacks?
    If these questions are stupid, "out of left field", don't matter, etc. Just ignore them.
    But the knowledge could help me avoid future memory related mistakes, and maybe pass a "Java Certified Developer" exam?
    My original question is already answered, so thanks to all.

  • What is the use of passing object reference to itself ?

    What is the use of passing object reference to itself ?
    regards,
    namanc

    There is an use for returning an object reference from itself, for instance:
    class C {
    public:
         C append(C c) {
             // do something interesting here, and then:
             return this;
    }You can "chain" calls, like this:
    C c = new C();
    C d = new C();
    C e = new C();
    c.append (d).append (e);Maybe the OP has "inverted" the common usage, or thought about a static method of a class C that requires a parameter of type C (effectively being a sort of "non-static method").
    class C {
        static void doAnotherThing (C c) {
            c.doSomething(); //-- effectively C.doAnotherThing(c) is an "alternative syntax" for c.doSomething()

  • ExternalInterface: pass object reference across interface - how?

    I want to invoke methods on specific Javascript or
    ActionScript objects through calls across the ExternalInterface
    barrier. I would like to be able to do this either AS -> JS or
    JS -> AS.
    So I would like to pass an object reference across the
    interface. I'm not sure exactly what *is* getting passed (is it the
    serialized value of the object?), but it doesn't seem to work as an
    object reference.
    Here's a notional code sample. I have two symmetric object
    definitions, one in Javascript, one in ActionScript. During
    initialization, one instance of each object will be created and
    given a pointer to the other. Then they should each be able to
    invoke a method on the other to "do stuff".
    //----------[ code ]---------------------------------
    //--- Javascript ---
    class JSobj {
    var _asObj;
    JSobj.prototype.setASObj = function(obj) { _asObj = obj; }
    JSobj.prototype.callASObj = function(foo) {
    callASObjectMethod(_asObj, foo); } // does: _asObj.asMethod(foo);
    JSobj.prototype.jsMethod = function(bar) { /* do stuff */ }
    function callJSObjectMethod(obj, args) { obj.jsMethod(args);
    //--- ActionScript ---
    class ASobj {
    var _jsObj;
    public function set jsObj (obj:Object):void { _jsObj = obj;
    public function callJSObj (foo:Number):void {
    ExternalInterface.call("callJSObjectMethod", _jsObj, foo); } //
    does: _jsObj.jsMethod(foo);
    public function asMethod (bar:Number):void { /* do stuff */
    function callASObjectMethod (obj:Object, args) {
    obj.asMethod(args); }
    ExternalInterface.addCallback("callASObjectMethod",
    callASObjectMethod);
    //----------[ /code ]---------------------------------
    My workaround is to pass a uint as an opaque handle for the
    object, then resolve it when it is passed back. I'd rather pass a
    real reference if possible. Is there a way to pass object
    references between JS and AS?
    Thanks,
    -e-

    It's an object of a class that extends Object. I guess the answer is no then.
    Thanks for your answer

  • Pass object reference from TestStand to C#

    Hi,
    I have created a GUI in .NET which i invoke in TestStand (through a custom step type). User can enter a object reference teststand variable in the UI input expression box. So i need to get the object value in that variable and use it to call some .net functions. To get the values from expression box of UI and put in TestStand step variable i use:
             PropertyObject.SetValInterface("Step.TestStationObj", 0, tsexprTestStationObj.DisplayText.Trim()); To check the value in the step variable if i do:
             MessageBox.Show("TestStation obj after setting:",PropertyObject.GetValInterface("Step.TestStationObj",0).ToString());
    But i do not get any value. Guess it is null. Is this a correct way? My intension is to get the value corresponding to a teststand object reference and pass it to C#. The C# UI control is of type NationalInstruments.TestStand.Interop.UI.Ax.AxExpressionEdit

    Thanks Andy.
    I still get the error when i am trying to pass the object created from C# to Teststand. I have explained what i am trying to do. Kindly requesting your assitance on this issue.
    I have 2 classes in C# (code given below), I am trying to pass the object of "Counter" (c1) class from the "Mainfrm" to teststand. In teststand(counter.seq), I am trying to access the function "GetCount() and SetCount()". I have attached the snapshot of the error that i get from teststand.
    Class Counter
        private int count;
        public int GetCount ()
           return (count);
        public void SetCount(int _count)
           count = _count;
    Class Mainfrm : Form
        public Counter c1;
            private void Mainfrm (object sender, EventArgs e)
                InitializeComponent();
                axApplicationMgr1.Start();
                mEngine = axApplicationMgr1.GetEngine();
                currentFile = axApplicationMgr1.OpenSequenceFile(@"Counter.seq");
                pobj = mEngine.NewPropertyObject(NationalInstruments.TestStand.Interop.API.PropertyValueTypes.PropValType_Container, false, "", 0);
                pobj.NewSubProperty("Parameters.ObjRef1", NationalInstruments.TestStand.Interop.API.PropertyValueTypes.PropValType_Reference, false, "", 0);
                pobj.SetValInterface("Parameters.ObjRef1", 0, (object)c1);
                mExecution = mEngine.NewExecution(currentFile, "MainSequence", null, false, 0, pobj, null, null);
    Attachments:
    ErrorFromTestStand.JPG ‏28 KB

  • A simple teststand applicatio​n passing object reference to C#

    Hi,
     I have a  .NET application written in C# which has a UI with  NationalInstruments.TestStand.Interop.UI.Ax.AxExpressionEdit controls. This UI is invoked by a custom step in TestStand. One of the values, entered by user in the UI is a object reference variable created in a previous step. I need to store the values entered in the UI during the edit mode of the step, into the TestStand Step variables. And during the run mode i use these values to execute the logic in C#. 
    The problem is during edit time, the object reference variable, entered in the UI, has no value. It is null. So there is no use storing it at edit time. During the runtime i am trying to retrieve the value of the object reference variable using GetValInterface(...) and GetValIDispatch(..) methods of PropertyObject. But the object returned to C# is of type System.__COMObject wherease in TestStand that object reference is of type .NET.
    I don't know how a .NET object reference is converted to COM object when it is returned to .Net function.
    Also is there any other method to send this object reference variable's (whose value is '.NET' in previous step itself) value to .NET as a .NET object only so that i can typecast to appropriate type and start using.
    Thanks.
    Please let me know if anything is not clear.
    I have attached the .Net project, .ini file for the custom step and a example sequence file.
    Attachments:
    CCustomStepObj.zip ‏23 KB

    Hello Shivapriya,
    The example you've sent doesn't compile. And it without it I'm affraid I do not understand the problem you're describing.
    You've given references to libraries that you've not attached with your files.
    For the C# I see these are the
    IADCore.dll
    InstrimentInterfaces.dll
    TestStand also seems to want to reach for the assembly named TestSystem.dll.
    I can only tell you that I have used successfully in the past the Variables in TestStand to hold .NET object references, and call methods on them and I experienced nothing similar that you describe, but I don't quite follow what is the problem here, as I can't use the example. 
    I would appriciate if you cold narrow down the example to 1 dll or something where the problem occurs and than resend it.
    Regards,
    Maciej 
    Message Edited by Mac671 on 09-28-2009 02:59 AM

  • Passing objects to a method.

    Hi,
    I was reading this from a book and puzzled by this suggestion:
    for example:
    public Employee findEmployee(String employeeID);
    This method takes a String specifying a unique employee id and returns the Employee object with that id, null otherwise. Don't pass un-necessary objects to methods, and return the appropriate results.
    Why not passing objects to methods, I found it is convenient to pass objects to methods, why ?
    Thanks in advance !
    Tee

    Of course you can pass objects to methods. A String is also an object.
    The author doesn't say to not pass any objects to methods, only no unnecessary objects. He propably means that you don't need a method likepublic Employee findEmployee(String employeeID, String country)to retrieve the Employee if the employee ID by itself is unique or you don't use the country in the method, to give you an example.

  • Find memory leakage when passing Object Reference from Teststand to vi

    I am using Teststand to call labview vi, and pass ThisContext of sequence to vi as object reference, but if I just loop this step and I can find the memory using keep increasing, how can I avoid the memory leakage inside the vi.
    see my vi, it is to post message to UI.
    Solved!
    Go to Solution.

    You should be using a close reference node to close the references you get as a result of an invoke. In the code below you should be closing the references you get from the following:
    AsPropertyObject
    Thread
    Close those two references once you are done with them.
    Also make sure you turned off result collection in your sequence or you will be using up memory continually for the step results.
    Hope this helps,
    -Doug

  • Passing object reference array to a method

    Hi everyone,
    I'm new to the java programming language. I want to create create a array of 50 objects and pass them in to a method in other class.
    Can anyone help me on this problem........................
    Chathu.

    Object[] objectArray = new Object[50];
    objectArray[0] = "Hello World";
    objectArray[1] = new Integer(42);
    myClass.myMethod(objectArray);

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

  • Confused about passing by reference and passing by valule

    Hi,
    I am confuse about passing by reference and passing by value. I though objects are always passed by reference. But I find out that its true for java.sql.PreparedStatement but not for java.lang.String. How come when both are objects?
    Thanks

    Hi,
    I am confuse about passing by reference and passing
    by value. I though objects are always passed by
    reference. But I find out that its true for
    java.sql.PreparedStatement but not for
    java.lang.String. How come when both are objects?
    ThanksPass by value implies that the actual parameter is copied and that copy is used as the formal parameter (that is, the method is operating on a copy of what was passed in)
    Pass by reference means that the actual parameter is the formal parameter (that is, the method is operating on the thing which is passed in).
    In Java, you never, ever deal with objects - only references to objects. And Java always, always makes a copy of the actual parameter and uses that as the formal parameter, so Java is always, always pass by value using the standard definition of the term. However, since manipulating an object's state via any reference that refers to that object produces the same effect, changes to the object's state via the copied reference are visible to the calling code, which is what leads some folk to think of java as passing objects by reference, even though a) java doesn't pass objects at all and b) java doesn't do pass by reference. It passes object references by value.
    I've no idea what you're talking about wrt PreparedStatement, but String is immutable, so you can't change its state at all, so maybe that's what's tripping you up?
    Good Luck
    Lee
    PS: I will venture a guess that this is the 3rd reply. Let's see...
    Ok, second. Close enough.
    Yeah, good on yer mlk, At least I beat Jos.
    Message was edited by:
    tsith

  • Passing paramaters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    This is an extremely common question. A search through this forum would be very useful to you.
    Java does not pass-by-reference in the same way C/C++ do. When you pass an object to a method, you can change the contents of the object using its methods and see the changes after the method completes in the calling method. In this way Java is similar to C/C++.
    However, you cannot change an object to equal another object or a new object inside a method and expect the changes to be visible after the method completes in the calling method.
    Here is an example.
    This will show changes and the line "String" would be printed.
      StringBuffer sb = new StringBuffer();
      method(sb);
      System.out.println(sb);
      public void method(StringBuffer buf) {
        buf.append("String");
      }However, this would not show changes and the line "Old String would be printed:
      String string = "Old String";
      method(string);
      System.out.println(string);
      public void method(String string) {
        string = "New String";
        // string.concat("New String) would also fail to work

  • Passing parameters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    I do some changes to them and expect the changed
    objects to be available in the calling methodIf you modify an object passed to a method, then the changes made to that object will be visible as soon as they are made.
    If you change the parameter so that it references some other object, this will NOT be seen in the calling method.
    You can "fake" it by putting the object in question in an array and passing the array. Better though is to just not expect methods to be able to change references they are passed to point at some other object.

  • Pass by reference and String

    public class Test {
        static void method(String str) {
            str = "String Changed";
        public static void main(String[] args) {
            String str = new String("My String");
            System.out.println(str);
            method(str);
            System.out.println(str);
    }The output is
    My String
    My String
    How this is possible when objects are passed by reference ?

    > How this is possible when objects are passed by reference ?
    All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments. If you pass a double to a method, its parameter is a copy of whatever value was being passed as an argument, and the method can change its parameter's value without affecting values in the code that invoked the method. For example:
    class PassByValue {
        public static void main(String[] args) {
            double one = 1.0;
            System.out.println("before: one = " + one);
            halveIt(one);
            System.out.println("after: one = " + one);
        public static void halveIt(double arg) {
            arg /= 2.0;     // divide arg by two
            System.out.println("halved: arg = " + arg);
    }The following output illustrates that the value of arg inside halveIt is divided by two without affecting the value of the variable one in main:before: one = 1.0
    halved: arg = 0.5
    after: one = 1.0You should note that when the parameter is an object reference, the object reference -- not the object itself -- is what is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. Here is an example to show the distinction:
    class PassRef {
        public static void main(String[] args) {
            Body sirius = new Body("Sirius", null);
            System.out.println("before: " + sirius);
            commonName(sirius);
            System.out.println("after:  " + sirius);
        public static void commonName(Body bodyRef) {
            bodyRef.name = "Dog Star";
            bodyRef = null;
    }This program produces the following output: before: 0 (Sirius)
    after:  0 (Dog Star)Notice that the contents of the object have been modified with a name change, while the variable sirius still refers to the Body object even though the method commonName changed the value of its bodyRef parameter variable to null. This requires some explanation.
    The following diagram shows the state of the variables just after main invokes commonName:
    main()            |              |
        sirius------->| idNum: 0     |
                      | name --------+------>"Sirius"       
    commonName()----->| orbits: null |
        bodyRef       |______________|At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same underlying object. When commonName changes the field bodyRef.name, the name is changed in the underlying object that the two variables share. When commonName changes the value of bodyRef to null, only the value of the bodyRef variable is changed; the value of sirius remains unchanged because the parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line would say "null". However, the variable bodyRef in commonName and the variable sirius in main both refer to the same underlying object, so the change made inside commonName is visible through the reference sirius.
    Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. If the Java programming language actually had pass-by-reference parameters, there would be a way to declare halveIt so that the preceding code would modify the value of one, or so that commonName could change the variable sirius to null. This is not possible. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
    -- Arnold, K., Gosling J., Holmes D. (2006). The Java� Programming Language Fourth Edition. Boston: Addison-Wesley.
    ~

  • Calrification on Pass by reference

    Hi All,
    In java, if we are passing an object to a function actually we are passing the reference. So, if the function is doing any manipulation on the Object reference, it will affect the passing object.
    For example,
    class Ob1
         int i=0;
    public class Ref
         public static void main(String a[])
              Ob1 o=new Ob1();
              System.out.println("Before calling :"+o.i);
              call(o);
              System.out.println("After calling :"+o.i);
         static void call(Ob1 o)
              o.i++;
    Is it possible to get the original value of i(object Ob1) after calling call()?
    Thanks in advance
    +Sha                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    > In java, if we are passing an object to a function
    actually we are[b] passing the reference.
    By value.
    Is it possible to get the original value of i(object
    Ob1) after calling call()?
    Store the original value in a local variable.
    And please note the following:
    All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments. If you pass a double to a method, its parameter is a copy of whatever value was being passed as an argument, and the method can change its parameter's value without affecting values in the code that invoked the method. For example:
    class PassByValue {
        public static void main(String[] args) {
            double one = 1.0;
            System.out.println("before: one = " + one);
            halveIt(one);
            System.out.println("after: one = " + one);
        public static void halveIt(double arg) {
            arg /= 2.0;     // divide arg by two
            System.out.println("halved: arg = " + arg);
    }The following output illustrates that the value of arg inside halveIt is divided by two without affecting the value of the variable one in main:before: one = 1.0
    halved: arg = 0.5
    after: one = 1.0You should note that when the parameter is an object reference, the object reference -- not the object itself -- is what is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. Here is an example to show the distinction:
    class PassRef {
        public static void main(String[] args) {
            Body sirius = new Body("Sirius", null);
            System.out.println("before: " + sirius);
            commonName(sirius);
            System.out.println("after:  " + sirius);
        public static void commonName(Body bodyRef) {
            bodyRef.name = "Dog Star";
            bodyRef = null;
    }This program produces the following output: before: 0 (Sirius)
    after:  0 (Dog Star)Notice that the contents of the object have been modified with a name change, while the variable sirius still refers to the Body object even though the method commonName changed the value of its bodyRef parameter variable to null. This requires some explanation.
    The following diagram shows the state of the variables just after main invokes commonName:
    main()            |              |
        sirius------->| idNum: 0     |
                      | name --------+------>"Sirius"       
    commonName()----->| orbits: null |
        bodyRef       |______________|At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same underlying object. When commonName changes the field bodyRef.name, the name is changed in the underlying object that the two variables share. When commonName changes the value of bodyRef to null, only the value of the bodyRef variable is changed; the value of sirius remains unchanged because the parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line would say "null". However, the variable bodyRef in commonName and the variable sirius in main both refer to the same underlying object, so the change made inside commonName is visible through the reference sirius.
    Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. If the Java programming language actually had pass-by-reference parameters, there would be a way to declare halveIt so that the preceding code would modify the value of one, or so that commonName could change the variable sirius to null. This is not possible. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
    -- Arnold, K., Gosling J., Holmes D. (2006). The Java� Programming Language Fourth Edition. Boston: Addison-Wesley.

Maybe you are looking for

  • How to implement JAAS With Weblogic 10.3

    I am working on a migration project. A project is to be migrated from JBOSS to Weblogic 10.3. JAAS has been used in JBOSS for security purpose. Required classess like LoginModule, CallBackHandler are customized and put into a jar file. Next a Login p

  • LMS 4.1 multiserver config problem

    I m facing a problem in multiserver configuration, in making master-slave servers. Master server config is done, certificates are imported, SSO is also configured and all the pre-requisites given in the multiserver-config doc of lms4.1. While making

  • Error in Test Connection through the DQE for my JDBC system

    Hi, I created a JDBC system and I gave DQE properties to connect to the PUBS database. I am getting the below error when I did Test Connection through the DQE. Test Details: The test consists of the following steps: 1. Checks the existence of a backe

  • Webservice Stubs generation problems

    I need to consume a axis webservice. I got the wsdl from the url and i tried to generate stubs in Jdev 10.1.2 but it is giving some wsdl validation errors like schema element not found. In that wsdl they imported some schema(.xsd) files.I dont know h

  • Scheduling IDOCs- PFAL

    Hi  All, Can you help me on regarding this : We have scenario where ECC(HCM) sending the master and reference data of PersonnelAdministration(PA)/Organization Management(OM)  to MDM  and our design confirmed that usign PFAL transaction for send the m