Java String variable setting - reference or value? -


the following java code segment ap computer science practice exam.

string s1 = "ab"; string s2 = s1; s1 = s1 + "c"; system.out.println(s1 + " " + s2); 

the output of code "abc ab" on bluej. however, 1 of possible answer choices "abc abc". answer can either depending on whether java sets string reference primitive types (by value) or objects (by reference).

to further illustrate this, let's @ example primitive types:

int s1 = 1; int s2 = s1; // copies value, not reference s1 = 42;  system.out.println(s1 + " " + s2); // prints "1 42" 

but, had bankaccount objects hold balances.

bankaccount b1 = new bankaccount(500); // 500 initial balance parameter bankaccount b2 = b1; // reference same object b1.setbalance(0); system.out.println(b1.getbalance() + " " + s2.getbalance()); // prints "0 0" 

i'm not sure case strings. technically objects, compiler seems treat them primitive types when setting variables each other.

if java passes string variables primitive type, answer "abc ab". however, if java treats string variables references other object, answer "abc abc"

which think correct answer?

java strings immutable, reassignment causes variable point new instance of string rather changing value of string.

string s1 = "ab"; string s2 = s1; s1 = s1 + "c"; system.out.println(s1 + " " + s2); 

on line 2, s1 == s2 , s1.equals(s2). after concatenation on line 3, s1 references different instance immutable value of "abc", neither s1==s2 nor s1.equals(s2).


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -