<?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/"
	>

<channel>
	<title>Kevin&#039;s Blog &#187; Fundamental</title>
	<atom:link href="http://blog.lckymn.com/category/it/software-development/java-software-development-it/fundamental/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lckymn.com</link>
	<description>IT, Java, Ubuntu, Linux</description>
	<lastBuildDate>Thu, 12 Jan 2012 05:48:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Java Uses Call By Sharing</title>
		<link>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/</link>
		<comments>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/#comments</comments>
		<pubDate>Thu, 11 Nov 2010 17:13:38 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[call by reference]]></category>
		<category><![CDATA[call by sharing]]></category>
		<category><![CDATA[call by value]]></category>
		<category><![CDATA[caller]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[parameter]]></category>
		<category><![CDATA[Reference]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=587</guid>
		<description><![CDATA[<p>I just saw [<a href="http://www.jeviathon.com/2010/11/java-it-is-most-certainly-pass-by-value.html">Java: It is most certainly pass by value</a>]. It is very shocking that I can still often see people saying &#8220;Java is call by value&#8221;. I mean, I don&#8217;t really get why it is even controversial. I think it is clear that &#8220;Java is call by value&#8221;. Oh, actually it is more precisely &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">call by sharing</a>&#8221; (Notice that it is NOT &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference">call by reference</a>&#8220;).</p> <p>Call-by-reference means a reassigned reference to a method parameter variable <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/">Java Uses Call By Sharing</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>I just saw [<a href="http://www.jeviathon.com/2010/11/java-it-is-most-certainly-pass-by-value.html">Java: It is most certainly pass by value</a>].<br />
It is very shocking that I can still often see people saying &#8220;Java is call by value&#8221;.  I mean, I don&#8217;t really get why it is even controversial.  I think it is clear that &#8220;Java is call by value&#8221;. Oh, actually it is more precisely &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing">call by sharing</a>&#8221; (Notice that it is <b>NOT</b> &#8220;<a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference">call by reference</a>&#8220;).</p>
<p>Call-by-reference means a reassigned reference to a method parameter variable is visible by the caller of the method which means if a new object reference is assigned to the parameter variable in a method then caller will have the newly assigned one after execution of the method whereas call-by-sharing means the new reference is not visible by the caller.  Thus the old reference will still remain after calling the method. That means if a new reference is assigned to the parameter variable, it is visible just within the method thus after execution of the method, the caller will still get the old reference so the same old object.</p>
<p>The people who do not understand the difference between call-by-reference and call-by-sharing do probably not know the difference between assigning a new reference to a variable and changing the state of an object the reference of which is stored in the variable.  I guess, it is presumably caused by their ignorance about a reference of object and the actual object.  They perhaps think a variable is an object itself or that contains an object, yet the variable does not contain an object but the reference of an object. So when we use a variable to change the state of an object or use the methods in it, we are not directly having the actual object but are using the reference of the object stored in the variable in order to access the object.</p>
<p>To sum up, Java uses call-by-sharing NOT call-by-reference. The difference between call-by-reference and call-by-sharing is</p>
<p>call-by-reference: You are able to assign a new reference to a method parameter variable in a method, and it will be visible by the caller of the method so after calling the method, the caller will get the new reference (new object).</p>
<p>call-by-sharing: You are able to assign a new reference to a method parameter variable in a method, BUT it will NOT be visible by the caller of the method so after calling the method, the caller will still get the same old reference which was passed as a method parameter to the method.</p>
<p>In both evaluation strategies, you have access to the reference so are able to change the state of the object the reference of which is stored in the parameter variable if the object is mutable. Therefore it is possible to change the values of the object member variables in the method and these changes are visible by the caller but the caller still see the same old object with a different state from the state it had before calling the method.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/11/12/java-uses-call-by-sharing/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Quizzes for Primary Schoolchildren</title>
		<link>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/</link>
		<comments>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#comments</comments>
		<pubDate>Thu, 06 May 2010 12:53:40 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[primary schoolchild]]></category>
		<category><![CDATA[primary schoolchildren]]></category>
		<category><![CDATA[quiz]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=548</guid>
		<description><![CDATA[<p>Yesterday (the 5th of May) was the children&#8217;s day, which is an official holiday, in South Korea, (by the way, the day before yesterday was <a href="http://en.wikipedia.org/wiki/Star_Wars_Day" title="Star Wars Day: May the 4th be with you">Star Wars Day</a> <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) and I found that <a href="http://xeraph.com" title="Xeraph">Xeraph</a>, who is the CEO of the IT security company named <a href="http://nchovy.com/" title="NCHOVY Inc.">Nchovy</a>, as well as the creator &#038; core programmer of the OSGi based opensource security platform, <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/">Quizzes for Primary Schoolchildren</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>Yesterday (the 5th of May) was the children&#8217;s day, which is an official holiday, in South Korea, (by the way, the day before yesterday was <a href="http://en.wikipedia.org/wiki/Star_Wars_Day" title="Star Wars Day: May the 4th be with you">Star Wars Day</a> <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) and I found that <a href="http://xeraph.com" title="Xeraph">Xeraph</a>, who is the CEO of the IT security company named <a href="http://nchovy.com/" title="NCHOVY Inc.">Nchovy</a>, as well as the creator &#038; core programmer of the OSGi based opensource security platform, <a href="http://krakenapps.org/" title="Kraken">Kraken</a>, posted <a href="http://xeraph.com/5261697" title="some quiz for kids">some quiz for kids</a>. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  His blog also has <a href="http://xeraph.com/5251248" title="other quizzes for the primary schoolchildren">other quizzes for the primary schoolchildren</a>.</p>
<p>These quizzes remind me of my childhood as these kinds of quizzes are what I used to solve when I was a primary schoolchild. It was approximately 22 years ago. That time, I learned Basic (Not Visual Basic (VB), VB didn&#8217;t exist back then), Fortran, COBOL and C.  When I was learning Basic, those kinds of problems were what I solved. After I graduated from the primary school, I had not touched any computer programming languages at all for 13 years.  I started it again as I came to Sydney and entered the university to study IT. Then I realised that I could remember nothing about what I learned before. Nothing at all. That&#8217;s why my &#8216;<a href="http://blog.lckymn.com/about/" title="About me">about me</a>&#8216; page doesn&#8217;t contain any of Basic, Fortran and COBOL since I&#8217;ve completely forgot about these (it does have Visual Basic though as it&#8217;s my first programming language that I learned at the diploma school, <a href="http://www.insearch.edu.au/" title="UTS:INSEARCH">UTS:INSEARCH</a>). So my point is, doesn&#8217;t matter whether it&#8217;s a programming language or a human language, if you don&#8217;t practice or keep studying constantly, you will lose your skills and fluency of the language.</p>
<p>Anyway, I saw those quizzes and solved it for fun yet feel like I did better when I was a kid. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Back then, I didn&#8217;t even use a computer to solve it but only pen and paper.<br />
The followings are the quizzes and my answers, yet there can be much better answers of course, so why don&#8217;t you try by yourself before you check out mine.</p>
<p>This is the prompt utility class, used for the other programmes, to get input values. Notice that it doesn&#8217;t check whether the input value is number, integer more precisely, or not although it does check if the given integer is a positive one.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.simplequiz;

import java.util.Scanner;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-05-05)
 */
public final class PromptUtil
{
    private PromptUtil()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static int askForPositiveInt(String message)
    {
        final Scanner scanner = new Scanner(System.in);
        System.out.print(message);
        int number = Integer.parseInt(scanner.nextLine());

        while (0 &gt;= number)
        {
            System.out.println(&quot;Please enter a position integer.&quot;);
            System.out.print(message);
            number = Integer.parseInt(scanner.nextLine());
        }
        return number;
    }
}
</pre>
<p>&nbsp;</p>
<p>Quiz 1. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
  *
 ***
*****
 ***
  *
</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 5
</pre>
<pre class="brush: plain; title: ; notranslate">
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 7
</pre>
<pre class="brush: plain; title: ; notranslate">
      *
     ***
    *****
   *******
  *********
 ***********
*************
 ***********
  *********
   *******
    *****
     ***
      *
</pre>
<pre class="brush: plain; title: ; notranslate">
n for diamond? 9
</pre>
<pre class="brush: plain; title: ; notranslate">
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************
 ***************
  *************
   ***********
    *********
     *******
      *****
       ***
        *
</pre>
<p>* Kevin&#8217;s Answer1</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_1_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>* Kevin&#8217;s Answer2</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_2_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 2. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 4
m for inner box? 2
</pre>
<pre class="brush: plain; title: ; notranslate">
****
*  *
*  *
****
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 7
m for inner box? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
*******
*******
**   **
**   **
**   **
*******
*******
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 10
m for inner box? 4
</pre>
<pre class="brush: plain; title: ; notranslate">
**********
**********
**********
***    ***
***    ***
***    ***
***    ***
**********
**********
**********
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer box? 12
m for inner box? 6
</pre>
<pre class="brush: plain; title: ; notranslate">
************
************
************
***      ***
***      ***
***      ***
***      ***
***      ***
***      ***
************
************
************
</pre>
<p>* Kevin&#8217;s Answer</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_3_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 3. (taken from <a href="http://xeraph.com/5251248">http://xeraph.com/5251248</a>)</p>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 3
m for inner triangle? 1
</pre>
<pre class="brush: plain; title: ; notranslate">
  *
 ***
** **
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 5
m for inner triangle? 3
</pre>
<pre class="brush: plain; title: ; notranslate">
    *
   ***
  ** **
 **   **
**     **
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 8
m for inner triangle? 4
</pre>
<pre class="brush: plain; title: ; notranslate">
       *
      ***
     *****
    *******
   **** ****
  ****   ****
 ****     ****
****       ****
</pre>
<pre class="brush: plain; title: ; notranslate">
n for outer triangle? 10
m for inner triangle? 5
</pre>
<pre class="brush: plain; title: ; notranslate">
         *
        ***
       *****
      *******
     *********
    ***** *****
   *****   *****
  *****     *****
 *****       *****
*****         *****
</pre>
<p>* Kevin&#8217;s Answer</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_4_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Quiz 4. (taken from <a href="http://xeraph.com/5261697">http://xeraph.com/5261697</a>)</p>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 5
  1   2   3   4   5
 16  17  18  19   6
 15  24  25  20   7
 14  23  22  21   8
 13  12  11  10   9
</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 6
  1   2   3   4   5   6
 20  21  22  23  24   7
 19  32  33  34  25   8
 18  31  36  35  26   9
 17  30  29  28  27  10
 16  15  14  13  12  11
</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 7
  1   2   3   4   5   6   7
 24  25  26  27  28  29   8
 23  40  41  42  43  30   9
 22  39  48  49  44  31  10
 21  38  47  46  45  32  11
 20  37  36  35  34  33  12
 19  18  17  16  15  14  13
</pre>
<pre class="brush: plain; first-line: 0; title: ; notranslate">
matrix size n? 8
  1   2   3   4   5   6   7   8
 28  29  30  31  32  33  34   9
 27  48  49  50  51  52  35  10
 26  47  60  61  62  53  36  11
 25  46  59  64  63  54  37  12
 24  45  58  57  56  55  38  13
 23  44  43  42  41  40  39  14
 22  21  20  19  18  17  16  15
</pre>
<p>* Kevin&#8217;s Answer1</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_5_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
<p>* Kevin&#8217;s Answer2</p>
<p><a href='http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/#SID548_6_tgl' title='Visit blog to check out this spoiler'>[[Visit blog to check out this spoiler]]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/05/06/quizzes-for-primary-schoolchildren/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Catch-Up 01 May, 2010</title>
		<link>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/</link>
		<comments>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 19:04:16 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Web Application Development]]></category>
		<category><![CDATA[Mine]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Ubuntu Linux]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[hashCode]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[Issue Tracking System]]></category>
		<category><![CDATA[Java Reflection]]></category>
		<category><![CDATA[javac]]></category>
		<category><![CDATA[JDK7]]></category>
		<category><![CDATA[Kevin]]></category>
		<category><![CDATA[M2Eclipse]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Maven2]]></category>
		<category><![CDATA[Objects]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[Spring MVC]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=496</guid>
		<description><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);"> Some part of <a href="#3. Shadowing Declarations?">3. Bug in Java compiler?Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010. </div> <p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/">Catch-Up 01 May, 2010</a>...]</p>]]></description>
			<content:encoded><![CDATA[<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Some part of <a href="#3. Shadowing Declarations?">3. <span style="text-decoration: line-through;"> Bug in Java compiler?</span>Shadowing Declarations?</a> is <a href="#update1-2010-05-10">updated</a> <a href="#update2-2010-05-10">twice</a> on the 10th of May in 2010.
</div>
<p>I have been very busy and am still busy so haven&#8217;t written anything for quite a while on my blog except for those entries with only one or two sentences. So I&#8217;m quickly writing what I do these days and some issues I have dealt with.</p>
<h3><a name="1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)">1. Issue with the new m2eclipse (version: 0.10.0.20100209-0800)</a></h3>
<p><a href="http://www.sonatype.com/">Sonatype</a> released the new version of <a href="http://m2eclipse.sonatype.org/">m2eclipse</a> in February 2010. Since I updated with it, I had got some problem with maven build through <a href="http://hudson-ci.org/">Hudson</a>.</p>
<p>The new version of m2eclipse comes with maven3 embedded yet my server uses maven2 so does my Linux on my Desktop PC.  So it was only m2eclipse which uses maven3 (SNAPSHOT version) and I deployed some of my libraries used in one web application development project. Problem was that I deployed the dependency libraries several times with the same version number. With maven2, it&#8217;s OK as it uses time-stamp to distinguish one version from another within the same version, yet with maven3, having the same version is not allowed. Well, I am not 100% sure about this as once I solved the problem I didn&#8217;t really check the details as I didn&#8217;t have enough time. Anyway, so as shown in the following image, the project status icon once became dark rain clouds which mean really bad.<br />
<div id="attachment_501" class="wp-caption alignnone" style="width: 530px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure01.jpg" alt="Build Failure: Project status icon became dark rain clouds" title="00 build failure01" width="520" height="294" class="size-full wp-image-501" /></a><p class="wp-caption-text">Build Failure: Project status icon became dark rain clouds</p></div></p>
<p>My project build failed seven times due to the difference between maven2 and maven3 I described above, or it can be something else yet it is caused by some difference between those two versions.<br />
<div id="attachment_502" class="wp-caption alignnone" style="width: 336px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/00_build_failure02.jpg" alt="Build Failure: It failed seven times due to the difference between maven2 and maven3" title="00 build failure02" width="326" height="446" class="size-full wp-image-502" /></a><p class="wp-caption-text">Build Failure: It failed seven times due to the difference between maven2 and maven3</p></div><br />
(It happened in February. The build number in the image is 108 but it is now 305).</p>
<p>So why did I not just keep the old version of m2eclipse with maven2 embedded? Well, the old one comes with some old version of maven2 which does not support <a href="http://maven.apache.org/guides/mini/guide-encryption.html">password encryption</a> while the maven2 on both my PC and my server does support it as it is a newer version. Thus I updated with the new m2eclipse as soon as it was available yet didn&#8217;t really expect that it comes with maven3. Anyway, It&#8217;s solved by using maven2 installed on my PC when deploying project packages. The other times such as solving dependencies and building package without deployment, I can still use the embedded maven3 in the new m2eclipse without any problems.</p>
<h3><a name="2. I have been working on...">2. I have been working on&#8230;</a></h3>
<p>I founded a start-up company with my friend a few months ago, and we are currently working on a web application development for our own start-up, but it is probably too premature to announce what it is as it&#8217;s still an early stage of development.<br />
The issues listed in the following image is a part of the issues I and my colleague have solved and been working on.<br />
<div id="attachment_503" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_00.jpg" alt="I&#039;m currently working on this project." title="01 Issue Tracking 00" width="640" height="477" class="size-full wp-image-503" /></a><p class="wp-caption-text">I'm currently working on this project.</p></div></p>
<p>In addition, I have been developing my own Java libraries which can be commonly used in many other projects (and my friend has also been developing reusable JavaScript libraries). However, I did not record all the issues belong to these reusable components and recently felt that I should do it before I go any further. Otherwise, I may later forget what problems I solved and how I did as well as all the issues covered previously. So I wrote all the tickets for those libraries.<br />
<div id="attachment_504" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_01.jpg" alt="Issues of commonly used libraries built by myself" title="01 Issue Tracking 01" width="640" height="335" class="size-full wp-image-504" /></a><p class="wp-caption-text">Issues of commonly used libraries built by myself</p></div></p>
<p>I&#8217;ve also been developing &#8216;Java object to JSON&#8217; library and did the same as what I just explained (that is creating issue tickets).  There are already a number of the libraries which convert Java object into <a href="http://json.org/">JSON</a> so why would I make another?  Well, there can be several reasons but major ones are</p>
<ol>
<li>I need it to convert any <a href="http://en.wikipedia.org/wiki/POJO">POJO</a> with only <a href="http://en.wikipedia.org/wiki/Java_annotation">annotations</a> into <a href="http://json.org/">JSON</a>.</li>
<li>It has to be simple as I do not want to have any complex functions or heavy library for a simple conversion (some libraries are too heavy for such a simple task).</li>
<li>When customisation is required or bug is found in the library, I want to be able to change and fix it however I want so that I do not have to waste my time on waiting for others to solve it.</li>
<li>I want it to work in some environments where using bytecode manipulation is not an option. So if I programme one with bytecode manipulation then it works faster when it&#8217;s available whereas the other one is without it so that it can be used in those enviornments (I currently have only the latter one and will do the former one when I have time later).</li>
</ol>
<p>The following issues are what I have solved for the Java to JSON library.<br />
<div id="attachment_505" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_02.jpg" alt="Issues of my Java object to JSON library" title="01 Issue Tracking 02" width="640" height="451" class="size-full wp-image-505" /></a><p class="wp-caption-text">Issues of my Java object to JSON library</p></div></p>
<p>Finally, I have another project to help Ajax enabled web application development. From my experience, I found that it is sharing the information about the available server-side functions with the client-side developers that causes the most waste of time between the front-end development and the back-end development.  The first time one function is made or whenever the existing ones are changed, I have to write or rewrite the document explaining it and the client-side developer has to find the changed parts in the document.  It is annoying and a non-productive moment in the development so I and my colleague discussed about this issue and came up with the idea of having a library which exposes all the available server-side functions to the front-end (It can understand Spring <code>@MVC</code> controllers).  For now, it has only this, yet I will add more features to help Ajax web application development.<br />
<div id="attachment_506" class="wp-caption alignnone" style="width: 650px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/01_issueTracking_03.jpg" alt="Issues of my web method library" title="01 IssueTracking 03" width="640" height="146" class="size-full wp-image-506" /></a><p class="wp-caption-text">Issues of my web method library</p></div></p>
<p>* As I used more and more reflection to develop those libraries, I realised that Java Reflection has no method to get the names of method parameters. Well, there can be some ways for instance, using -g (generating debugging info) option when compiling or using some libraries such as <a href="http://asm.ow2.org/">ASM</a> or use <a href="http://paranamer.codehaus.org/">ParaNamer</a> (It requires an additional step when compiling to add the constants having the parameter names in the class) but not by just Java reflection.  Anyway, none of these is the solution I want, and unfortunately if I heard right, this problem will remain in JDK 7. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h3><a name ="3. Shadowing Declarations?">3. <span style="text-decoration: line-through;">Bug in Java compiler?</span> Shadowing Declarations?</a></h3>
<p>I created the Objects utility class based on <a href="http://download.java.net/jdk7/docs/api/java/util/Objects.html">http://download.java.net/jdk7/docs/api/java/util/Objects.html</a>. This will be available in JDK 7 yet I wanted to use it before JDK 7 is released so I made my own one. I can use it now, and it can easily be replaced by the one in JDK when it&#8217;s available.  <span style="text-decoration: line-through;">After I made it, I found some weird bug, I believe, in Java compiler.</span> After I used it, I had some problem and though it could be a bug in Java compiler yet <a href="#update2-2010-05-10">it looks like &#8216;shadowing declarations&#8217;.</a></p>
<p>This is the part of Objects class I coded.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.common.util;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public final class Objects
{
    private Objects()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    // other code omitted ...

    /**
     * Returns the hash code of a non-{@code null} argument and 0 for a {@code null} argument.
     *
     * @param o
     *            an object
     * @return the hash code of a non-{@code null} argument and 0 for a {@code null} argument
     * @see {@link Object#hashCode()}
     */
    public static int hashCode(final Object o)
    {
        return (null == o ? 0 : o.hashCode());
    }

    // other code omitted ...
}
</pre>
<p>The following code is a POJO in which I want to use the Objects.hashCode(Object) method.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.test.bean;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                &amp;&amp; (this.name == that.getName() ||
                        (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>So I changed this code snippet</p>
<pre class="brush: java; gutter: false; highlight: [7]; title: ; notranslate">
@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + number;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}
</pre>
<p>to this.</p>
<pre class="brush: java; gutter: false; highlight: [3,15]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import static com.lckymn.kevin.common.util.Objects.*;

public class SomePojo
{
    // ...

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + hashCode(name);
        return result;
    }
}
</pre>
<p>I used static import and hashCode(Object) method in the Objects class. Although, nothing&#8217;s wrong in the code, my Eclipse complains that there is a compile-time error. The following image shows that.<br />
<div id="attachment_511" class="wp-caption alignnone" style="width: 929px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_01.jpg" alt="Objects.hashCode(Object) with static import does not work." title="02 Objects.hashCode 01" width="919" height="837" class="size-full wp-image-511" /></a><p class="wp-caption-text">Objects.hashCode(Object) with static import does not work.</p></div></p>
<p>Yet the same code with no-static import but using class name as the qualifier to use <code>hashCode(Object)</code> method works perfectly. The following code has <code>Objects.hashCode(name)</code> and no compile-time error.</p>
<pre class="brush: java; highlight: [36]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-04-30)
 */
public class SomePojo
{
    private final int number;
    private final String name;

    public SomePojo(int number, String name)
    {
        this.number = number;
        this.name = name;
    }

    public int getNumber()
    {
        return number;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + number;
        result = prime * result + Objects.hashCode(name);
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (null == obj)
        {
            return false;
        }
        if (!(obj instanceof SomePojo))
        {
            return false;
        }
        final SomePojo that = (SomePojo) obj;
        return (this.number == that.getNumber())
                &amp;&amp; (this.name == that.getName() || (null != this.name &amp;&amp; this.name.equals(that.getName())));
    }
}
</pre>
<p>The following image shows it has no error in the part where <code>Objects.hashCode(Object)</code> is used..<br />
<div id="attachment_508" class="wp-caption alignnone" style="width: 515px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/02_objects_hashcode_02.jpg" alt="Using Class as qualifier to use hashCode works." title="02 Objects.hashCode 02" width="505" height="622" class="size-full wp-image-508" /></a><p class="wp-caption-text">Using Class as qualifier to use hashCode works.</p></div></p>
<p>I wondered if it&#8217;s a bug in the Eclipse or a bug in the Java compiler. So I opened the terminal and tested it.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ javac -version
javac 1.6.0_15

$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>As it shows, the compiler does totally not understand that the hashCode(Object) method from the Objects class is available and valid.</p>
<p>Is a bug only in the SUN JDK in the Ubuntu Linux repository? So I tried with OpenJDK 6 as well.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ /usr/lib/jvm/java-6-openjdk/bin/javac -version
javac 1.6.0_0

$ /usr/lib/jvm/java-6-openjdk/bin/javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>The same result&#8230;</p>
<p>OK, it might be a bug in that particular version. Fortunately, the most recent version of SUN JDK 6 was released yesterday. It was officially released before (the 15th of April, 2010) yet the version managed by Ubuntu was not available before yesterday. So I installed it and tested it again with the Java compiler in the new JDK6.<br />
<div id="attachment_509" class="wp-caption alignnone" style="width: 622px"><a href="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2010/05/03_update_jdk.jpg" alt="New version of SUN JDK6 is available in the Ubuntu repository" title="03 Update JDK" width="612" height="640" class="size-full wp-image-509" /></a><p class="wp-caption-text">New version of SUN JDK6 is available in the Ubuntu repository</p></div></p>
<p>It still has the same problem.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
$ javac -version
javac 1.6.0_20

$ javac com/lckymn/kevin/test/bean/SomePojo.java
com/lckymn/kevin/test/bean/SomePojo.java:39: cannot find symbol
symbol  : method hashCode(java.lang.String)
location: class com.lckymn.kevin.test.bean.SomePojo
        result = prime * result + hashCode(name);
                                  ^
com/lckymn/kevin/test/bean/SomePojo.java:39: operator + cannot be applied to int,hashCode
        result = prime * result + hashCode(name);
                       ^
com/lckymn/kevin/test/bean/SomePojo.java:39: incompatible types
found   : &lt;nulltype&gt;
required: int
        result = prime * result + hashCode(name);
                                ^
3 errors
</pre>
<p>I probably need to test with the Java compiler in the JDK6 for Windows but I have no stomach for that now nor do I have time to do that.</p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update1-2010-05-10">* Update1 (2010-05-10)</a><br />
I also tested it with the Java compiler in the JDK 6 (1.6.0_16) for Windows and got the same result. <span style="text-decoration: line-through">It seem like static import cannot handle method overloading. I didn&#8217;t have time to research to find the details but based on my testing, method overloading cannot be used with static import.<br />
If so then there should be a good reason for that, and the only one I can think of right now is that it might have something to do with varargs.</span><br />
Take a look at the following code.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static void test(Object... object)
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,14,17]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println(&quot;Test.test()&quot;);
    }

    public void callTest()
    {
        test();            // no error here.

        Object object = new Object();
        test(object);    // compile-time error
    }
}
</pre>
<p><span style="text-decoration: line-through">Since a method with varargs can take no argument when it&#8217;s called, Test.test() and SomeHelper.test(Object&#8230; object) can be indistinguishable with static import. This is, I think, probably one of the reasons why method overloading is not allowed with static import. Nevertheless, it is still very weird as calling test() does not cause any compile-time error while test(object) does.</span><br />
So the following code has no compile-time error and displays <code>Test.test()</code>.</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test()
    {
        System.out.println(&quot;Test.test()&quot;);
    }

    public void callTest()
    {
        test();    // static import of SomeHelper.test has no effect here.
    }

    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}
</pre>
<p>It displays <code>Test.test()</code>.</p>
<p>What if the helper class has test() method with no arguments and the Test class has test() method with varargs then call <code>test()</code>? The same result! It still calls Test&#8217;s test() method with varargs (<code>Test.test(Object... object)</code>).</p>
<pre class="brush: java; highlight: [10]; title: ; notranslate">
package com.lckymn.kevin.common.util;

public final class SomeHelper
{
    private SomeHelper()
    {
        throw new IllegalStateException(getClass().getName() + &quot; cannot be instantiated.&quot;);
    }

    public static void test()
    {
        System.out.println(&quot;SomeHelper.test()&quot;);
    }
}
</pre>
<pre class="brush: java; highlight: [3,7]; title: ; notranslate">
package com.lckymn.kevin.test;

import static com.lckymn.kevin.common.util.SomeHelper.test;

public class Test
{
    public void test(Object... object)
    {
        System.out.println(&quot;Test.test(Object...object)&quot;);
    }

    public void callTest()
    {
        test(); // it calls the Test.test(Object... object) method NOT SomeHelper.test().
    }

    public static void main(String[] args)
    {
        new Test().callTest();
        System.exit(0);
    }
}
</pre>
<p>It displays <code>Test.test(Object...object)</code>
</div>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
<a name="update2-2010-05-10">Update2 (2010-05-10)</a><br />
It is more likely to be <a href="http://java.sun.com/docs/books/jls/third_edition/html/names.html#34133">&#8216;Shadowing Declarations&#8217;</a>. Although, I couldn&#8217;t find the exactly matching case from the <a href="http://java.sun.com/docs/books/jls/">JLS</a> yet, it makes more sense if the method imported by static-import is shadowed.
</div>
<h3><a name="4. Using Objects">4. Using Objects</a></h3>
<p>By the way, the Objects class is simple but very useful.<br />
with it, the highlighted parts of the following code can</p>
<pre class="brush: java; highlight: [53,54,55,56,57,72,73,74,75]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
        result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return (this.bankName == that.getBankName() ||
               (null != this.bankName &amp;&amp; this.bankName.equals(that.getBankName())))
                &amp;&amp; (this.bsbNumber == that.getBsbNumber() ||
                   (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
    }
}
</pre>
<p>become like this</p>
<pre class="brush: java; highlight: [55,70,71]; title: ; notranslate">
package com.lckymn.kevin.test.bean;

import com.lckymn.kevin.common.util.Objects;

public class Bank
{
    private Long id;
    private String bankName;
    private String bsbNumber;
    private String address;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getBankName()
    {
        return bankName;
    }

    public void setBankName(String bankName)
    {
        this.bankName = bankName;
    }

    public String getBsbNumber()
    {
        return bsbNumber;
    }

    public void setBsbNumber(String bsbNumber)
    {
        this.bsbNumber = bsbNumber;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(bankName, bankName);
    }

    @Override
    public boolean equals(Object bank)
    {
        if (this == bank)
        {
            return true;
        }
        if (!(bank instanceof Bank))
        {
            return false;
        }
        final Bank that = (Bank) bank;
        return Objects.equals(this.bankName, that.getBankName())
               &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
    }
}
</pre>
<p>So these five lines in the hashCode method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
final int prime = 31;
int result = 1;
result = prime * result + ((bankName == null) ? 0 : bankName.hashCode());
result = prime * result + ((bsbNumber == null) ? 0 : bsbNumber.hashCode());
return result;
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.hash(bankName, bankName);
</pre>
<p>and these four lines in the equals method</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return (this.bankName == that.getBankName() ||
       (null != this.bankName &amp;&amp; this.bankName.equals(that.getBankName())))
        &amp;&amp; (this.bsbNumber == that.getBsbNumber() ||
           (null != this.bsbNumber &amp;&amp; this.bsbNumber.equals(that.getBsbNumber())));
</pre>
<p>become</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
return Objects.equals(this.bankName, that.getBankName())
       &amp;&amp; Objects.equals(this.bsbNumber, that.getBsbNumber());
</pre>
<p>Although one might say that I can use <a href="http://projectlombok.org/">Lombok</a> instead, I prefer to see what is going on in my code. Those hashCode and equals methods are not additional info of the class. It tells what makes instances of the class equal thus I prefer to have it in there to see and want to freely change it whenever and however I want. Well, in other words, just a matter of personal preference. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
That&#8217;s it.<br />
I perhaps have more to say yet am getting tired (4:55 AM :O). So I&#8217;m calling it a night. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2010/05/01/catch-up-2010-05-01/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Re: Java Challenge: Dropping Balloons in Java</title>
		<link>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/</link>
		<comments>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 10:54:21 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[balloon]]></category>
		<category><![CDATA[building]]></category>
		<category><![CDATA[egg]]></category>
		<category><![CDATA[floor]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[quiz]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=455</guid>
		<description><![CDATA[<p>About a few days ago, I read <a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">this post, Java Challenge: Dropping Balloons in Java</a> having an interesting question.</p> <p>It&#8217;s a question to find an algorithm that gives the highest floor where you can drop a water balloon without breaking it at a 100 story building. You have only two balloons. I had actually seen this problem before and solved it already. It was not balloons but eggs. The solution is simple. Since if you miss two chances <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/">Re: Java Challenge: Dropping Balloons in Java</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>About a few days ago, I read <a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">this post, Java Challenge: Dropping Balloons in Java</a> having an interesting question.</p>
<p>It&#8217;s a question to find an algorithm that gives <span style="font-weight: bolder;">the highest floor where you can drop a water balloon without breaking it at a 100 story building</span>.  You have <span style="font-weight: bolder;">only two balloons</span>.  I had actually seen this problem before and solved it already.  It was not balloons but eggs.  The solution is simple. Since if you miss two chances then have no balloons available, you need to try from the lowest safe level which means throw it from the first floor then if it does not pop, pick it up and go up to the level 2 and repeat it until the balloon pops.  When you get the level from which the balloon bursts after dropping it, one level below this level is the highest safe level. (e.g. If the balloon first breaks on the 20th floor, the highest safe floor is the 19th).</p>
<p>It&#8217;s easy isn&#8217;t it? Yet the post above has one more condition to make it a little bit more difficult which is that <span style="font-weight: bolder;">you can try only 15 times</span>. This means if I try the solution I&#8217;ve just described, I can test up to only the 15th floor. If the breaking point is the 40th floor or even the 16th floor, I&#8217;ll never know it.  When I first saw it, I tried to solve it for about five minutes yet couldn&#8217;t solve it.  That time, I was too busy to think about it further thus couldn&#8217;t be bothered to do it.  So I saved the URI of the post and forgot about it.  Last night, no actually today morning, at approximately 6 am, I went to bed (yeah, am I a vampire or what? <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).  Although I didn&#8217;t even try to think about the problem yet all of sudden I came up with the answer of that question.  It was just like the &#8216;<a href="http://en.wikipedia.org/wiki/Eureka_(word)" target="_blank">Eureka</a>&#8216; story of <a href="http://en.wikipedia.org/wiki/Archimedes" target="_blank">Archimedes</a>.  Just like he figured out how to assess the purity of a golden crown when he stepped into a bath.  OK, stop flattering myself <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  I figured it out as the question was easy to solve.</p>
<p>Well, an important point here is that I in fact often find solutions to some difficult problems when I am not struggling to solve it yet am doing something irrelevant to the problem such as working out at the gym, washing dishes after a meal, lying on the bed to sleep or even when I&#8217;m dreaming. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  So if you can&#8217;t solve some problem then why don&#8217;t you try something else rather than thinking about the solution all the time.  Your brain may need to relax or when you use the other parts of the brain by doing something else, it might figure it out.</p>
<p>Anyway, here is what my brain told me that time.</p>
<p>Since I have only two balloons, if I choose a wrong floor twice, I lose all the chances.  Then what if I check every second level as I have two balloons. So first, if I drop it from the second level and it breaks then I still have one more balloon so that I can try it from the first level and I can find if the highest safe level is the first or there is no safe level. If the balloon is fine after dropping it from the second level then I can pick it up and try it from the fourth level and so on. However, with this solution I can check at most until the 30th floor which is better than checking up to the 15th one but still not enough to check the 100 stories.  This means that it is not sufficient to check ever second level in order to find the floor and I should focus on not only the two balloons but also the 15 times of attempts.  From the first solution above, I know that I can definitely have 15 times if I try from the lowest safe floor and move up.  It means if the number of floors between the already known highest safe level and the breaking point level found is the same as or fewer than the number of attempts I still have, I can find the very first level where the balloon bursts after dropping it (In order to reduce the number of attempts, of course, I have to make it the same as the number of attempts still left).  Therefore I can tell the highest safe level that is one level below the breaking point level found.  This should be easier to understand with an example.</p>
<p>Let&#8217;s assume that the breaking point is the 17th floor.</p>
<p>At first, I have 15 tries to drop one balloon from the 15th floor.<br />
The balloon&#8217;s still OK and I now have 14 times of attempts. Since the number of attempts I still have is 14 time, I can&#8217;t try it from the 30th floor which is 15 + 15 yet I have to try it from the 29th floor (15 + 14). Because the breaking point is the 17th floor, the balloon breaks on the 29th floor.  Now I have 13 times of attempts and 1 balloon left.  From the first try, I know the 14th floor is fine so I try from the next floor that is floor 15 to see if floor 14 is the highest safe floor.  It turns out the 15th one is fine and now I have 12 times left.  16th -> OK / 11 times left, 17th -> it breaks! / 10 times left<br />
So I can tell the 16th floor is the highest safe floor and I didn&#8217;t even use all the 15 times of attempts.</p>
<p><a href="http://united-coders.com/nico-heid/java-challenge-dropping-balloons-in-java" target="_blank">The post that has the question</a> specifies the floor starts from 0 so let&#8217;s make the first floor is floor 0 and see have it works. I made a table which shows the number of attempts required to find the highest safe floor.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
====================================================
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15   tries
====================================================
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14	- 1
15 16 17 18 19 20 21 22 23 24 25 26 27 28		- 2
29 30 31 32 33 34 35 36 37 38 39 40 41			- 3
42 43 44 45 46 47 48 49 50 51 52 53				- 4
54 55 56 57 58 59 60 61 62 63 64				- 5
65 66 67 68 69 70 71 72 73 74					- 6
75 76 77 78 79 80 81 82 83						- 7
84 85 86 87 88 89 90 91							- 8
92 93 94 95 96 97 98							- 9
99												- 10
</pre>
<p>So if the highest safe floor is 73. The first balloon breaks on the floor 74 after 6 times of attempts. After that try from the floor 65 (attempts: 7) through 66 (8), 67 (9), 68 (10), 69 (11), 70 (12), 71 (13), 72 (14) to 73 (15) and the second balloon hasn&#8217;t broken so I can tell the highest safe floor is the floor 73.</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
====================================================
 1  2  3  4  5  6  7  8[ 9]10 11 12 13 14 15
====================================================
65 66 67 68 69 70 71 72[73]74					-[6]
</pre>
<p>attempts: 6 times to get the floor 74 + 9 times to check until the floor 73 = 15 times.</p>
<p>Once I found the solution writing code is a piece of cake.<br />
I roughly wrote the main part of the code like this.</p>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private static final int MAX_ATTEMPTS = 15;

private int theFloor = (int) (Math.random() * 100);
private int numberOfBalloons = 2;
private int numberOfAttempts = 0;

// ...

public void findHighestSafeFloor()
{
	int previousFloorIndex = -1;
	int floorIndex = MAX_ATTEMPTS - 1;
	int highestSafeFloor = 0;

	while (MAX_ATTEMPTS &gt; numberOfAttempts)
	{
		numberOfAttempts++;
		if (theFloor &lt;= floorIndex)
		{
			numberOfBalloons--;
			highestSafeFloor = findHighestSafeFloor(previousFloorIndex + 1, floorIndex);
			break;
		}
		previousFloorIndex = floorIndex;
		floorIndex += (MAX_ATTEMPTS - numberOfAttempts);
		if (99 &lt; floorIndex)
		{
			floorIndex = 99;
		}
	}

	/* print the result. */
}

private int findHighestSafeFloor(final int start, final int end)
{
	for (int i = start; i &lt; end; i++)
	{
		numberOfAttempts++;
		if (theFloor == i)
		{
			numberOfBalloons--;
			return (i - 1);
		}
	}
	return (end - 1);
}
</pre>
<p>I am sure that the <code>findHighestSafeFloor()</code> method above works but I decided to make it recursion. Why? No special reasons. I just like recursion <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  as I haven&#8217;t used it for approximately four years since I last programmed in a functional programming language like <a href="http://haskell.org/" target="_blank">Haskell</a> in my math class thus miss it. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Although the code can be very simple as the following code with recursion, it has to increase the number of attempts and to decrease the number of balloons left, so it would be a bit more verbose as the second code.</p>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private int findHighestSafeFloor(final int start, final int end)
{
	return (start &lt; end ? (theFloor == start ? (start - 1) : findHighestSafeFloor((start + 1), end)) : (end - 1));
}
</pre>
<pre class="brush: java; gutter: false; tab-size: 4; title: ; toolbar: true; notranslate">
private int findHighestSafeFloor(final int start, final int end)
{
	if (start &lt; end)
	{
		numberOfAttempts++;
		if (theFloor == start)
		{
			numberOfBalloons--;
			return (start - 1);
		}
		else
		{
			return findHighestSafeFloor((start + 1), end);
		}
	}
	else
	{
		return (end - 1);
	}
}
</pre>
<p>Now it&#8217;s time to code the complete programme and test it.  Well, since it&#8217;s a very small programme, I didn&#8217;t do object-oriented programming. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: java; tab-size: 4; title: ; toolbar: true; notranslate">
package com.lckymn.kevin.findingfloor;

public final class HighestSafeFloorFinder
{
	private static final int TOP_LEVEL = 99;
	private static final int MAX_ATTEMPTS = 15;

	private int theBreakingPointFloor;
	private int numberOfBalloons;
	private int numberOfAttemptsMade;

	public void init(final int theBreakingPointFloor)
	{
		this.theBreakingPointFloor = theBreakingPointFloor;
		System.out.println(&quot;The breaking point: &quot; + theBreakingPointFloor);
		numberOfBalloons = 2;
		numberOfAttemptsMade = 0;
	}

	public void findHighestSafeFloor()
	{
		int previousFloorIndex = -1;
		int floorIndex = MAX_ATTEMPTS - 1;
		int highestSafeFloor = 0;

		while (MAX_ATTEMPTS &gt; numberOfAttemptsMade)
		{
			dropBalloon();
			if (theBreakingPointFloor &lt;= floorIndex)
			{
				breakBalloon();
				highestSafeFloor = findHighestSafeFloor(previousFloorIndex + 1, floorIndex);
				break;
			}
			previousFloorIndex = floorIndex;
			floorIndex += (MAX_ATTEMPTS - numberOfAttemptsMade);
			if (TOP_LEVEL &lt; floorIndex)
			{
				floorIndex = TOP_LEVEL;
			}
		}

		if (0 &gt; highestSafeFloor)
		{
			System.out.println(&quot;There is no floor that you can drop a balloon without breaking it. Even the first floor (floor 0) is not safe.&quot;);
		}
		else
		{
			System.out.println(&quot;The highest safe floor: &quot; + highestSafeFloor);
		}

		System.out.println(&quot;The number of attempts made: &quot; + numberOfAttemptsMade);
	}

	private int findHighestSafeFloor(final int start, final int end)
	{
		if (start &lt; end)
		{
			dropBalloon();
			if (theBreakingPointFloor == start)
			{
				breakBalloon();
				return (start - 1);
			}
			else
			{
				return findHighestSafeFloor((start + 1), end);
			}
		}
		else
		{
			return (end - 1);
		}
	}

	private void dropBalloon()
	{
		if (MAX_ATTEMPTS == numberOfAttemptsMade)
		{
			throw new IllegalStateException(&quot;You've already tried 15 times.&quot;);
		}
		numberOfAttemptsMade++;
	}

	private void breakBalloon()
	{
		if (0 == numberOfBalloons)
		{
			throw new IllegalStateException(&quot;You've already broken all the balloons available.&quot;);
		}
		numberOfBalloons--;
	}

	public static void main(String[] args)
	{
		HighestSafeFloorFinder highestSafeFloorFinder = new HighestSafeFloorFinder();
		for (int i = 0; i &lt; 100; i++)
		{
			System.out.println(&quot;[Test Number: &quot; + i + &quot;]&quot;);
			highestSafeFloorFinder.init(i);
			highestSafeFloorFinder.findHighestSafeFloor();
			System.out.println(&quot;=======================================&quot;);
		}
		System.exit(0);
	}
}
</pre>
<p>Well, the code looks a bit ugly but in my defence, I&#8217;d just like to see the result and am busy so had no stomach for making it pretty. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  (Oh! such a poor excuse / but really busy <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> )</p>
<p>The <code>dropBalloon()</code> and the <code>breakBalloon()</code> are added to increase the number of attempts made and to decrease the number of balloons left respectively.  The <code>dropBalloon()</code> method also checks if the number of attempts already made is 15 and it tries to make another one than throws an exception telling that all the chances have been used.  Similarly the <code>breakBalloon()</code> method checks if all the available balloons have broken if so, it also throws an exception saying there are no available balloons left.  Thus I can see if the programme can find the highest safe floor with 15 times or fewer times of attempts and only two water balloons.  If it cannot, it immediately throws an exception and stop the programme so I can see my programme fails to prove my algorithm.</p>
<p>The <code>init()</code> method is to initialise all the variables so that I can test it many times. It checks all the floors from the first one (floor 0) to the last one (floor 99) so if the programme works fine without any exception thrown then it might prove my answer is correct.</p>
<p>Let&#8217;s check out the result!</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
[Test Number: 0]
The breaking point: 0
There is no floor that you can drop a balloon without breaking it. Even the first floor (floor 0) is not safe.
The number of attempts made: 2
=======================================
[Test Number: 1]
The breaking point: 1
The highest safe floor: 0
The number of attempts made: 3
=======================================
[Test Number: 2]
The breaking point: 2
The highest safe floor: 1
The number of attempts made: 4
=======================================
[Test Number: 3]
The breaking point: 3
The highest safe floor: 2
The number of attempts made: 5
=======================================
[Test Number: 4]
The breaking point: 4
The highest safe floor: 3
The number of attempts made: 6
=======================================
[Test Number: 5]
The breaking point: 5
The highest safe floor: 4
The number of attempts made: 7
=======================================
[Test Number: 6]
The breaking point: 6
The highest safe floor: 5
The number of attempts made: 8
=======================================
[Test Number: 7]
The breaking point: 7
The highest safe floor: 6
The number of attempts made: 9
=======================================
[Test Number: 8]
The breaking point: 8
The highest safe floor: 7
The number of attempts made: 10
=======================================
[Test Number: 9]
The breaking point: 9
The highest safe floor: 8
The number of attempts made: 11
=======================================
[Test Number: 10]
The breaking point: 10
The highest safe floor: 9
The number of attempts made: 12
=======================================
[Test Number: 11]
The breaking point: 11
The highest safe floor: 10
The number of attempts made: 13
=======================================
[Test Number: 12]
The breaking point: 12
The highest safe floor: 11
The number of attempts made: 14
=======================================
[Test Number: 13]
The breaking point: 13
The highest safe floor: 12
The number of attempts made: 15
=======================================
[Test Number: 14]
The breaking point: 14
The highest safe floor: 13
The number of attempts made: 15
=======================================
[Test Number: 15]
The breaking point: 15
The highest safe floor: 14
The number of attempts made: 3
=======================================
[Test Number: 16]
The breaking point: 16
The highest safe floor: 15
The number of attempts made: 4
=======================================
[Test Number: 17]
The breaking point: 17
The highest safe floor: 16
The number of attempts made: 5
=======================================
[Test Number: 18]
The breaking point: 18
The highest safe floor: 17
The number of attempts made: 6
=======================================
[Test Number: 19]
The breaking point: 19
The highest safe floor: 18
The number of attempts made: 7
=======================================
[Test Number: 20]
The breaking point: 20
The highest safe floor: 19
The number of attempts made: 8
=======================================
[Test Number: 21]
The breaking point: 21
The highest safe floor: 20
The number of attempts made: 9
=======================================
[Test Number: 22]
The breaking point: 22
The highest safe floor: 21
The number of attempts made: 10
=======================================
[Test Number: 23]
The breaking point: 23
The highest safe floor: 22
The number of attempts made: 11
=======================================
[Test Number: 24]
The breaking point: 24
The highest safe floor: 23
The number of attempts made: 12
=======================================
[Test Number: 25]
The breaking point: 25
The highest safe floor: 24
The number of attempts made: 13
=======================================
[Test Number: 26]
The breaking point: 26
The highest safe floor: 25
The number of attempts made: 14
=======================================
[Test Number: 27]
The breaking point: 27
The highest safe floor: 26
The number of attempts made: 15
=======================================
[Test Number: 28]
The breaking point: 28
The highest safe floor: 27
The number of attempts made: 15
=======================================
[Test Number: 29]
The breaking point: 29
The highest safe floor: 28
The number of attempts made: 4
=======================================
[Test Number: 30]
The breaking point: 30
The highest safe floor: 29
The number of attempts made: 5
=======================================
[Test Number: 31]
The breaking point: 31
The highest safe floor: 30
The number of attempts made: 6
=======================================
[Test Number: 32]
The breaking point: 32
The highest safe floor: 31
The number of attempts made: 7
=======================================
[Test Number: 33]
The breaking point: 33
The highest safe floor: 32
The number of attempts made: 8
=======================================
[Test Number: 34]
The breaking point: 34
The highest safe floor: 33
The number of attempts made: 9
=======================================
[Test Number: 35]
The breaking point: 35
The highest safe floor: 34
The number of attempts made: 10
=======================================
[Test Number: 36]
The breaking point: 36
The highest safe floor: 35
The number of attempts made: 11
=======================================
[Test Number: 37]
The breaking point: 37
The highest safe floor: 36
The number of attempts made: 12
=======================================
[Test Number: 38]
The breaking point: 38
The highest safe floor: 37
The number of attempts made: 13
=======================================
[Test Number: 39]
The breaking point: 39
The highest safe floor: 38
The number of attempts made: 14
=======================================
[Test Number: 40]
The breaking point: 40
The highest safe floor: 39
The number of attempts made: 15
=======================================
[Test Number: 41]
The breaking point: 41
The highest safe floor: 40
The number of attempts made: 15
=======================================
[Test Number: 42]
The breaking point: 42
The highest safe floor: 41
The number of attempts made: 5
=======================================
[Test Number: 43]
The breaking point: 43
The highest safe floor: 42
The number of attempts made: 6
=======================================
[Test Number: 44]
The breaking point: 44
The highest safe floor: 43
The number of attempts made: 7
=======================================
[Test Number: 45]
The breaking point: 45
The highest safe floor: 44
The number of attempts made: 8
=======================================
[Test Number: 46]
The breaking point: 46
The highest safe floor: 45
The number of attempts made: 9
=======================================
[Test Number: 47]
The breaking point: 47
The highest safe floor: 46
The number of attempts made: 10
=======================================
[Test Number: 48]
The breaking point: 48
The highest safe floor: 47
The number of attempts made: 11
=======================================
[Test Number: 49]
The breaking point: 49
The highest safe floor: 48
The number of attempts made: 12
=======================================
[Test Number: 50]
The breaking point: 50
The highest safe floor: 49
The number of attempts made: 13
=======================================
[Test Number: 51]
The breaking point: 51
The highest safe floor: 50
The number of attempts made: 14
=======================================
[Test Number: 52]
The breaking point: 52
The highest safe floor: 51
The number of attempts made: 15
=======================================
[Test Number: 53]
The breaking point: 53
The highest safe floor: 52
The number of attempts made: 15
=======================================
[Test Number: 54]
The breaking point: 54
The highest safe floor: 53
The number of attempts made: 6
=======================================
[Test Number: 55]
The breaking point: 55
The highest safe floor: 54
The number of attempts made: 7
=======================================
[Test Number: 56]
The breaking point: 56
The highest safe floor: 55
The number of attempts made: 8
=======================================
[Test Number: 57]
The breaking point: 57
The highest safe floor: 56
The number of attempts made: 9
=======================================
[Test Number: 58]
The breaking point: 58
The highest safe floor: 57
The number of attempts made: 10
=======================================
[Test Number: 59]
The breaking point: 59
The highest safe floor: 58
The number of attempts made: 11
=======================================
[Test Number: 60]
The breaking point: 60
The highest safe floor: 59
The number of attempts made: 12
=======================================
[Test Number: 61]
The breaking point: 61
The highest safe floor: 60
The number of attempts made: 13
=======================================
[Test Number: 62]
The breaking point: 62
The highest safe floor: 61
The number of attempts made: 14
=======================================
[Test Number: 63]
The breaking point: 63
The highest safe floor: 62
The number of attempts made: 15
=======================================
[Test Number: 64]
The breaking point: 64
The highest safe floor: 63
The number of attempts made: 15
=======================================
[Test Number: 65]
The breaking point: 65
The highest safe floor: 64
The number of attempts made: 7
=======================================
[Test Number: 66]
The breaking point: 66
The highest safe floor: 65
The number of attempts made: 8
=======================================
[Test Number: 67]
The breaking point: 67
The highest safe floor: 66
The number of attempts made: 9
=======================================
[Test Number: 68]
The breaking point: 68
The highest safe floor: 67
The number of attempts made: 10
=======================================
[Test Number: 69]
The breaking point: 69
The highest safe floor: 68
The number of attempts made: 11
=======================================
[Test Number: 70]
The breaking point: 70
The highest safe floor: 69
The number of attempts made: 12
=======================================
[Test Number: 71]
The breaking point: 71
The highest safe floor: 70
The number of attempts made: 13
=======================================
[Test Number: 72]
The breaking point: 72
The highest safe floor: 71
The number of attempts made: 14
=======================================
[Test Number: 73]
The breaking point: 73
The highest safe floor: 72
The number of attempts made: 15
=======================================
[Test Number: 74]
The breaking point: 74
The highest safe floor: 73
The number of attempts made: 15
=======================================
[Test Number: 75]
The breaking point: 75
The highest safe floor: 74
The number of attempts made: 8
=======================================
[Test Number: 76]
The breaking point: 76
The highest safe floor: 75
The number of attempts made: 9
=======================================
[Test Number: 77]
The breaking point: 77
The highest safe floor: 76
The number of attempts made: 10
=======================================
[Test Number: 78]
The breaking point: 78
The highest safe floor: 77
The number of attempts made: 11
=======================================
[Test Number: 79]
The breaking point: 79
The highest safe floor: 78
The number of attempts made: 12
=======================================
[Test Number: 80]
The breaking point: 80
The highest safe floor: 79
The number of attempts made: 13
=======================================
[Test Number: 81]
The breaking point: 81
The highest safe floor: 80
The number of attempts made: 14
=======================================
[Test Number: 82]
The breaking point: 82
The highest safe floor: 81
The number of attempts made: 15
=======================================
[Test Number: 83]
The breaking point: 83
The highest safe floor: 82
The number of attempts made: 15
=======================================
[Test Number: 84]
The breaking point: 84
The highest safe floor: 83
The number of attempts made: 9
=======================================
[Test Number: 85]
The breaking point: 85
The highest safe floor: 84
The number of attempts made: 10
=======================================
[Test Number: 86]
The breaking point: 86
The highest safe floor: 85
The number of attempts made: 11
=======================================
[Test Number: 87]
The breaking point: 87
The highest safe floor: 86
The number of attempts made: 12
=======================================
[Test Number: 88]
The breaking point: 88
The highest safe floor: 87
The number of attempts made: 13
=======================================
[Test Number: 89]
The breaking point: 89
The highest safe floor: 88
The number of attempts made: 14
=======================================
[Test Number: 90]
The breaking point: 90
The highest safe floor: 89
The number of attempts made: 15
=======================================
[Test Number: 91]
The breaking point: 91
The highest safe floor: 90
The number of attempts made: 15
=======================================
[Test Number: 92]
The breaking point: 92
The highest safe floor: 91
The number of attempts made: 10
=======================================
[Test Number: 93]
The breaking point: 93
The highest safe floor: 92
The number of attempts made: 11
=======================================
[Test Number: 94]
The breaking point: 94
The highest safe floor: 93
The number of attempts made: 12
=======================================
[Test Number: 95]
The breaking point: 95
The highest safe floor: 94
The number of attempts made: 13
=======================================
[Test Number: 96]
The breaking point: 96
The highest safe floor: 95
The number of attempts made: 14
=======================================
[Test Number: 97]
The breaking point: 97
The highest safe floor: 96
The number of attempts made: 15
=======================================
[Test Number: 98]
The breaking point: 98
The highest safe floor: 97
The number of attempts made: 15
=======================================
[Test Number: 99]
The breaking point: 99
The highest safe floor: 98
The number of attempts made: 10
=======================================
</pre>
<p>It works! <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/11/20/java-challenge-dropping-balloons-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Test for Empty String</title>
		<link>http://blog.lckymn.com/2009/05/17/test-for-empty-string/</link>
		<comments>http://blog.lckymn.com/2009/05/17/test-for-empty-string/#comments</comments>
		<pubDate>Sun, 17 May 2009 00:30:22 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[Fundamental]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Empty String]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[Maintainability]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=171</guid>
		<description><![CDATA[<p>If you programme in Java (or other languages), the first thing to do when validating a String value might be checking if the String variable has the reference pointing to any String object or not (in other words, if it is null or not) or if the String object to which the reference in the String variable points contains an empty String (&#8220;&#8221;) value. In both cases, there is nothing to validate. Or you might purposely expect it and if <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/05/17/test-for-empty-string/">Test for Empty String</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>If you programme in Java (or other languages), the first thing to do when validating a String value might be checking if the String variable has the reference pointing to any String object or not (in other words, if it is null or not) or if the String object to which the reference in the String variable points contains an empty String (&#8220;&#8221;) value.  In both cases, there is nothing to validate. Or you might purposely expect it and if so, want to do something else. One way or another, the test happens frequently.  In Java, like other languages, there are, of course, many ways to do it. However, there can be a better way than other ways in terms of performance.  The reason why I&#8217;m writing it is that we seem to often forget that kind of basic principles while we are focusing on higher level design issues.  It is maintainability that I think the most important in software development but the better way to test for an empty String that I am about to point out here does not reduce maintainability yet increases performance.</p>
<p>To be honest, I had not thought of any other ways until the second grade when I was a university student. At that time, I coded like the following whenever I tried to test for an empty String.</p>
<pre class="brush: java; title: ; notranslate">
if (text == null || text.equals(&quot;&quot;))
</pre>
<p>(By the way, I now programme in this way when I check if an Object type variable is null.</p>
<pre class="brush: java; title: ; notranslate">
if (null == object)
</pre>
<p>This is to avoid some problem caused by a possible typo mistake that is (object = null) which means assigning null to the variable so it refers to nowhere.  Yet if I use (null == object), that mistake would be (null = object). This is assigning whatever in the object variable to null which does not make any sense and will cause a compile time error thus I can easily notice it.  So I follow this way even though I did not make this kind of mistake before. I will also never do it as long as I keep that style. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> )</p>
<p>Move back to the original topic, when I became a third year student which was the final year of my course, I was attracted to Object-Orientation and Java.  Probably at the same time, I also enjoyed checking out the source code of JDK.  I thought &#8220;it doesn&#8217;t seem to be a good idea to use the equals method for empty String test&#8221; after I read the source of the method in Java String class.</p>
<p>Here is the source code of the equals() method of String class in JDK 1.6.0_13.</p>
<pre class="brush: java; title: ; notranslate">
    /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
	if (this == anObject) {
	    return true;
	}
	if (anObject instanceof String) {
	    String anotherString = (String)anObject;
	    int n = count;
	    if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
		while (n-- != 0) {
		    if (v1[i++] != v2[j++])
			return false;
		}
		return true;
	    }
	}
	return false;
    }
</pre>
<p>For just simple empty String test, the code does not seem to be right, as you see, it requires several lines of code to be processed for that simple test. Since String is immutable its length value is always a constant int value and it is therefore comparing the length of the String with zero should be faster than using the <code>equals()</code> method.</p>
<p>So in order to see how many lines of code in the <code>equals()</code> method are processed to test for an empty String, I made simple test code.  I copied code partially from Java&#8217;s String class and made TestString class which has the same <code>equals()</code> method as what String class has then added some code to display how many lines are processed.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.test.emptystring;

import java.util.Arrays;

/**
 * This is TestString class the code of which is copied from java.lang.String class to test the equals() method of the String class. It just
 * has the part of String code which is enough to see how many lines of code are processed for empty String test.
 *
 * @author Lee, SeongHyun (Kevin)
 * @version 0.01 (2009-05-05)
 */
public final class TestString
{
	/** The value is used for character storage. */
	private final char value[];

	/** The offset is the first index of the storage that is used. */
	private final int offset;

	/** The count is the number of characters in the String. */
	private final int count;

	public TestString()
	{
		this.offset = 0;
		this.count = 0;
		this.value = new char[0];
	}

	public TestString(char value[])
	{
		int size = value.length;
		this.offset = 0;
		this.count = size;
		this.value = Arrays.copyOf(value, size);
	}

	public TestString(int offset, int count, char value[])
	{
		this.value = value;
		this.offset = offset;
		this.count = count;
	}

	public boolean equals(Object anObject)
	{
		int tempCount = 0;
		System.out.println(++tempCount + &quot;: A&quot;);
		if (this == anObject)
		{
			System.out.println(++tempCount + &quot;: B&quot;);
			return true;
		}
		System.out.println(++tempCount + &quot;: C&quot;);
		if (anObject instanceof TestString)
		{
			System.out.println(++tempCount + &quot;: D&quot;);
			TestString anotherString = (TestString) anObject;
			System.out.println(++tempCount + &quot;: E&quot;);
			int n = count;
			System.out.println(++tempCount + &quot;: F&quot;);
			if (n == anotherString.count)
			{
				System.out.println(++tempCount + &quot;: G&quot;);
				char v1[] = value;
				System.out.println(++tempCount + &quot;: H&quot;);
				char v2[] = anotherString.value;
				System.out.println(++tempCount + &quot;: I&quot;);
				int i = offset;
				System.out.println(++tempCount + &quot;: J&quot;);
				int j = anotherString.offset;
				System.out.println(++tempCount + &quot;: K&quot;);
				while (n-- != 0)
				{
					System.out.println(++tempCount + &quot;: L&quot;);
					if (v1[i++] != v2[j++])
					{
						System.out.println(++tempCount + &quot;: M&quot;);
						return false;
					}
				}
				System.out.println(++tempCount + &quot;: N&quot;);
				return true;
			}
		}
		System.out.println(++tempCount + &quot;: O&quot;);
		return false;
	}

}
</pre>
<p>The following is the test code using the TestString.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.test.emptystring;

/**
 * This class is to see how many lines of code in the equals() method of String class are processed to test for an empty String.
 *
 * @author Lee, SeongHyun (Kevin)
 * @version 0.01 (2009-05-05)
 *
 */
public final class EmptyTest
{
	private static final String EMPTY = &quot;It's empty.\n&quot;;
	private static final String NOT_EMPTY = &quot;It's not empty.\n&quot;;

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{

		TestString emptyOne = new TestString();
		TestString anotherEmptyOne = new TestString();
		TestString testString = new TestString(new char[] { 'H', 'e', 'l', 'l', 'o' });

		System.out.println(&quot;TestString emptyOne = new TestString();\n&quot; + &quot;TestString anotherEmptyOne = new TestString();\n&quot;
				+ &quot;TestString testString = new TestString(new char[] { 'H', 'e', 'l', 'l', 'o' });\n&quot;);

		System.out.println(&quot;emptyOne.equals(emptyOne): &quot;);
		if (emptyOne.equals(emptyOne))
		{
			System.out.println(EMPTY);
		}
		else
		{
			System.out.println(NOT_EMPTY);
		}

		System.out.println(&quot;emptyOne.equals(anotherEmptyOne): &quot;);
		if (emptyOne.equals(anotherEmptyOne))
		{
			System.out.println(EMPTY);
		}
		else
		{
			System.out.println(NOT_EMPTY);
		}

		System.out.println(&quot;emptyOne.equals(testString)&quot;);
		if (emptyOne.equals(testString))
		{
			System.out.println(EMPTY);
		}
		else
		{
			System.out.println(NOT_EMPTY);
		}

		System.exit(0);
	}

}
</pre>
<p>The result of this code is</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
TestString emptyOne = new TestString();
TestString anotherEmptyOne = new TestString();
TestString testString = new TestString(new char[] { 'H', 'e', 'l', 'l', 'o' });

emptyOne.equals(emptyOne):
1: A
2: B
It's empty.

emptyOne.equals(anotherEmptyOne):
1: A
2: C
3: D
4: E
5: F
6: G
7: H
8: I
9: J
10: K
11: N
It's empty.

emptyOne.equals(testString)
1: A
2: C
3: D
4: E
5: F
6: O
It's not empty.
</pre>
<p>The first test is comparing two empty TestString objects which are in fact an identical object. To recognise it is an empty String, two lines of the code are executed.</p>
<pre class="brush: plain; gutter: false; highlight: [3]; title: ; notranslate">
emptyOne.equals(emptyOne):
1: A
2: B
It's empty.
</pre>
<p>The second test is comparing two empty TestString objects each of which has a reference to a different TestString object meaning emptyOne.equals(anotherEmptyOne) is true but emptyOne == anotherEmptyOne is false.  It requires to process eleven lines of the code to know anotherEmptyOne object is an empty TestString object.</p>
<pre class="brush: plain; gutter: false; highlight: [12]; title: ; notranslate">
emptyOne.equals(anotherEmptyOne):
1: A
2: C
3: D
4: E
5: F
6: G
7: H
8: I
9: J
10: K
11: N
It's empty.
</pre>
<p>The final one is testing if testString TestString object is an empty TestString object. Since testString has &#8220;Hello&#8221;, it is not empty. To find it, six lines of the code are implemented.</p>
<pre class="brush: plain; gutter: false; highlight: [7]; title: ; notranslate">
emptyOne.equals(testString)
1: A
2: C
3: D
4: E
5: F
6: O
It's not empty.
</pre>
<p>Based on the test above, it is quite obvious that <code>equals()</code> method cannot perform better than comparing zero(0) with the length of String object as the former one requires two to eleven (average: (2+11+6)/3 = 10) lines of code to test for an empty String whereas a length comparison requires only one or two lines of code.  So I finally tested if it is truly faster to check String&#8217;s length to test for an empty String.</p>
<p>The following is the test code.</p>
<pre class="brush: java; title: ; notranslate">
package com.lckymn.test.emptystring;

/**
 * This class is to benchmark the performance of the equals() method in String class and comparing the length of the String object in order
 * to test if the String object contains an empty String.
 *
 * @author Lee, SeongHyun (Kevin)
 * @version 0.01 (2009-05-05)
 */
public final class EmptyPerformanceTest
{
	public static final int HOW_MANY_TIMES = 1000000000;

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		String emptyOne = &quot;&quot;;
		String anotherEmptyOne = new String(&quot;&quot;);
		String notEmptyOne = &quot;Hello&quot;;

		System.out.println(&quot;String emptyOne = \&quot;\&quot;;\n&quot; + &quot;String anotherEmptyOne = new String(\&quot;\&quot;);\n&quot;
				+ &quot;String notEmptyOne = \&quot;Hello\&quot;;\n&quot;);

		long result = 0;

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (&quot;&quot;.equals(emptyOne))
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;\&quot;\&quot;.equals(emptyOne): &quot; + result);

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (&quot;&quot;.equals(anotherEmptyOne))
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;\&quot;\&quot;.equals(anotherEmptyOne): &quot; + result);

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (&quot;&quot;.equals(notEmptyOne))
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;\&quot;\&quot;.equals(notEmptyOne): &quot; + result);

		System.out.println(&quot;&quot;);

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (0 == emptyOne.length())
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;0 == emptyOne.length(): &quot; + result);

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (0 == anotherEmptyOne.length())
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;0 == anotherEmptyOne.length(): &quot; + result);

		result = System.currentTimeMillis();
		for (int i = 0; i &lt; HOW_MANY_TIMES; i++)
		{
			if (0 == notEmptyOne.length())
				;
		}
		result = System.currentTimeMillis() - result;
		System.out.println(&quot;0 == notEmptyOne.length(): &quot; + result);

		System.exit(0);
	}
}
</pre>
<p>And&#8230; seeing is believing&#8230; so here is the result.</p>
<pre class="brush: plain; gutter: false; highlight: [5,6,7,9,10,11]; title: ; notranslate">
String emptyOne = &quot;&quot;;
String anotherEmptyOne = new String(&quot;&quot;);
String notEmptyOne = &quot;Hello&quot;;

&quot;&quot;.equals(emptyOne): 1470
&quot;&quot;.equals(anotherEmptyOne): 6951
&quot;&quot;.equals(notEmptyOne): 5601

0 == emptyOne.length(): 5
0 == anotherEmptyOne.length(): 5
0 == notEmptyOne.length(): 5
</pre>
<p>Using <code>equals()</code> method to test both empty String objects which are also an identical object took 1470 milliseconds while comparing 0 with the length of the emptyOne object took 5 milliseconds.<br />
If the target object is not the same empty object, it is worse. The test shows it took 6951 milliseconds. Again, the length comparison took just 5 milliseconds.  Considering that the test conducted one billion times, taking just 5 milliseconds is really fast.<br />
Finally, as seen in the test, it took 5601 milliseconds to know the given String is not empty.  The length checking is still 5 milliseconds.</p>
<p>Although each test is repeated 1,000,000,000 times, the difference is, in my opinion, not really acceptable as we may have numerous other places to lose the performance of the software thus it might be a good idea to prevent predictable ones from happening.</p>
<p>So better do this when testing for an empty String. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: java; title: ; notranslate">
if (null == text || 0 == text.length())
{
	// it is empty.
}
</pre>
<p>Or if you are using JDK 1.6 (Java 6), you can also use <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#isEmpty()" target="_blank">String&#8217;s isEmpty()</a> method which does exactly the same as checking if its length is 0.</p>
<pre class="brush: java; title: ; notranslate">
if (null == text || text.isEmpty())
{
	// it is empty.
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/05/17/test-for-empty-string/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

