Are Calendar Objects passed by reference?

Consider the following bit O' code:
TimeZone CST = TimeZone.getTimeZone("America/Chicago");
GregorianCalendar g = new GregorianCalendar(CST);
DateFormat D= DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
D.setTimeZone(CST);
System.out.println(D.format(g.getTime()));
GregorianCalendar g2 = new GregorianCalendar(CST);
g2=g;
g2.add(Calendar.DATE,400);
System.out.println(D.format(g.getTime()));
Note that the last println prints g, not g2. The result is:
Apr 21, 2002 7:11:04 PM
May 26, 2003 7:11:04 PM
So advancing g2 affected g. Why? This doesnt happen with objects like strings.
How can I copy the contents of g into g2 then modify g2 without affecting g?

Try     g2=(GregorianCalendar)g.clone();Passing by reference has nothing to do with this problem.
When you assign g2 to g, g2=g;then both variables (references) reference the same object. The object that you created in GregorianCalendar g2 = new GregorianCalendar(CST); has gone to the Garbage Collector.
This doesnt happen with objects like stringsStrings are immutable and don't have any methods to change the contents, so the behavior is very different.
Dave

Similar Messages

  • Objects pass by reference?

    Can some explain why this doesn't behave like I expect please?
    var obj:Object = null;
    recursionTest(0, obj);
    trace("obj: " + obj);
    private function recursionTest(iterations:int, obj:Object):void
              trace("call recursion test: " + iterations);
              if (iterations == 0)
                        obj = new Object();
                        trace("set obj: " + obj);
              else
                        recursionTest(iterations - 1, obj);
    actual output:
    call recursion test: 0
    set obj: [object Object]
    obj: null
    expected output:
    call recursion test: 0
    set obj: [object Object]
    obj: [object Object]

    I think I now understand why this is happening
    var obj:Object = null;
    recursionTest(0, obj);
    trace("obj: " + obj);
    private function recursionTest(iterations:int, obj2:Object):void
              trace("call recursion test: " + iterations);
              if (iterations == 0)
                        obj2 = new Object();
                        trace("set obj: " + obj2);
              else
                        recursionTest(iterations - 1, obj2);
    we create a reference (obj) and assign it to null
    as part of calling the function a new reference (obj2) is created and it points towards the target of the passed in reference (obj)
    so we have obj pointing to null and obj2 pointing to null
    now if we assign a new object obj2 this simply makes the reference obj2 point towads the newly created object and doesn't affect the obj reference in anyway. obj is still pointing towards null.
    now consider
    var obj:Object = new Object();
    obj.a = 3;
    recursionTest(0, obj);
    trace("obj: " + obj.a);
    private function recursionTest(iterations:int, obj2:Object):void
              trace("call recursion test: " + iterations);
              if (iterations == 0)
                        obj2.a = 5;
                        trace("set obj: " + obj2.a);
              else
                        recursionTest(iterations - 1, obj2);
    we create a reference (obj) and assign it a new object
    as part of calling the function a new reference (obj2) is created and it points towards the target of the passed in reference (obj)
    so we have obj pointing to an object and obj2 pointing to the same object obj is pointing to
    now we assign a value to one of the properties of the object obj2 is pointing to but obj2 is pointing to the same object as obj and so the object obj is pointing to has changed.

  • Pass by Reference automatically?

    In Java, are objects passed by reference automatically?
    Basically, if I pass an object into a method and the method modifies the object, will the original object reflect that modification?

    They're not objects. They're primitive data types. Objects require you to use new when you create and instance of them. Primitives are automatically allocated space when you declare them. Also, they are not passed by reference... only a copy of them is passed on the methods

  • How BAPI Tables parameters are passed by reference

    Hi Gurus,
                     I have a genuine doubt regarding BAPI parameters. I would like to point out the genreal rules of bapi like,
    1. BAPI parameters should be passed by value. (Because they are rfc fm's. So both systems will be in different servers. This is the normal scenario.)
    2. But the tables parameters in BAPI can't be passed by value. Instead they are passed by reference.
    3. I know they use some kind of delta mechanism to transfer tables parameters to remote servers.
    So gurus I would like to know what exactly happens when a tables parameter is passed. And also I didn't understand the delta mechanism. Kindly guide me.
    Thanks in advance,
    Jerry Jerome

    You'll see in [SAP Library - RFC - Parameter Handling in Remote Calls|http://help.sap.com/saphelp_nw04s/helpdata/en/22/042551488911d189490000e829fbbd/frameset.htm] that tables are not passed by reference when you use RFC. It also explains the delta.
    When you make a remote function call, the system handles parameter transfer differently than it does with local calls.
    TABLES parameters
    The actual table is transferred, but not the table header. If a table parameter is not specified, an empty table is used in the called function.
    The RFC uses a delta managing mechanism to minimize network load during parameter and result passing. Internal ABAP tables can be used as parameters for function module calls. When a function module is called locally, a parameter tables is transferred u201Cby reference". This means that you do not have to create a new local copy. RFC does not support transfer u201Cby referenceu201D. Therefore, the entire table must be transferred back and forth between the RFC client and the RFC server. When the RFC server receives the table entries, it creates a local copy of the internal table. Then only delta information is returned to the RFC client. This information is not returned to the RFC client every time a table operation occurs, however; instead, all collected delta information is passed on at once when the function returns to the client.
    The first time a table is passed, it is given an object-ID and registered as a "virtual global table" in the calling system. This registration is kept alive as long as call-backs are possible between calling and called systems. Thus, if multiple call-backs occur, the change-log can be passed back and forth to update the local copy, but the table itself need only be copied once (the first time).

  • Arrays are passed by reference or value ?

    Hi peoples,
    I have something interesting here which I need to know. Look into the following classes :
         public class example1 {
         int i[] = {0};
         public static void main(String args[]) {
         int i[] = {1};
         change_i(i);
         System.out.println(i[0]);
         public static void change_i(int i[]) {
         i[0] = 2;
         i[0] *= 2;
         public class example2 {
         int i[] = {0};
         public static void main(String args[]) {
         int i[] = {1};
         change_i(i);
         System.out.println(i[0]);
         public static void change_i(int i[]) {
         int j[] = {2};
         i = j;
    Among the above classes, the class named 'example1' returns the value 4 whereas, the class named 'example2' returns the value 1.
    Any explanations to this one please....
    Cheers,
    Rasmeet

    minglu, you are not doing right.
    i just don't get it why you have i[] as instance variable but never use it ( i[] is declared in every method so each i you refer to in the method is a local varable not member variable that can be shared for the object ).
    your first solution work. but that i = j line is not needed because it has no effect you still cannot change the referrence of i to other int[]. your first soultion just need to be
    public static int[] change_i(int i[]) {
    int j[] = {2};
    return j;
    }anyway, using this solution, the method name will be misleading because the method didnot change i in anyway. i is changed because you assign the return array (j) to i.
    for that second solution also, you didn't use your member variable i at all. what you change is the content of i you pass so the result is correct. but then how is this method different from the first method the original poster posted?
    moreover, java never pass argument to the method by reference it ALWAYS pass by copy.i suppose you define passing by reference in the same way C++ does. all object variable in java is a refernce to Object so passing the variable to method is surely passing the reference to the method but that's not passing by reference. it's passing by copy because what is passed is the copy of the reference to the object, not the reference to the reference to Object. if it is really passing by refernce, then you will be able to change your reference to object to point anywhere because you have the access the address of the reference. but since you don't (you only know where the passed reference is pointing to (you have the COPY of value of reference) but you don't know where the refernce store its value) you can only change the content of the pointed object but not changing the pointed object.
    let me restate this, java always pass by reference.

  • Strings are passed by Reference

    Since strings are objects, they are passed by reference. I tested this out:
    1.in main(): String str="in main"; creates a new string "in main" and has str point to it.
    2.Passed str into changeStr(String str2)
    3.in changeStr: str2="in changeStr", since str2 is a reference, it should redirect str to point to the new string "changeStr".
    4.Back in main I print out str and get "in main".
    Why?

    (When you post source code, please put it in CODE tags; there's a button for that above the textarea.)
    Don't think of references as memory addresses; that makes them sound like C pointers, when in fact they're fundamentally different: a pointer points to a memory location, while a reference points to an Object. C lets you dereference a pointer and replace the data at that memory location with something else. Afterward, any existing variable that referred to the data in that section of memory, will see the new value.
    A Java reference lets you access the object to call its methods, examine its variables, and so on. If the object is mutable, you can change itss contents, and all existing variables that refer to that object will see those changes. But you can't replace the whole object with something else. Reassigning the variable that was passed into the method has no effect on the original object or on any other variables that pointed to it.
    So stop thinking of references as memory addresses. In fact, stop thinking about memory addresses, period. You never need that information in Java, and for that you should be eternally grateful. The absence of C pointers was one of Java's biggest selling points, way back when.
    Edited by: uncle_alice on Feb 27, 2008 7:55 AM
    Oh well. :-/ At least I may have done some good by asking the OP to use CODE tags.

  • 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 control reference to subVI crashes labview

    Hi,
    using a image control (as indicator) provided by imaq Vision, I tried to pass the reference of the control to a subVI. On a computer it works and on a other (same labview version, same vision version, same os, same hardware and hardware drivers!), this crashes labview. I tried to close the control refnum at the end of the subVI, but that changed nothing to the issue. Now I use the reference as a global variable and it seems to work...nevertheless, I would like to understand what the issue and if I should remove any passing to subVI of control ref because this can potentially triggers an error. My correlated question is if this global passing is a "fake" workaround or have real chance of improving (this before going through the whole code for changing all passing of reference to subVI)
    thanks a lot

    Hi,
    thank CoastalMaineBird for your answer
    How do you know it's this issue which causes the crash?
    When I remove this parameter from and the only property node in the subVi that write to it, I have no longer any problem. Moreover, to ensure that's really the "passing", and made a global variable containing the reference to this control and use my original SubVi that do access the control through its reference number
    , and it works! In this last exemple, the only change is the way of transmitting the reference
    What LabVIEW version?
    8.0.1
    up to date according Measurement & Automation update tool
    Given that one computer works OK, and another crashes, I would say that
    you are seeing the effect of something else, not the cause. If passing
    a control ref via terminals was fatal, it would be fatal all the time.
    You have some other sort of issue, perhaps timing of the different
    machines triggers the bug, perhaps running out of memory, perhaps
    LabVIEW is corrupted on one machine.... But I don't think changing all
    your code to use globals would solve the real problem. Actually, saying that I wonder about problem of synchronisation. I know from Visual C++ that this kind of error happens if two process try to access the same control at the same time. This is typically an error changing from a computer to an other, and mutex or semaphore are the way to deal nicely with that. But does labview contains already such a securisation? If so, the global variable point on a single object and can "fell" the semaphore/mutex. But passing make a copy that will likely have two different semaphore/mutex but will point to a single control! Do someone know if I'm wrong in this idea or not?
    Thanks

  • Calendar object with Microsoft DST patch

    We have been testing changes to the 2007 daylight saving time. We applied Microsoft DST patch to Windows 2000 with Java 1.3.1_18 and Windows 2003 with Java 5.0 Update 8. On both systems the calendar object return time zone of GMT although the system clock is set for Eastern.
    If the Microsoft patch is removed, the correct time zone is again returned. Has anyone else seen this behavior when Windows OS patch is applied?

    > Does anyone know exactly what the problem is (what has Microsoft changed) ?
    a) Go to <http://www.ciac.org/ciac/bulletins/p-006.shtml> and search for the "CAN-" links. Each component has a one paragraph description.
    b) According to <http://patch-info.de/IE/2004/10/12/20-35-16.html> it contains:
    mshtml.dll (6,0,2800,1476 - 29,09,2004)
    urlmon.dll (6,0,2800,1474 - 23,09,2004)
    shdocvw.dll (6,0,2800,1584 - 27,08,2004)
    wininet.dll (6,0,2800,1468 - 23,08,2004)
    browseui.dll (6,0,2800,1584 - 22,08,2004)
    shlwapi.dll (6,0,2800,1584 - 20,08,2004)
    c) Some of the things that could be breaking are DOM references and DHTML, which are advanced features that not every application uses.
    From <http://www.microsoft.com/technet/security/bulletin/MS04-038.mspx>:
    "Caveats: Microsoft Knowledge Base Article 834707 <http://support.microsoft.com/?id=834707> documents the currently known issues that customers may experience when they install this security update. The article also documents recommended solutions for these issues."
    Among other issues, that page says [<b>emphasis</b> added]:
    - After you install the MS04-038 security updates for Internet Explorer, some dynamic HTML (DHTML) <b>drag-and-drop operations are blocked</b> by Internet Explorer.
    - Security update 834707 includes a change to the way that Internet Explorer handles function pointers. This change in functionality occurs when an event handler points directly to a Document Object Model (DOM) function [...] Change in Internet Explorer function pointer behavior <b>causes code to not be executed</b> when an event handler is set to directly reference a DOM function after installing MS04-038 security updates.
    BTW, Note 785308 has been updated with a workaround.
    Regards,
    Sean

  • Pass by reference?  I think not!

    As I understand it, Java code automatically passes everything by reference. The code that I've written seems not to do this though.
         String benefitID = new String();
         String allBenID = new String();
              try
                   benefitInfoDAO.selectIDs(awardCode, i, benefitID, allBenID);
              catch (CMSException e)
                   throw e;
              }The strings benefitId and allBenID are assigned values in the selectIDs method. However, when execution returns to the calling method, their values are "". What's going on?

    You forget that Strings are immutable objects, and when you pass the String into that other method, you are actually passing THAT String object into that method, here is an example.
    class Bob()
    Bob()
    String myString = "Hello";
    doSomething(myString);
    System.out.println(myString); //Still prints out "Hello"
    public void doSomething(String inString)
    System.out.println(inString); //Prints out "Hello"
    inString = "Bye!";
    System.out.println(inString); //Prints out "Bye!"
    Why is this? This is because Java passes everything as pointers, and not as C++ "References". Strings are also special, because they are immutable objects, there is no real way to manipulate a String object's memory once it's created. You can however do this to achieve the result you were looking for:
    class Bob()
    Bob()
    StringBuffer myString = new StringBuffer("Hello");
    doSomething(myString);
    System.out.println(myString.toString()); //Now it prints out "Bye!"
    public void doSomething(StringBuffer inString) //inString is a NEW pointer, you can change where it's pointing, but it will not change where myString in pointing!
    System.out.println(inString.toString()); //Prints out "Hello"
    inString.setLength(0);
    inString.append("Bye!");
    System.out.println(inString.toString()); //Prints out "Bye!"
    }

  • 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.
    ~

  • Pass-by-reference?

    Please tell me if I am wrong and explain how it actually works!
    But i think there is pass-by-reference..
    Part of Frame.java
    SplashPanel splashpanel = new SplashPanel(this);Part of SplashPanel.java
    public class SplashPanel extends JPanel{
         private Frame frame;
         public SplashPanel(final Frame frame) {
              this.frame = frame;I am newbie in Java and programming at all, so sorry if i am wrong.

    That's not pass by reference. That's passing a reference by value.
    Primitives are passed by value.
    References are passed by value.
    Objects are not passed at all--not by reference, not by value.
    Java is always pass-by-value. Always.
    Always. Always. Always.
    http://javadude.com/articles/passbyvalue.htm
    http://java.sun.com/developer/JDCTechTips/2001/tt1009.html#tip1
    http://www.javaranch.com/campfire/StoryPassBy.jsp
    http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
    http://www-106.ibm.com/developerworks/library/j-praxis/pr1.html
    http://www.cs.toronto.edu/~dianeh/tutorials/params/
    http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#38698
    http://radio.javaranch.com/channel/val/2004/05/21/1085125887000.html
    There is exactly one parameter passing mode in Java -- pass by value -- and that helps keep things simple.
    -- James Gosling, "The Java Programming Language, Second Edition"
    (James Gosling being the father of Java)

  • About pass-by-reference

    From my current understanding, the recommended way (with ARC enabled) of 'pass by reference' is like:
        -(void)somefunc:(someclass **)byref;
        // and 'someclass **' should be inferred to 'someclass * __autoreleasing *'
        // am i right?
        //or we could just explicitly define it like
        -(void)somefunc:(someclass * __autoreleasing *)byref;
    However, from the answer to this thread, http://stackoverflow.com/questions/8814718/handling-pointer-to-pointer-ownership -issues-in-arc.
    It seems -(void)somefunc:(someclass *__strong *)byref could do the trick as well (in demo2 of above link).
        1.-(void)somefunc:(someclass * __autoreleasing *)byref;
        2.-(void)somefunc:(someclass *__strong *)byref
    For the first one, as documented by Apple it should be implicitly rewritten by compiler like this:
        NSError * __strong error;
        NSError * __autoreleasing tmp = error;
        BOOL OK = [myObject performOperationWithError:&tmp];
        error = tmp;
    It seems the second one has a better performance? Because it omits the process of 'assign the value back' and 'autoreleasing'. But I rarely see functions declared like this. Is it a better way to use the second function to do the 'pass by reference' job?
    Any suggestion or explanation? Thanks in advance.

    Why do you need to do this? Because Objective-C is based on pointers rather than objects, you already have pass by reference. In C++ it is a big deal to pass objects by value compared to by reference. Just passing by pointer, as in the case with Objective-C, is usually all you need for pass by reference. It is only in rare circumstances that you really need to pass a pointer and have the pointer itself get changed. Apple does this to return error pointers. That is only because so many programmers are unable to do exceptions properly.

  • JCS operation arguments, pass by reference or copy?

    Can I assume that objects passed from JPF into JCS, or between JCS arguments are passed by reference?
    [email protected] (replace MASK with '_')

    I'm asking this because the JCS may be in its own project independent of the web project, I wonder if it will still be pass by reference vs copy.
    If it is pass by copy, I'll need to return beans passed into JCS operations as follows:
    formBean = myControl.actionA(formBean);
    [email protected] (replace MASK with '_')

  • CPP DLL's use pass-by-reference integration with teststand

    I have the detail in the attached Outlook format file.
    Attachments:
    CPP DLL Integration with Teststand.docx ‏120 KB

    If you don't know what a method is, you're going to have a number of problems down the road... A method is a function. It's a member of a class. It sounds like you may need to go through some .NET tutorials to understand the terminology.
    Arrays in .NET are objects and are always passed by reference. That said, you would need to provide the details on the method's signature (i.e., the function prototype). Is the array a System.Array object or a regular old "int[]"? Is the method actually returning an array, or is it operating on the array in place. What is the return datatype of the method?
    Message Edited by smercurio_fc on 08-15-2008 02:26 PM

Maybe you are looking for