In eckel, chap4; what is the answer to: What is the difference between the (S1) String field initialized at point of definition and (S2) one initialized by the constructor ? My guess on the answer would be that S1 is initialized FIRST prior to S2. What if I created another String field which is 'final', will that get initialized first instead, if it is also initialized at point of definition ? Pho
Yeah, Randall, you're right. I guess I read the question just too fast. I don't know the answer to Pho's question; it's a good question. I hope someone knows the answer 'cause I'd like to know, too. Allen
Allen, My curiosity with the URL you posted took me to that wonderful discussion on 'String'. I am given to understand that everything in Java is an object. However, the string 'literal' that figures in the discussion has me confused. Is this 'literal' also an object in true sense. Please clarify. thanks, Raj.
Rajendra, In java, Strings are considered to be objects. String objects can be made in two ways either using the new modifier(like other objects) or without the new modifier(like other primitives).Memory storage for String reference variables are same like other object references. Lalit.
Joined: Oct 21, 2000
Pho Tek, It has been a while since I studied this so I waited for someone else to answer. The way I remember is that when you create an object, first super() is called, then declaration/assignments and initializers, lastly the rest of the constructor. So S1 will be initialized before S2. ------------------ Dont blindly believe everything I say.
Thanks for all your "attempts" at answering. I'm going to read the Java language spec and see if there's anything in there. Also does anybody know how to track the progress of the initializations of members via reflection (is that possible) - so that I can verify my conjenctures.. Pho
Pho, I can't tell if you are asking about the order that these get created or if you are asking the difference between saying String s = "XYZ"; and String s = new String("xyz"); So I'll try for both.
The order of execution is: 1 - static initializer blocks 2 - initializer blocks 3 - constructors. 4 - main()
Rajendra Objects are created on the heap. Garbage collection is done to keep the heap clean. When you use the "new" operator you are creating an object. Variables are created in the stack. Each method has it's own stack. If it is a local variable, when the method completes, the stack for that method is discarded. The garbage collector does not do this. The variable s will be discarded whenever the variable goes out of scope. However the String literal "XYZ" will get created at class load time in the Constant Pool, the garbage collector will not get rid of that. String Literals are NOT objects. They do not exist on the heap.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Oct 21, 2000
Pho, The JLS is the place to look. It describes in detail the order.