Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Immutable Integers

  1. #1
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,609
    Thanks
    25
    Thanked 316 Times in 295 Posts

    Default Immutable Integers

    Hello,

    I am attemping to figure out how to increment an integer value from another method (without returning the new value). Does anyone know a way to do this?

    Here is an obviously wrong solution that simply shows the sort of behavior I am trying to get:
    public void method1() {
    	int value = 0;
    	for(int i=0;i<10;i++) {
    		method2(value);
    		System.out.println(value);
    	}
    }
     
    public void method2(int value) {
    	value++;
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,530
    My Mood
    Mellow
    Thanks
    157
    Thanked 615 Times in 602 Posts

    Default Re: Immutable Integers

    If you define the variable, in this case 'value', INSIDE the method, it is LOCAL and VISIBLE only to that method. If you want a variable to be seen outside the method, then first define it outside the method:
    class ExampleClass
    {
        // define the variable here
        int value;
     
        // other code as needed
     
        // then the method that increments the variable
        public void incrementValue()
        {
            value++;
     
        } // end method incrementValue()
     
    } // end class ExampleClass

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Immutable Integers

    All primitive types in Java are pass by value. All arrays and objects are pass reference by copy. Thus the best you can get to truly passing by reference is to pass some non-primitive type.

    The most "correct" method is to somehow encapsulate value into a meaningful object which can be passed to method2.

    However, there is a semi-hack way to pass a single element array as a pointer-like value.

    What are you trying to accomplish? Why can't you return a value and re-assign to the original variable?

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,609
    Thanks
    25
    Thanked 316 Times in 295 Posts

    Default Re: Immutable Integers

    I managed to solve the issue by placing the int in an array and passing the array of a single int. This is basically how I would change my basic example to work properly:
    public void method1() {
    	int[] value = new int[]{0};
    	for(int i=0;i<10;i++) {
    		method2(value);
    		System.out.println(value[0]);
    	}
    }
     
    public void method2(int[] value) {
    	value[0]++;
    }

    A class variable was not an option, as the methods were static and the class is actually server-side, which would mean there could be an unknown number of sessions accessing the class at the same time. A static class variable would not be safe by any means in this situation (I didn't think all this detail would be very important for this question, so I didn't include it in the original question).

    I couldn't return a value because the methods in the real program are already returning a different object. Basically, I had an array of Object As, each of which contained X number of Object Bs. I was looping through the Object As in one method, and then looping through the Object Bs in each Object A in another method and sending the Object Bs to a third method, where Object Cs were being created from each Object B. The Object Cs were being returned from that method and an array was being created out of them. The reason I needed a mutable integer was because each Object C had a reference number associated with it that needed to be incremented.
    Since the reference counter was being incremented three methods deeper than where it was declared, I was having trouble figuring out how to keep track of its value.

    This sounds like a crazy-ass system, and it is, but there is a rhyme and reason behind the way things are.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Member
    Join Date
    Sep 2013
    Posts
    101
    Thanks
    38
    Thanked 0 Times in 0 Posts

    Default Re: Immutable Integers

    Forgive my ignorance but does this mean when you pass an object the method doesn't create a copy of that object but rather uses that very object?

    All primitive types in Java are pass by value. All arrays and objects are pass reference by copy. Thus the best you can get to truly passing by reference is to pass some non-primitive type.
    aren't array's and objects non-primitive types? I am unable to clearly ascertain your meaning; "All arrays and objects are pass reference by copy". To me that seems to imply that they are copies, but then you say that non-primitive types pass by reference. I would be pretty green in the face if I was so wrong on what I defined as non-primitive (an object created of primitive types (given types)).

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,530
    My Mood
    Mellow
    Thanks
    157
    Thanked 615 Times in 602 Posts

    Default Re: Immutable Integers

    I recommend you read this discussion which is a really long answer to your question, called "Cup Size," including the second part. Everybody learns and remembers differently, but this is one of the best explanations I've seen, and I remember it because of the simple way it's explained.

  7. #7
    Member
    Join Date
    Sep 2013
    Posts
    101
    Thanks
    38
    Thanked 0 Times in 0 Posts

    Default Re: Immutable Integers

    That's fine, but I'm curious how methods handle these variables. I always was under the impression that non-primitive types are copied for use (with parameters). If I am wrong there could be some dangerous consequences.

  8. #8
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,470
    My Mood
    Grumpy
    Thanks
    0
    Thanked 159 Times in 150 Posts

    Default Re: Immutable Integers

    Remember that Java is ALWAYS pass-by-value. The value of the primitive is passed as the parameter. For objects the reference to that object is passed by value and not the object. The fact that Java uses references when dealing with objects confuses the matter as some people incorrectly think that means objects are passed-by-reference. This absolutely incorrect.
    Improving the world one idiot at a time!

  9. #9
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Immutable Integers

    Quote Originally Posted by KAJLogic View Post
    ..under the impression that non-primitive types are copied for use (with parameters)...
    Non primitive types, when passed as parameters, are not copied. Instead a copy of the reference to the object is passed. The object is not copied, but is subject to modification by the receiving method.

  10. The Following User Says Thank You to jps For This Useful Post:

    KAJLogic (September 2nd, 2013)

  11. #10
    Member
    Join Date
    Sep 2013
    Posts
    101
    Thanks
    38
    Thanked 0 Times in 0 Posts

    Default Re: Immutable Integers

    That wraps it up quite nicely. Given the initial problem I would say that easily closes this thread.

Similar Threads

  1. immutable
    By chalapathi in forum Java Theory & Questions
    Replies: 2
    Last Post: May 7th, 2012, 09:31 AM
  2. immutable
    By saurabhRBMI in forum Java Theory & Questions
    Replies: 2
    Last Post: October 1st, 2011, 11:23 AM
  3. Replies: 3
    Last Post: July 24th, 2011, 06:13 AM
  4. [SOLVED] Writing Integers to .txt File; Returning Random Characters Instead of Integers
    By verbicidalmaniac in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: March 8th, 2011, 08:42 PM
  5. Determine the two smallest integers from a set of user input integers
    By bpontin in forum Loops & Control Statements
    Replies: 4
    Last Post: October 17th, 2010, 06:38 PM