<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>kirlich's blog</title>
	<atom:link href="http://kirlich.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kirlich.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Sat, 19 Sep 2009 22:26:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='kirlich.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>kirlich's blog</title>
		<link>http://kirlich.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://kirlich.wordpress.com/osd.xml" title="kirlich&#039;s blog" />
	<atom:link rel='hub' href='http://kirlich.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Where is the ball?</title>
		<link>http://kirlich.wordpress.com/2008/12/27/where-is-the-ball/</link>
		<comments>http://kirlich.wordpress.com/2008/12/27/where-is-the-ball/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 15:40:24 +0000</pubDate>
		<dc:creator>kirlich</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[string intern]]></category>

		<guid isPermaLink="false">http://kirlich.wordpress.com/?p=6</guid>
		<description><![CDATA[Recently I&#8217;ve stumbled uppon the Magic Trick In Java article, where Atlassian developer James Roper sets up a magic trick in Java for his colleagues. So as he suggested (and I suggest you the same), I first went to find my own solution to the problem, to do my own &#8220;magic&#8221;. After I came up with one, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kirlich.wordpress.com&amp;blog=4815234&amp;post=6&amp;subd=kirlich&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Recently I&#8217;ve stumbled uppon the <a href="http://blogs.atlassian.com/developer/2008/07/magic_trick_in_java.html">Magic Trick In Java</a> article, where Atlassian developer James Roper sets up a magic trick in Java for his colleagues. So as he suggested (and I suggest you the same), I first went to find my own solution to the problem, to do my own &#8220;magic&#8221;. After I came up with one, I went to check their solutions, and as much as James was surprised with the number of different solutions, I was surprised that mine was different than others (even there is one similar solution but mine goes step further, and is simpler).</p>
<p style="text-align:justify;">Instead of posting it as comment there, I&#8217;ve decided to write a post and back it up with some explanations. This is the very first post on this blog and I hope it will be worth reading.</p>
<h4>The Trick</h4>
<p style="text-align:justify;">So here is the trick:</p>
<blockquote><p>I have two hats and one ball. The ball looks like this:</p>
<p><strong>Ball.java</strong></p>
<div class="magictrickcode">
<pre><strong><span style="color:#993366;">public class</span></strong> Ball {
    <strong><span style="color:#993366;">public static final</span></strong> String <span style="color:#0000ff;"><em>UNDER_HAT</em></span> = <span style="color:#0000ff;">"NONE"</span>;
}</pre>
</div>
<p>The first hat looks like this:</p>
<p><strong>HatOne.java</strong></p>
<div class="magictrickcode">
<pre><strong><span style="color:#993366;">public class</span></strong> HatOne {
    <strong><span style="color:#993366;">public boolean</span></strong> hasBall() {
        <strong><span style="color:#993366;">return </span></strong><span style="color:#0000ff;">"ONE"</span>.equals(Ball.<span style="color:#0000ff;"><em>UNDER_HAT</em></span>);
    }
}</pre>
</div>
<p>The second hat looks like this:</p>
<p><strong>HatTwo.java</strong></p>
<div class="magictrickcode">
<pre><strong><span style="color:#993366;">public class</span></strong> HatTwo {
    <strong><span style="color:#993366;">public boolean</span></strong> hasBall() {
        return <span style="color:#0000ff;">"TWO"</span>.equals(Ball.<span style="color:#0000ff;"><em>UNDER_HAT</em></span>);
    }
}</pre>
</div>
<p>The magic trick looks like this:</p>
<p><strong>MagicTrick.java</strong></p>
<div class="magictrickcode">
<pre><span style="color:#993366;"><strong>public class</strong></span> MagicTrick {
    <span style="color:#993366;"><strong>public static void</strong></span> main(String... args) {
        HatOne hatOne = <strong><span style="color:#993366;">new </span></strong>HatOne();
        HatTwo hatTwo = <strong><span style="color:#993366;">new </span></strong>HatTwo();
        <strong><span style="color:#993366;">if</span></strong> (hatOne.hasBall() &amp;&amp; hatTwo.hasBall())
            System.<span style="color:#0000ff;"><em>out</em></span>.println(<span style="color:#0000ff;">"TADA!! The ball is under both hats!"</span>);
        <strong><span style="color:#993366;">else if</span></strong> (hatOne.hasBall())
            System.<span style="color:#0000ff;"><em>out</em></span>.println(<span style="color:#0000ff;">"The ball is under hat one."</span>);
        <strong><span style="color:#993366;">else if</span></strong> (hatTwo.hasBall())
            System.<span style="color:#0000ff;"><em>out</em></span>.println(<span style="color:#0000ff;">"The ball is under hat two."</span>);
        <strong><span style="color:#993366;">else</span></strong>
            System.<span style="color:#0000ff;"><em>out</em></span>.println(<span style="color:#0000ff;">"Better luck next time."</span>);
    }
}</pre>
</div>
<p style="text-align:justify;">For this trick, I am not allowed to modify  MagicTrick.java, HatOne.java or HatTwo.java, but I am allowed to change the implementation of Ball.java as much as I like. After making secret changes to Ball.java, I execute the magic trick:</p>
<pre>$ java MagicTrick
TADA!! The ball is under both hats!</pre>
<p>How did I do it?</p></blockquote>
<p style="text-align:justify;">First I&#8217;ll give you my &#8220;magic&#8221; solution, and then provide step by step explanation. Again I recommend you to first try to make one yourself. Maybe you&#8217;ll come up with something different than provided here, or in original <a href="http://blogs.atlassian.com/developer/2008/07/magic_trick_in_java.html">Magic Trick In Java</a> article (and its comments).</p>
<h4>Solution</h4>
<pre style="padding-left:30px;"><strong> </strong><span style="color:#ff0000;"><strong><span style="color:#993366;">public class</span></strong></span> Ball {
  <span style="color:#993366;"><strong>public static</strong></span> String <em><span style="color:#0000ff;">UNDER_HAT</span></em> = <span style="color:#0000ff;">""</span>;
  <span style="color:#993366;"><strong>static </strong></span>{
    <span style="color:#993366;"><strong>new</strong></span> HatTwo().hasBall();
    <span style="color:#993366;"><strong>try </strong></span>{
      Field countField = String.<span style="color:#993366;"><strong>class</strong></span>.getDeclaredField(<span style="color:#0000ff;">"count"</span>);
      countField.setAccessible(<strong><span style="color:#993366;">true</span></strong>);
      countField.set(<span style="color:#0000ff;">"ONE"</span>, 0);
      countField.set(<span style="color:#0000ff;">"TWO"</span>, 0);
    } <strong><span style="color:#993366;">catch </span></strong>(Exception e) {
      e.printStackTrace();
    }
  }
}</pre>
<p style="text-align:justify;">Try it yourself and check the &#8220;magic&#8221; output.</p>
<h4>Whats the magic?</h4>
<p style="text-align:justify;">So what&#8217;s going on here? How could this affect output in completely different part of code? Well here is how.</p>
<p style="text-align:justify;">Ignore the hasBall() method invocation on HatTwo instance for now. First change is that UNDER_HAT literal is not final anymore. Reason for this is that Java compiler will inline Ball.UNDER_HAT invocations in HatOne and HatTwo hasBall method, if the field is static final. Those are the only two references to Ball class, and if they are inlined at compile time, Ball class will never be loaded. Since we are allowed only to modify Ball class, we have no chance of doing anything in it at runtime, if it is not loaded at all. Note that I said &#8220;at runtime&#8221;, since you can exploit this compile time inlining to make the trick work, but I leave that to you (or you can check solution, that James had in mind while setting up this trick).</p>
<p style="text-align:justify;">Next change is that we added static initializer. By removing final we ensured that Ball class will be loaded, which gives us the possibility to do some work in static initializer. Let see what &#8220;magic&#8221; can we do. We need to make the condition:</p>
<pre style="padding-left:30px;">hatOne.hasBall() &amp;&amp; hatTwo.hasBall()</pre>
<p style="text-align:justify;">to be true, that is:</p>
<pre style="padding-left:30px;"><span style="color:#0000ff;">"ONE"</span>.equals(Ball.<span style="color:#0000ff;"><em>UNDER_HAT</em></span>);
<span style="color:#0000ff;">"TWO"</span>.equals(Ball.<span style="color:#0000ff;"><em>UNDER_HAT</em></span>);</pre>
<p style="text-align:justify;">both to be true. So we need to somehow manipulate those two strings: &#8220;ONE&#8221; and &#8220;TWO&#8221; to make them equal to Ball.UNDER_HAT. But there are two problems:</p>
<ol>
<li><span style="line-height:38px;">strings are immutable</span></li>
<li>how can we refer to them from Ball class?</li>
</ol>
<p>For (1) we can use reflection to access String private field. But first we need reference to those strings, thus we need to to solve (2) first. In order to do so we will exploit the way Java handles string literals. Here is the excerpt from <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5">Java Language Specification</a>:</p>
<blockquote><p>Each string literal is a reference <a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#9317">(§4.3)</a> to an instance (<a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#12028">§4.3.1</a>, <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44670">§12.5</a>) of class String (<a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#26992">§4.3.3</a>). String objects have a constant value. <strong>String literals</strong>-or, more generally, strings that are the values of constant expressions <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313">(§15.28)</a>-<strong>are &#8220;interned&#8221; so as to share unique instances, using the method String.intern</strong>.</p></blockquote>
<p>So, if we define string literal &#8220;ONE&#8221; in Ball class, that literal will refer to the same string instance as string literal &#8220;ONE&#8221; in class HatOne.  Analog for string literal &#8220;TWO&#8221;.  I would like to recommend you a very interesting read on this topic at Java Specialists&#8217; Newsletter: <a href="http://www.javaspecialists.eu/archive/Issue014.html">Insane Strings</a> which instantly came to my mind when I read setup for <a href="http://blogs.atlassian.com/developer/2008/07/magic_trick_in_java.html">Magic Trick In Java</a>.</p>
<h4>Mutating Strings</h4>
<p>Now that we have a way to get references to string literals &#8220;ONE&#8221; and &#8220;TWO&#8221; used in classes HatOne and HatTwo we can use reflection to modify them in order to get desired results. How should they be modified? Well, we could go by setting their underlying char array to {&#8220;N&#8221;,&#8221;O&#8221;,&#8221;N&#8221;,&#8221;E&#8221;} so that they are equal to original value of UNDER_HAT:<span style="color:#ff0000;"><strong></strong></span></p>
<pre style="padding-left:30px;">  <span style="color:#993366;"><strong>public static</strong></span> String <em><span style="color:#0000ff;">UNDER_HAT</span></em> = <span style="color:#0000ff;">"NONE"</span>;
  <span style="color:#993366;"><strong>static </strong></span>{
    <span style="color:#993366;"><strong>new</strong></span> HatTwo().hasBall();
    <span style="color:#993366;"><strong>try </strong></span>{
      Field countField = String.<span style="color:#993366;"><strong>class</strong></span>.getDeclaredField(<span style="color:#0000ff;">"value"</span>);
      countField.setAccessible(<strong><span style="color:#993366;">true</span></strong>);
      countField.set(<span style="color:#0000ff;">"ONE"</span>, <em><span style="color:#0000ff;">UNDER_HAT</span></em>.getCharArray());
      countField.set(<span style="color:#0000ff;">"TWO"</span>, <em><span style="color:#0000ff;">UNDER_HAT</span></em>.getCharArray());
    } <strong><span style="color:#993366;">catch </span></strong>(Exception e) {
      e.printStackTrace();
    }
  }</pre>
<p>but in that case we also need to set their count field to 4, since obviously two strings are not equal if they &#8220;contain&#8221; (actually &#8220;represent&#8221; would be more apropriate term) different number of characters:</p>
<pre>      Field countField = String.<span style="color:#993366;"><strong>class</strong></span>.getDeclaredField(<span style="color:#0000ff;">"count"</span>);
      countField.setAccessible(<strong><span style="color:#993366;">true</span></strong>);
      countField.set(<span style="color:#0000ff;">"ONE"</span>, <em><span style="color:#0000ff;">UNDER_HAT</span></em>.length());
      countField.set(<span style="color:#0000ff;">"TWO"</span>, <em></em><em><span style="color:#0000ff;">UNDER_HAT</span></em>.length());</pre>
<p>or we could avoid this by changing UNDER_HAT to &#8220;NON&#8221;.  Since I wanted for solution to be as simple as possible I used different approach. I&#8217;ve only changed count field value to zero because, in that case, String.equals method will not even bother with underlying char arrays. Once String.equal method determines that both strings count field is zero it will return true. So all we need to do is set the count field for strings &#8220;ONE&#8221;, &#8220;TWO&#8221;, and UNDER_HAT to zero, and they will be equal (well at least for String.equals method).  If there was additional trick constraint that forbids me to change value of UNDER_HAT literal, then I could have done this for  UNDER_HAT &#8220;NONE&#8221; string, but since trick allows me to change Ball class anyway I want I decided to manually change UNDER_HAT to empty string.</p>
<pre style="padding-left:30px;"><span style="color:#ff0000;"><span style="color:#993366;"><strong>public class</strong></span></span> Ball {
  <span style="color:#993366;"><strong>public static</strong></span> String <span style="color:#0000ff;">UNDER_HAT</span> = <span style="color:#0000ff;">""</span>;
    .
    .
    Field countField = String.<span style="color:#993366;"><strong><span style="color:#993366;">class</span></strong></span>.getDeclaredField(<span style="color:#0000ff;">"count"</span>);
    countField.setAccessible(<span style="color:#993366;"><strong>true</strong></span>);
    countField.set(<span style="color:#0000ff;">"ONE"</span>, 0);
    countField.set(<span style="color:#0000ff;">"TWO"</span>, 0);
    .
    .
}</pre>
<h4>Mystery</h4>
<p>Finally, we get to that mysterious line:</p>
<pre style="padding-left:30px;"><span style="color:#993366;"><strong>new</strong></span> HatTwo().hasBall();</pre>
<p>Without this line, MagicTrick will print:</p>
<p style="padding-left:30px;">&#8220;The ball is under hat one.&#8221;</p>
<p>How can that be? In the end we changed both string literals, &#8220;ONE&#8221; and &#8220;TWO&#8221;, in a same way. We set the value of their count field to 0, but somehow HatTwo.hassBall() returns false, as opposed to HatOne.hasBall(). In order to understand why, lets get back to string literals interning from JLS:</p>
<blockquote><p>String literals are &#8220;interned&#8221; so as to share unique instances, using the method <strong>String.intern</strong>.</p></blockquote>
<p>And String.intern method javadoc states:</p>
<blockquote><p>When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned</p></blockquote>
<p>Now, having this in mind lets examine the expression that we want to satisfy in order to print magic output:</p>
<pre style="padding-left:30px;">hatOne.hasBall() &amp;&amp; hatTwo.hasBall()</pre>
<p>So the expression:</p>
<pre style="padding-left:30px;"><span style="color:#0000ff;">"ONE"</span>.equals(Ball.<span style="color:#0000ff;"><em>UNDER_HAT</em></span>);</pre>
<p>will be executed first. Note that string literal &#8220;ONE&#8221; will be interned before Ball class is loaded (it is loaded when static reference to UNDER_HAT literal is made). Thus, when string literal &#8220;ONE&#8221; in Ball class static initializer is interned, it will refer to the same string as string literal in HatOne.hasBall() method. However, in case of expression:</p>
<pre style="padding-left:30px;"><span style="color:#0000ff;">"TWO"</span>.equals(Ball.<span style="color:#0000ff;"><span style="color:#0000ff;"><em>UNDER_HAT</em></span></span>);</pre>
<p>when string literal &#8220;TWO&#8221; is interned there is no equal string in string pool (remember that we changed count field of string literal &#8220;TWO&#8221; in Ball class to zero). So, string literal &#8220;TWO&#8221; in HatTwo.hasBall() method refers to different string than string literal &#8220;TWO&#8221; in Ball static initializer. Thus, we need to make sure that string literals from HatOne.hasBall() and HatTwo. hasBall() are interned before we use same literals in Ball static initializer. And that is where the mysterious line</p>
<pre style="padding-left:30px;"><span style="color:#993366;"><strong><span style="color:#993366;">new</span></strong></span><strong><span style="color:#993366;"> </span></strong>HatTwo().hasBall();</pre>
<p>comes from.</p>
<p>And that&#8217;s it. But to keep the game going, I have one for you: If you are allowed to modify MagicTrick class how can you break my solution?</p>
<p>Not so fast&#8230;  there are some rules. MagicTrick must follow the same logic as the original one, that is:</p>
<table style="text-align:center;" border="0">
<tbody>
<tr>
<th> HatOne.hasBall()</th>
<th> HatTwo.hasBall()</th>
<th>print</th>
</tr>
<tr>
<td style="text-align:center;">true</td>
<td style="text-align:center;">true</td>
<td>&#8220;TADA!! The ball is under both hats!&#8221;</td>
</tr>
<tr>
<td style="text-align:center;">true</td>
<td style="text-align:center;">false</td>
<td>&#8220;The ball is under hat one.&#8221;</td>
</tr>
<tr>
<td style="text-align:center;">false</td>
<td style="text-align:center;">true</td>
<td>&#8220;The ball is under hat two.&#8221;</td>
</tr>
<tr>
<td style="text-align:center;">false</td>
<td style="text-align:center;">false</td>
<td>&#8220;Better luck next time.&#8221;</td>
</tr>
</tbody>
</table>
<p>And when you break it, how would you fix my version of Ball class to print magic output again?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kirlich.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kirlich.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kirlich.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kirlich.wordpress.com&amp;blog=4815234&amp;post=6&amp;subd=kirlich&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kirlich.wordpress.com/2008/12/27/where-is-the-ball/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d4ad9ecc5437557ae39c6a04581d59dd?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kirlich</media:title>
		</media:content>
	</item>
	</channel>
</rss>
