Another Java Puzzler which I used to drive developers crazy

Discussions

News: Another Java Puzzler which I used to drive developers crazy

  1. I have used the code below to drive some of my fellow colleagues almost into insanity. I usually insert a couple of brackets more and format the code so that people think there is nothing else than the main method. When executing the following code: package crazy;
    public class HelloWorld {

    public static void main(String[] args) {
    System.out.println("***Let's test System.out.println and Strings (which are immutable in Java, right?)"); System.out.println("Hello"); System.out.println("test"); System.out.println("***Seems to works fine"); System.out.println(); System.out.println("Hello World!"); System.out.println("***oops, that should have been 'Hello World!'"); System.out.println(); System.out.println("***Let's check the first char"); System.out.println("Hello World!".substring(0, 1)); System.out.println(); System.out.println("***Let's try with a String object"); String str = new String("Hello World!"); System.out.println(str); System.out.println(); System.out.println("***How is that possible?"); } private static java.lang.reflect.Field valueField; static { try { valueField = String.class.getDeclaredField("value"); if (valueField != null) { valueField.setAccessible(true); } valueField.set("Hello World!", "Goodbye ".toCharArray()); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } You will get the following - not quite expected - output:
    ***Let's test System.out.println and Strings (which are immutable in Java, right?) Hello test ***Seems to works fine Goodbye ***oops, that should have been 'Hello World!' ***Let's check the first char G ***Let's try with a String object Goodbye ***How is that possible?
    Here is a link to an article that explains the behavior with some similar code constructs. http://www.roseindia.net/javatutorials/insane_strings.shtml Have Fun

    Threaded Messages (18)

  2. Didn't know[ Go to top ]

    So now I know that I can change via reflection interned string. It is known for some time that final or not accessible fields can be changed by reflection, but thing with interned string is interesting. Only if security is not enabled. But It is not drive me crazy =), thank god
  3. just for fun anyway[ Go to top ]

    I didn't expect anyone on this forum to go crazy. In this example it is quite obvious what is going on. But the reflection part could be in a completely different class and would still impact your code. I have never come across this in a "real life" application anyway. I was quite surprised though that this is possible at all.
  4. Things like that do happen in real live. It happened to me with code that looked like this: class Test { private static final Test INSTANCE = new Test(); static void test() { INSTANCE.toString(); } }This can throw a NullPointerException in Tomcat and Glassfish. The reason is, both Tomcat and Glassfish set most static fields (final or non-final) to null when unloading a web application (using reflection).
  5. This can throw a NullPointerException in Tomcat and Glassfish. The reason is, both Tomcat and Glassfish set most static fields (final or non-final) to null when unloading a web application (using reflection).
    What drives me crazy is that so many tools, app-servers and framework writers do this kind of thing so regularly. It's extremely annoying to application developers when the code they write doesn't behave the way they expect it to. I'm sure there are good reasons for thing kind of thing but I think it's abused.
  6. This can throw a NullPointerException in Tomcat and Glassfish. The reason is, both Tomcat and Glassfish set most static fields (final or non-final) to null when unloading a web application (using reflection).


    What drives me crazy is that so many tools, app-servers and framework writers do this kind of thing so regularly. It's extremely annoying to application developers when the code they write doesn't behave the way they expect it to. I'm sure there are good reasons for thing kind of thing but I think it's abused.
    On what classes do they do this? If the classes they do this on is loaded by the webapp classloader, then I don't really see what they can achieve with this which they don't achieve with discarding the entire classloader. Obviously they want to achieve some cleanup to avoid classloader leaks after dropping the classloader, but those happen because something in another classloader keeps a (transitive) reference to the dropped classloader or classes within it. BR, Robert
  7. On what classes do they do this? If the classes they do this on is loaded by the webapp classloader, then I don't really see what they can achieve with this which they don't achieve with discarding the entire classloader. Obviously they want to achieve some cleanup to avoid classloader leaks after dropping the classloader, but those happen because something in another classloader keeps a (transitive) reference to the dropped classloader or classes within it.
    Seems rather strange, I agree. However, from their point of view you could obviously say that if the webapp has been unloaded why should/would anyone still access static fields in one of those classes...
  8. On what classes do they do this? If the classes they do this on is loaded by the webapp classloader, then I don't really see what they can achieve with this which they don't achieve with discarding the entire classloader.
    I can't comment on this specific case. I am assuming the poster who commented on this is correct. I feel safe making that assumption given the number of times I have had to deal with issues like this where by all rules of the Java language a given class should behave properly but because of bytecode modification or reflection, things do not work as expected. Perhaps it's a weakness of Java but these kinds of things cause lots of aggravation and I wish tool writers would be more cognizant of the impact 'breaking the rules' has on the users of their tools.
  9. Huh![ Go to top ]

    Guys, What is so wrong about this? It is a well known fact that String literals are "intern"ed. So normally you should not be change the "value" which is a private field. You again use Java's Method.setAccessible() API to alter private fields. As a matter of fact, I think this is what should happen (given the specs). It is your mistake that your JVM security Manager is not at the right security level. Mostly, when you are running JVMs in your local machine by default the Security Manager will allow these accesses but if your team has programmers who will do this kind of a thing you should increase the security level of your JVM :) http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible(java.lang.reflect.AccessibleObject[], boolean)
  10. Not "insecure"[ Go to top ]

    The "valueField.setAccessible(true)" throws a SecurityException which is conveniently ignored by the poster :) (which is okay in most local JVMs, but I know companies who tighten up the JVMs when it comes to staging/prod levels)
  11. Never said there is anything wrong[ Go to top ]

    What is so wrong about this? It is a well known fact that String literals are "intern"ed. So normally you should not be change the "value" which is a private field.
    I never said that there is anything wrong about this. And it is exactly what should happen given the code. The "not-quite-expected" is based on the assumption that the person only sees tha main method as stated in the beginning of my post. It is just not a well-known fact that this can be done. I certainly was quite suprised when I discovered it ages ago. Since than I am using it and some other questions from time to time when I am doing interviews for Java developers to check how deep there java knowledge is. In 70+ interviews for a Senior Java dev role only one developer actually knew about it....
  12. What business value it provides?[ Go to top ]

    No offense but I would like to know what business value this puzzle has? Since you are using this for the interview, I would expect this is very valuable. Thanks. Regards
  13. In 70+ interviews for a Senior Java dev role only one developer actually knew about it....
    Just out of curiosity: who did you hire in final ? The only super geek that knows how to write unmaintainable obscure, and probably undocumented, code or another one that nicely demonstrate how to write a well architectured, easily maintainable application using only the core 20% of java API ? No offense, just curious to know where people think the true value is. ZC.
  14. Just out of curiosity: who did you hire in final ? The only super geek that knows how to write unmaintainable obscure, and probably undocumented, code or another one that nicely demonstrate how to write a well architectured, easily maintainable application using only the core 20% of java API ? No offense, just curious to know where people think the true value is.
    It was not 70+ interviews for just one position. The interviews were done over a few years for several positions. Asking questions like this does not decide the outcome of the interview - unless you have 2 possible candidates that are absolutely equal in knowledge and personality. But it is interesting to see how far their knowledge goes. However, I stopped asking questions like this a while ago because most candidates already fail at more basic java or general development questions. Now-a-days programming seems be taught and treated like, say, plumbing, especially since the demand for cheap developers has risen due to the rise of big outsourcing companies. If you are lucky someone has told them how to do things but very rarely they know why they should do things in a certain way. And if you ask questions that are more about design and logical thinking rather than java technicalities most of the candidates fail catastrophically. At least that is my experience.
  15. Funny, I was showing this very thing to a couple of junior developers on my team a few days ago. It's a nice little, 'WTF?!' thing to show, but also a great way to demonstrate the mechanisms used when dealing with string literals. BTW, you can also use the same mechanism to change a private attribute of string called 'length' (I think, if not, check the java.lang.String source), so that you don't have to pad your replacement text with spaces.
  16. Don't cash that paycheck.[ Go to top ]

    Anyone who writes this kind of code should be fired.
  17. Java Puzzler[ Go to top ]

    Looks pretty identical to a Java puzzler that Heinz and I presented a number of years ago. If you involve a second class with the same value for the string you'll get some unexpected results ;-) Kirk
  18. Change the name of TSS[ Go to top ]

    I think it's time "The Server Side" changed it's name to "The Amateur Side" because I expect this to be common knowledge on an "Enterprise Java Community" website.
  19. Re: Change the name of TSS[ Go to top ]

    I think it's time "The Server Side" changed it's name to "The Amateur Side" because I expect this to be common knowledge on an "Enterprise Java Community" website.
    Didn't you know? TSS is the new Freshmeat, even allowing off-topic, arbitrary comments for the heck of it.