[HD Pg 0, Sec. 3.2.1 - reference-variables-and-primitive-variables]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
zeldalex
Posts: 3
Joined: Sun May 12, 2019 8:32 am
Contact:

[HD Pg 0, Sec. 3.2.1 - reference-variables-and-primitive-variables]

Post by zeldalex »

Hi, I was wondering why str1 is not changed in the following code

Code: Select all

String str1 = new String("String1");
String str2 = str1;
str2 = "String2";
System.out.println(str1);
 
The output will always be String1, changes on str2 seems doesn't affect str1, but according to my understanding, with the 'new' keyword the String object shall be placed on the heap and both str1 and str2 shall point to the same object?

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 0, Sec. 3.2.1 - reference-variables-and-primitive-variables]

Post by admin »

Yes, at the end of String str2 = str1; both str1 and str2 will point to the same string object containing "String1".
But the next statement is str2 = "String2"; this will make str2 point another string object containing "String2". But this statement doesn't affect str1. It will still point to the first string object containing "String1".
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 40 guests