Joshua Baker
Joshua Baker

Reputation: 399

What is the output and why?

What would the output be of these two statements. I am having trouble understanding how this works. I would say for number 1, b = 33. This is it says a=a+1 so therefor a = 33. b is equal to a, so b must also be 33? For the second one I would say b = delmar. Sort of confused, would appreciate some help, thanks.

1:

int a;
int b;
a = 32;
b = a;
a = a + 1;
System.out.println(b);

2:

Person a;
Person b;
a = new Person("Everett");
b = a;
a.changeName("Delmar");
System.out.println(b.getName());

Upvotes: 1

Views: 160

Answers (3)

Rais Alam
Rais Alam

Reputation: 7016

In case of premetive after addition, new object is created. Hence b would point to old a which is equal to 32.

But in case of non premetive Person class both a and b are pointing to same object hence any change to object will be reflated to both refrence variable.

Upvotes: 0

P.P
P.P

Reputation: 121347

In the first one, the value of a is copied to b. So the change in a later doesn't affect b.

In the second both a and b refer to the same object. So change in a later will reflect in b.

So the output will be: 32 in the first case and Delmar in the second case.

Upvotes: 1

christopher
christopher

Reputation: 27336

Output of the first statement is 32. This is because b is not an object, so the int variable doesn't represent a pointer to an object; it represents the actual value.

The second statement will output "Delmar". This is because B and A actually point to the same object, and when you change a value in a, you implicitly change the value in b.

Upvotes: 2

Related Questions