0

I am new to java and I was writing some code to practice, but there is something that I am confused about. I have the following code:

public class test {
    public static void main(String[]args) {
        int n = 0;
        ArrayList<String> fruits = new ArrayList();
        setList(fruits);
        n =setInt(9);

        // get the values from fruits
        for (String value: fruits) {
            print(value);
        }
    }

    public static void setList( ArrayList list) {
        list.add("pear");
        list.add("apple");
        list.add("pear");
    }

    public static int setInt(int number) {
        number = 3;
        return number;
    }
}

My question is why in order to set my Arraylist() there is no need to return the any value, but in order to set my int I need to return something.If run this code it prints all the values in my list, but I expected not to print anything because In my method setList I do not return any value. If I did not return any value with my setInt, the value of n would not change, and that makes sense to me. Thank you.

Raceimaztion
  • 8,844
  • 4
  • 24
  • 38
danilo
  • 792
  • 7
  • 24

1 Answers1

1

There are different ways to that params get passed in functions. The usuall way that most beginners start with is pass by value. The other way is pass by reference. In passing by reference, the object itself is pass in, not a copy as is with pass by value. That means any changes will affect the param and remain, even after it is called. All objects in java are passed by reference, only primitives are passed by value. Thus, is why you don't have to return when using arraylist object.

Edit: Actually, I've made an error. What is actually occuring is that a copy of the reference itself is being passed by value. Take a look at this. Everything in Java is Pass by Value.

Community
  • 1
  • 1
jax
  • 678
  • 9
  • 27
  • Sorry for the downvote, but *"All objects in java are passed by reference"* is not correct. Please read this: [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/q/40480) – Tom Jul 29 '15 at 17:29
  • *"Everything in Java is Pass by Reference."* Haven't we just learned, that everything is passed by value? ;P – Tom Jul 30 '15 at 06:30
  • @Tom Ops, i'll fix that. Thanks – jax Jul 30 '15 at 07:18