• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

inner class doubt

 
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi in K&B book there written

that method-local inner class can't access the locol variable in which its defined...

like this below

Because the local variables aren�t guaranteed to be alive as long as
the method-local inner class object, the inner class object can�t use them. Unless the
local variables are marked final! The following code attempts to access a local variable
from within a method-local inner class:
class MyOuter2 {
private String x = "Outer2";
void doStuff() {
String z = "local variable";
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Local variable z is " + z); // Won't Compile!
} // close inner class method
} // close inner class definition
} // close outer class method doStuff()
} // close outer class
Compiling the preceding code really upsets the compiler:
MyOuter2.java:8: local variable z is accessed from within inner class;
needs to be declared final
==================

but here above "z" is object ...even that will not accessible ?

just because it will be ready for garbage collection when method returns ?
will that be not in heap...what if we return "z" ? then ?

just clarify me


*** one more thing ... why the method local innenr class can't be marked public,private, protected, static, ???
[ April 28, 2005: Message edited by: amit taneja ]
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if you have a method local object ( say assigned to z) and if you return z, a reference to that object is returned and a new reference variable is used to refer to that object. ( this is why the object is not eligible for GC).

But once return is done, the initial variable z used to reference the object wont be alive ( even though the object is still accessible through another refernce , the variable z is no longer accessible). This is why a method local inner class cant access local variables of a method.

hope this helps !!
[ April 28, 2005: Message edited by: Jagadesh cs ]
 
Jagadesh cs
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


*** one more thing ... why the method local innenr class can't be marked public,private, protected, static, ???



A method local inner class should follow all rules that are applicable for local variables. Since you cant apply any modifiers except final to local variables , that also applies to method local inner classes ( you can apply only final and abstract to method local inner classes )
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The string "local variable" will not be in the heap it will be in the string pool. An object will be created in the heap only when string is created using new.


Rubbish.
http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true

I *so* wish that codswallop would go away.
Is it from yet another poorly written book or something?
 
Jagadesh cs
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for that tony ... i wanted to say some thing and i ended up sayin some thing else !!!



hope this will make it clear !!
 
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Now I am confused.

In the first case Jagadesh has mentioned, the object resides in the literal pool and not in the heap, right ?
In the second case there are two objects, one in the heap and the other in the pool (provided there is not an identical one there already).

Are the above true ?

Thanks,
Soumya.

String on heap and in pool
 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jagadeesh,
i've to say u some misconceptions regarding
Originally posted by Jagadeesh

String str = "java"; // Creates a reference variable and an object
String str = new String("java") //creates two objects and a reference


well plz refer to Strings by Corey URL.....one of The Best articles till now on Strings.

well in short i'll give my say:
String str = "java"; // Creates a reference variable and an object

is wrong......actually 2 references are created on one object(the string literal) which is on heap

String str = new String("java") //creates two objects and a reference
is again wrong:
well execution of above line after " String str = "java"; " will have two objects and two references. How?? well plz read that in the link provided...
in short.....
one reference is from the String Constant Pool to the string object on heap created initially(at the time of class loading b4 initialization happens) and another reference is the one created with new operator and that refers to a new String object(mind it, again created on the heap only and not in the String pool) created.
str.intern() returns a reference to the string of String pool.

in case of any doubts.....plz do get back
thanx
amit
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That article is flawed and contains fallacy.
Perhaps it is this that is the cause of confusion in this forum?
I am determined to clear up the wrong-doings of others at any expense as a personal mission.

Please send comments, particularly information that you feel is missing (after all, completeness is paramount), on my second attempt (after comments from Jim Yingst on the initial attempt) to tony _at_ jtiger.org

http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Tony Morris:
That article is flawed and contains fallacy.



Tony, any chance you could be more specific about what statements in the article are wrong?

Thanks.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sure, I'm a little busy at the moment, but perhaps over the weekend I'll get a chance.

I recall reading through the article finding minor points that were incorrect, but when I got to the part that explicitly suggests that String literals are not garbage collected, I stopped there. I provide proof that this is not true, with detailed explanation (i.e. classes, class loaders, etc.) and references (JVM Spec., etc.).

I'll provide a detailed refutation when I get a chance. Currently, I'm rebutting another article that I feel a little more strongly about
[ April 28, 2005: Message edited by: Tony Morris ]
 
Amit Das
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Tony,

Its highly appreciable on your mere thought of taking the responsibility and being proactive to show the mislead, the right path.....

well as u've said u'll do so, it'll be better if u continue in the same thread( i mean post) so that its easy for me(and all who have read this post till now) to get the clear picture.....hope u dont mind

thanx
amit
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is no distinction made between String literals and String constants in the introduction. The JLS is ambiguous in this respect. The issue at hand is specific to String constants, not literals as implied (assuming one side of the JLS ambiguity). The answer to the question "What is a String literal" makes unstated assumptions about the ambiguity in the JLS (and unfortunately, this ambiguity is a source of confusion in terminology).

"And just in case you were wondering, the '+' operator does the exact same thing as the concat() method." - this is blatantly false and misleading. Need I explain why? Heck, it forms part of the SCJP - the most basic of industry certifications that relate to Java.

"[referring to the String literal pool] Really, it's a collection of references to String objects." - this is false and unfortunately, appears to form the basis for the rest of the article. This statement severely undermines any future statements that are made. i.e. trust in the author is abandoned (though that's up to one's perspective and this is just mine).

The capital letters used in "String Literal Pool", as if were a proper noun, are a little amusing at first, but on a serious note, also undermine the alleged understanding by the author, but just a little.

"Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool." - OK, now the author is way off course. I'll keep reading, but not for informational purposes.

The code example highlights the importance of the distinction between a String literal and a String constant (if there in fact, is one as per the ambiguity in the JLS) which remains absent throughout the article.

"the JVM goes through the code for the class and looks for String literals." - I was beginning to think the author has a little credit. In fact, I thought the author might actually start referring to the constant_pool in the class format and show a little understanding, but to no avail. I am an optimist, but it pains me in times like these.

"An object is eligible for garbage collection when it is no longer referenced from an active part of the application." - blatantly false, and it is this misconception that has given me two free rides around the world (both to the US) to customer sites to fix the problem as a result.

"The answer is 1." - no it's not. Is this where all those JavaRanch folk have obtained their misinformation? Or is this where their study book authors have obtained it? Whatever the case, fallacy is clearly rife.

"That means that they always have a reference to them and are, therefore, not eligible for garbage collection." - OK, up until now all criticisms that I have presented have been a little weak in comparison to this one. I mean, where do you start? People are using this article as a definitive source ("well plz refer to Strings by Corey URL.....one of The Best articles till now on Strings.")!!! OK sure, that's their problem and really, it's quite a silly thing to do, but it happens nonetheless and sometimes you have to cater for those who are a little less aware than yourself (not to disacknowledge the fact that I too, am less aware than others in certain respects). But really... this statement is inexcusable. Fallacy is rife people! Do not take it for face value!! I see far (far, far) more bullshit than not, if you don't mind me saying so. This industry is ego-centric and egos hide truth in the name of pride. Don't be fooled.

"I constantly see this question coming up in the SCJP forum and on various mock exams." - well, I have to chuckle a little here. I wonder why the author thinks this is the case? Let's look at the facts; oh wait, too late, the facts have been superseded by fallacy and the poor misguided souls cannot be saved now.

"Equivalent String Literals (even those stored in separate classes in separate packages) will refer to the same String object." - no they won't (need I explain it again?).

"In general, String Literals are not eligible for garbage collection. Ever." - SLAP!! get a clue (in a friendly, informative, yet assertive way of course). Need I prove this wrong again? I think not.

"Strings created at run-time will always be distinct from those created from String Literals." - er, ambiguity++; An object representing a String literal is created at runtime. The author contradicts given the context that I assume given the ambiguity ("When a class is loaded..."), unless the author intended to go on to suggest that a class is not loaded at runtime (this is absurd surely?)?

"You can reuse String Literals with run-time Strings by utilizing the intern() method." - just WTF does that mean? Please explain how "you can reuse String Literals [sic] with run-time [sic] Strings"? This use of terminology is vague at best; clarification requested. Does it even mean anything? Accuracy is paramount! ...second only to completeness.

"The best way to check for String equality is to use the equals() method." - The best way to eat fruit is to eat an apple. I'll bet Sleeping Beauty would have something to say about that kind of silly dogmatism (not to be confused with justified dogmatism). This statement is a perfect conclusion to an article that merely portrays untruth to what seems to be an audience that are keen to learn, and thus, taking advantage of the apparant naivety of said audience. It is this kind of article that I believe would be better off not existing at all for the sake of the innocent less-informed who wish to change that fact. Please tell me ... it is not this article that formed the basis for either a) any certification book content b) the fallacy that appears to embed itself in the JavaRanch SCJP forum. Is it? It's not right?
 
soumya ravindranath
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Tony Morris:


"Equivalent String Literals (even those stored in separate classes in separate packages) will refer to the same String object." - no they won't (need I explain it again?).



Hi Tony,

With all respect to your opinion, I cannot quite understand why you refute the above statement.

I picked this up from section 3.10.5JLS second edition. Please look at point 3.




and the compilation unit:

package other;
public class Other { static String hello = "Hello"; }

produces the output:

true true true true false true

This example illustrates six points:

1. Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
2. Literal strings within different classes in the same package represent references to the same String object.
3. Literal strings within different classes in different packages likewise represent references to the same String object.
4. Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
5. Strings computed at run time are newly created and therefore distinct.
6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.



Thanks,
Soumya.
 
soumya ravindranath
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For other curious onlookers -

Can interned Strings be garbage collected?

Is JLS not trustworthy (at least to the less informed ones ) at all ?
[ April 29, 2005: Message edited by: soumya ravindranath ]
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Tony]: "Equivalent String Literals (even those stored in separate classes in separate packages) will refer to the same String object." - no they won't (need I explain it again?).

"No they won't" is rather misleading here. The vast majority of the time they do refer to the same instance. For any two classes which are in the same JVM at the same time, equivalent string literals will refer to the same object. It's only when classes are not in the JVM at the same time that we may find exceptions to the above rule. This requires that we have two different class loaders, and that we make sure the first class has been completely unloaded before we load the second class. Blanket statements like "this is false" or "no they won't" aren't terribly useful here as they mislead people into thinking the statement is never true, which is not at all correct in this case.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


For any two classes which are in the same JVM at the same time, equivalent string literals will refer to the same object. It's only when classes are not in the JVM at the same time that we may find exceptions to the above rule. This requires that we have two different class loaders


Not true.
I can prove it, can you?
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Tony]: I can prove it, can you?

Well, I could provide various examples that show the literals do refer to the same object. I don't have an easy way of proving that's always the case. So if you have a specific counterexample in mind, that would be appreciated. The ones you've posted so far always relied on unloading one class before loading another.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Although I can't prove that this is always the case, here's a sample of what I did to test my ideas before making the above assertions:

The code is refactored from past examples of Tony's, eliminating redundancies and trying to make it easier to run in a variety of environments as well as JDK's prior to 1.5. To run from the command line, you need:

java StringLiterals .

For other environments (e.g. an IDE) replace '.' with a path to wherever the class files are stored, relative to the working directory. I know Tony knows this, since he wrote the code I refactored; I'm just explaining for anyone else who may want to try this.

The key here is to see what happens if any of the currently-commented lines of code are uncommented. If we run the program as is, two different identity hashcodes are displayed. This indicates the literals refer to two different instances. If we uncomment any of the currently-commented lines of code, the identity hashcodes are the same. This indicates the literals refer to one instance (in all likelihood, anyway). At least this is true in all environments I've tried so far - if you learn otherwise, please describe the environment you're using.

It's worthwhile to run these examples using the java -verbose:class option. This makes it clear when a class is unloaded. Which is userful for verifying whether two classes are in the JVM at the same time or not.

Now, this does not prove my previous statement which Tony just quoted. It does however provide significant sample evidence. It's certainly possible there's some alternate way to evaluate string literals which I have overlooked. I look forward to Tony's next post.
[ April 29, 2005: Message edited by: Jim Yingst ]
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you encounter IllegalAccessException while running Jim's sample code, just add in the line in bold:

 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting. Tony's code handled this, but in my own test environments, accessibility was a non-issue, so I removed it in an attempt to cut down on unnecessary distractions. I've edited my last post with a more user-friendly version (including a few unrelated changes).
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bump.

[JY]: For any two classes which are in the same JVM at the same time, equivalent string literals will refer to the same object. It's only when classes are not in the JVM at the same time that we may find exceptions to the above rule. This requires that we have two different class loaders

[TM]: Not true.
I can prove it, can you?


Tony, some sort of clarification is in order here. As usual your "not true" is too vague to be useful to anyone. Which part of my statement was in error, in your opinion? In what way? Are you planning on showing some new sort of proof, or are you under the impression that your previous examples somehow disprove my assertion?
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To be honest, I don't understand the source of your misunderstanding - it is unclear to me. I have pointed out numerous times (5 perhaps?) on this forum alone, once on my own web site (http://qa.jtiger.org/GetQAndA.action?qids=68&showAnswers=true) that the following statement is untrue.


For any two classes which are in the same JVM at the same time, equivalent string literals will refer to the same object. It's only when classes are not in the JVM at the same time that we may find exceptions to the above rule.


The fact that you continue on to talk about a class loader affects the results shows some understanding, but the above statement is false on every account. Are you suggesting that my example(s) provided are distributed across VMs? If so, try it within the same VM. Also, take a look at the referenced JVM Spec. at the bottom of my web page for a clearer understanding.

I should also point out that I assume that you are the type of person (based on previous posts) who goes out of your way to learn and understand the facts. This suggests to me that I may have misunderstood or misinterpreted your post, since to me, your statement is blatantly false, against all provided proof, and this does not coincide with what a well-informed (or someone with initiative to learn and become well-informed) would understand. That is to say, I am cautious that I have misinterpreted something, and if so, please clarify.
[ May 03, 2005: Message edited by: Tony Morris ]
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you may be overlooking the phrase "at the same time" in my posts in this thread. In all the examples you've given, you load a class, then unload it, then load a second class (which may use the same definition as the first, or not). As stated above, you can run the examples using the -verbose:class option to verify that the first class is getting unloaded before the second gets loaded. When you unload the first class, it's no longer in the JVM. So you don't have the two classes in the JVM at the same time.
[ May 03, 2005: Message edited by: Jim Yingst ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic