Oscar F
Oscar F

Reputation: 323

Java Logic confusion

Can someone explain to me why with this code prints out "abeb" instead of abcb? I understood it was because you reference list2 from list1 so changing list2 also changes list1 but I'm not quite understanding that entirely.

char [] list1 = {'a','b','c','d'};    
char [] list2 = list1;    
list2[2] = 'e';    
list1[3] = list2[1]    
for (char a: list1)    
out.print(a)`

Why is the same logic(the logic I'm understanding) not being applied here in this code? It prints out x as "5" were from what I understood from the code above it should be 7?

int x = 5;
int y = x;
y += 2;
out.print(x);

Upvotes: 0

Views: 77

Answers (2)

JB Nizet
JB Nizet

Reputation: 691695

list2[2] = 'e' assigns a new value, 'e', to the third element of the list2 array. It thus modifies the array. list2 and list1 are two variables containing a reference to the same array.

Before:

list1 --> [a, b, c, d]
          ^
          |
list2 ---/

After:

list1 --> [a, b, e, d]
          ^
          |
list2 ---/

y += 2 increments the value of the variable y, which is different from the value of the variable x:

Before:

x  --> 5
y  --> 5

After:

x --> 5
y --> 7

Upvotes: 6

codingenious
codingenious

Reputation: 8653

This is because, first operation you are doing is on arrays and they are treated as objects in Java.

But second operation is done on int and that is a primitive type. So reference rule doesn't apply here.

Upvotes: 2

Related Questions