Java String variable setting - reference or value?

后端 未结 9 801
感动是毒
感动是毒 2020-11-30 01:08

The following Java code segment is from an AP Computer Science practice exam.

String s1 = \"ab\";
String s2 = s1;
s1 = s1 + \"c\";
System.out.println(s1 + \"         


        
相关标签:
9条回答
  • 2020-11-30 02:05

    Indeed, String is a class and it's assigned / passed by reference. But what's confusing is the statement:

    String s = "abc";
    

    Which suggests that String is a primitve ( like 'int x = 10;' ); But that's only a shortcut, the statement 'String s = "abc";' is actually compiled as 'String s = new String( "abc" );' Just like 'Integer x = 10;' is compiled as 'Integer x = new Integer( 10 );'

    This mechanism is called 'boxing'.

    And more confusing is: there's a class 'Integer' and a primitive 'int', but String doesn't have a primitive equivalent (allthough char[] comes close)

    Sije de Haan

    0 讨论(0)
  • 2020-11-30 02:05

    In Java, String objects are assigned and passed around by reference; it this respect they behave exactly like any other object.

    However, Strings are immutable: there isn't an operation that modifies the value of an existing string in place, without creating a new object. For example, this means that s1 = s1 + "c" creates a new object and replaces the reference stored in s1 with a reference to this new object.

    0 讨论(0)
  • 2020-11-30 02:10

    String is a class, so a String variable is a reference. But it's a language intrinsic, in the sense that Java has special handling and syntax for it, which is why you can do things like your example.

    See e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

    0 讨论(0)
提交回复
热议问题