Copying strings in Java

This exercise took me awhile to figure out. It is very simple, but what made it harder was the question being asked. I think my best advice is to be very careful about what’s being asked. In this exercise I create two variables, the second variable holds the value of the first variable, then I needed to make the second variable uppercased. 

The code:

String greeting = “Hello, World!”;

String greeting2 = greeting;


The questions:

What is the value of greeting?

What is the value of greeting2?

Here is a more visual presentation:



Compiling and then running the above 3 lines of Java will only returns the current value of greeting2, which is in uppercase because we are calling the toUpperCase() method on greeting2, currently. This is where I got confused, when I ran the code the result was “HELLO, WORLD!” and I was getting it wrong because that’s not what’s being asked.

In order to find out what the answer to the aforementioned questions are, one have to call greeting and greeting2 indepandently, or if you’re smarter than me you can figure it out immediately. 



Once we call greeting2 indepent from the toUpperCase() method we get “Hello, World!”, which is the value of the variable greeting (the first variable) and will not return the value uppercased because greeting2 is just a reference to the value of the first variable.

So the answer to both of the obove questions are the same, because on the second question they are asking what’s the value of greeting2 and not what’s the value of greeting2.toUpperCase().


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s