Hi , I found this ques in the ibm certification tool would like to know what u think the correct answer would be public class Xxx { static String s ="AAA"; static { s = (s + "BBB"); } public static void main(String args[]) { System.out.println("s = " + s); static { s = (s + "CCC"); } } } a) s = AAA is displayed
b) s = BBB is displayed
c) s = AAABBBCCC is displayed
d) lines 3 and 6 produce a compiler error i think the ans is d) as a static block will get executed only once at class load time and as strings are immutable objects you cannot initialise like this . ANy suggestions / correct explanations ? Thanks Arijit
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
The answer is C Lets see, Now the first a String opbject s i s made which ahs a vlue AAA. In the next static block you are actually re-initializing the String object when you say : [b] s = (s + "BBB"); [\b] Remember that each time time we concatenate a new String object is created and hence when we assign it to the same String object the value is re-initialized. Thus the answer is AAABBBCCC. Hope this helps.
Indu mathy
Greenhorn
Joined: Jun 08, 2000
Posts: 8
posted
0
public class Xxx { static String s ="AAA"; static { s = (s + "BBB"); } public static void main(String args[]) { System.out.println("s = " + s); static { s = (s + "CCC"); } } } in the above program the public static void main should be closed by } then static block should be given. i hope since String s is static the s gets re_initialized so if we give second static block after public static void main we get the o/p of s as AAABBBCCC
Indu
Arijit Kundu
Greenhorn
Joined: Jan 19, 2000
Posts: 19
posted
0
thanks lionel , i got it bye Arijit
Arijit Kundu
Greenhorn
Joined: Jan 19, 2000
Posts: 19
posted
0
thanks indu , u r right in pointing out the typo . thanks for ur help bye Arijit
Sunita
Greenhorn
Joined: Jun 08, 2000
Posts: 28
posted
0
Hi I got one basic doubt.Can we use the method name as static. I think static is a reserved word. Any one of u please help me..... Rgds Sunita
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
posted
0
Originally posted by Sunita: Hi I got one basic doubt.Can we use the method name as static. I think static is a reserved word. Any one of u please help me..... Rgds Sunita
static is a reserved word, what is defined here is a 'static code block' not a method. It is run once and only once on initial class load, you can't run it again like you can a method. It can be used to do initalization of static variables when you need to do complex operations to intialize them. For example, you can use a static code block to read in a properties file when your class is loaded.