Author | Topic: String Construction |
Wai Iu greenhorn |
posted April 17, 2000 11:16 AM
String astr=new String(); String astr=new String(""); Are the above two line of codes the same when generating an Moreover, for the following two lines of codes: String bstr=null; Are they the same? Please help, Thanks!
|
sree ranch hand |
posted April 17, 2000 12:05 PM
Wai, String astr=new String(); String astr=null;//astr doesn't hold any thing. Maha or anyone please correct me if i am wrong. I have a question myself. String astr=new String(""); Does it mean that now two "" string objects have been created one in the pool and one in memory?
|
maha anna bartender |
posted April 17, 2000 01:23 PM
Wai Iu, Sree, String s1=new String(); String s2=new String(""); Both are SAME Both statements create an emptyString in the heap. In fact in this code from this post there are 2 empty strings created in the heap memory. Both have nothing in it and length = 0 (which is no. of chars in the String object).
Also note that don't bother about the literal pool for cert purpose. In the above statements only 2 String objects are created. The foll code prints at run time
Sree, For the exam purpose don't bother about the literal pool's copy. [This message has been edited by maha anna (edited April 17, 2000).]
|
Wai Iu greenhorn |
posted April 17, 2000 07:08 PM
Thanks, Anna and Sree. Your comments really help me understand the problem. Another question, when does a program generate a NullPointerException and when does it generate an ArrayIndexOutOfBoundsException? Sometimes, I am just confusing about these two kinds of RuntimeExceptions.
|
maha anna bartender |
posted April 18, 2000 12:11 PM
Wai Iu, It is like this. When a reference is null and you try to invoke some member of its class type, for example nullref.someMethod() or nullref.somevar then a NullPointerException will be thrown at run time. Note that this rule is applicable for all ref type (class/interface/arrays). The ArrayIndexOutOfBoundsException is different. THis is thrown at run time when you have non-null reference, in other words the reference is already assigned to a solid physical array, and you try to access an element of the array by giving index value which falls out of its current size. Which means if an array has length = 10 (0,1,2,3,4,5,6,7,8,9) you can give index values anything bet 0(inclusive),1,2,3...9(inclusive).
regds [This message has been edited by maha anna (edited April 18, 2000).]
|
Javix Protocol ranch hand |
posted April 24, 2000 03:02 AM
maha anna care to tell me about the intern() in String . ------------------
|
| | |