Java Challenge (2)

Here I am again!!

The most of java programmers have in mind the knowledge about reference variables, so it’s easy for them to tell the console output of the code below:

import java.awt.Dimension;
public class Test {
              public static void main(String[] args) {
                          Dimension d1 = new Dimension(100, 50);
                          Dimension d2 = d1;
                          System.out.println(“d2 width = ” + d2.width);
                          d1.width = 50;
                          System.out.println(“d2 width = ” + d2.width);

The variables d1 and d2 make reference to the same, and the only one existing, Object. So, changes made by d1 will affect the Object’s content, wich is referenced by d2 too. So the console output is:

d2 width = 100
d2 width = 50

After that explanation, what is the console output of this similar code?

public class Test {
          public static void main(String[] args) {
                         String s1 = new String(“Teste 2”);
                         String s2 = s1;
                         System.out.println(“s2 = ” + s2);
                         s1 = s1 + ” modified”;
                         System.out.println(“s2 = ” + s2);

Try to answer it without implementing any code, all right? 🙂
Next post, I’ll show the answer.


2 thoughts on “Java Challenge (2)

  1. Hmmm… I will try… :p

    I guess that statement:

    s1 = s1 + “modified”

    will assign a new String object to s1, thus, the object referenced by s1 will not be the same referenced by s2, and the modifications in s1 String will not affect the s2 String value.

    Console Output:

    s2 = Test 2
    s2 = Test 2

    I´m correct?

  2. I believe that both prints will show the same result: “Teste 2”.
    This would occur once that String type is stored similarly to a primitive type, althoug being an Object.

    And good luck with the blog, it’s getting really nice!

Leave a Reply

Please log in using one of these methods to post your comment: 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