| Author |
String variables in static method
|
vidhya suvarna
Ranch Hand
Joined: Aug 28, 2008
Posts: 148
|
|
Source: ]http://www.javabeat.net/javabeat/scjp2/mocks/scjp_1_4_mock_exam_questions_2.php public class Test14{ static String s ="Instance"; public static void method(String s){ s+="Add"; } public static void main(String a[]){ Test14 t = new Test14(); s = "New Instance"; String s = "Local"; method(s); System.out.println(s); System.out.println(t.s); } } What is output? A1 Local Instance A2 Local New Instance A3 Loca Add New Instance A4 Compiler Error The correct ans is Local New Instance. Can someone tell me why the value of s updated in method() doesnt affect it when it's displayed? [ September 17, 2008: Message edited by: vidhya suvarna ] [ September 17, 2008: Message edited by: vidhya suvarna ]
|
SCJP 1.4 - 88%<br />SCWCD 1.5 - Preparing
|
 |
sannuth kashikar
Greenhorn
Joined: Sep 16, 2008
Posts: 14
|
|
|
|
scjp5 90%
|
 |
chander shivdasani
Ranch Hand
Joined: Oct 09, 2007
Posts: 206
|
|
public class Test14{ static String s ="Instance"; public static void method(String s){ s+="Add"; } public static void main(String a[]){ Test14 t = new Test14(); public class Test14{ static String s ="Instance"; public static void method(String s){ s+="Add"; } public static void main(String a[]){ Test14 t = new Test14(); s = "New Instance"; String s = "Local"; method(s); System.out.println(s); System.out.println(t.s); } } } } In these kind of questions, just remember that local variables have priority over other variables. s = "New Instance";//This is Static variable String s = "Local";//This is local variable method(s); //Local variable take precedence over static, so local variable is sent to the function. and the function modifies the local variable(The variable local to this function)
|
Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
|
 |
vidhya suvarna
Ranch Hand
Joined: Aug 28, 2008
Posts: 148
|
|
If you change the occurrence of statements: s = "New Instance"; String s = "Local"; as String s = "Local"; s = "New Instance"; you will find that static variable is passed to the method. My query is s is a String variable(object) so if we update its value in a method wouldnt it be reflected when it returns from the method?
|
 |
Stephen Davies
Ranch Hand
Joined: Jul 23, 2008
Posts: 352
|
|
Here is my take on things. [ September 17, 2008: Message edited by: Stephen Davies ]
|
be a well encapsulated person, don't expose your privates, unless you public void getWife()!
|
 |
vidhya suvarna
Ranch Hand
Joined: Aug 28, 2008
Posts: 148
|
|
|
Thanks Stephen i got it now!
|
 |
 |
|
|
subject: String variables in static method
|
|
|