0

Hi I did some reading and came across this behavior that I don't really know why is like this. Would love to get an explanation why it works like this.

class InputTest {
    public static void main(String[] args){
        System.out.println("WITHOUT array:");
        byte a=0;
        System.out.println(a);
        test(a);
        System.out.println(a);

        System.out.println("WITH array:");
        byte[] b={1,2,3,4,5};
        System.out.println(b[3]);
        test2(b);
        System.out.println(b[3]);

    }
    static void test(byte a){
        a=120;
    }
    static void test2(byte[] b){
        b[3]=120;
    }
}

printing of the code is:

WITHOUT array:
0
0
WITH array: 
4
120

So I kinda want to understand why this is so maybe I don't make a unnecessary mistake in the future.

martius
  • 60
  • 8
  • Please post your code in the question; links to external sites might die, rendering the question useless. Also, "WITH" and "WITHOUT" array look like they are the wrong way round. – Andy Turner Jan 05 '16 at 15:46
  • The short explenation is: the `byte` is a primitive type. In this case you are only working with the value. Hence changing the value of the byte wont effect the original value that was passed as a parameter since you are not working on a reference. On the other hand arrays are handled as objects. Due to this you are working on the reference of the array and changing a single value inside this array will affect the original array that was passed as a parameter. If you would reassign the passed array as `b = new byte[10]` and assign values to, then it wouldn´t change the original array. – SomeJavaGuy Jan 05 '16 at 15:51
  • The long answer is given in the duplicate link. – SomeJavaGuy Jan 05 '16 at 15:52
  • Thanks for a good answer Kevin Esche. I think my answer is a bit different from the duplicate, since as Kevin Esche said, primitives act by value. Thanks anyways. I have never heard of the pass by value / pass by pointers/reference debate. I'll try learn to put code in the question next time. I just don't know how yet. I guess I can try figure it out to next time, but I don't think It is so intuative. I don't know how to make a lineshift either. – martius Jan 05 '16 at 17:45
  • Found out how to put code now. But how did you add colors to my code? – martius Jan 05 '16 at 20:23
  • Learned that too. http://meta.stackexchange.com/questions/137685/how-to-insert-code-in-stack-overflow – martius Jan 06 '16 at 20:13

0 Answers0