<?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>JavaBeat &#187; Java</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Tue, 21 May 2013 13:43:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Example for a class implementing comparable interface in Java</title>
		<link>http://www.javabeat.net/2013/02/example-for-a-class-implementing-comparable-interface-in-java/</link>
		<comments>http://www.javabeat.net/2013/02/example-for-a-class-implementing-comparable-interface-in-java/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:47:45 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5947</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>When you need some sort of ordering for the classes which you define, you will be going either for a comparable or comparator interface. Consider this example package test; import java.util.*; public class TreeSetTest { private static Set&#60;Person&#62; s = new TreeSet&#60;Person&#62;(); public static void main(String a[]){ s.add(new Person(20)); s.add(new Person(30)); s.add(new Person(10)); s.add(new Person(50)); [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>When you need some sort of ordering for the classes which you define, you will be going either for a comparable or comparator interface. Consider this example</p>
<p><strong>package test;</strong></p>
<p><strong>import java.util.*;</strong></p>
<p><strong>public class TreeSetTest {</p>
<p>private static Set&lt;Person&gt; s = new TreeSet&lt;Person&gt;();</p>
<p>public static void main(String a[]){<br />
s.add(new Person(20));<br />
s.add(new Person(30));<br />
s.add(new Person(10));<br />
s.add(new Person(50));<br />
System.out.println( s);<br />
}<br />
}</p>
<p>class Person implements Comparable&lt;Person&gt; {<br />
int i;<br />
Person(int i){<br />
this.i = i;<br />
}</p>
<p>public int compareTo(Person o) {<br />
System.out.println(<wbr />&#8220;this.i :: &#8221; + this.i);<br />
int j = o.i;<br />
System.out.println(<wbr />&#8220;j :: &#8221; + j);</p>
<p>if (this.i &lt; j) {<br />
return -1;<br />
} else if (this.i == j) {<br />
return 0;<br />
} else {<br />
return 1;<br />
}<br />
}<br />
public String toString() {<br />
return String.valueOf(<wbr />&#8220;Person &#8221; + i);<br />
}<br />
}</strong></p>
<p>&nbsp;</p>
<p>Here in this case, the TreeSet API sorts the order of the Objects when you add to it. So, taking this example, if you try to add the Person objects to the TreeSet, it will be comparing the existing object with the object that is inserted and the comparison of objects is done by casting the objects to the <strong>Comparable</strong> interface and by invoking the <strong>compareTo</strong> method and the return value of this method determines the position where the object will be placed. When you use a comparable interface, you can sort the Class (in this case, <strong>Person</strong>) only with the logic you have specified in the compareTo method. But if you want to do different types of sorting of the same instances, then you can use <strong>Comparators </strong>based on the different instance variables available in the Class which you want to sort. The <strong>java.util.Collectio<wbr />ns </strong>class has a overloaded sort method which accepts the comparator to achieve the specific ordering which we would like to have.</p>
<p>The Java Classes which implements the Comparable interfaces are the wrapper classes like Integer, String, Character, Double, Long, Float etc..</p>
<p>To explain about Comparator, consider the following example</p>
<p><strong>package test;</strong></p>
<p><strong>import java.util.Collectio<wbr />ns;<br />
import java.util.List;<br />
import java.util.ArrayList<wbr />;<br />
import java.util.Comparato<wbr />r;</strong></p>
<p>&nbsp;</p>
<p><strong>public class ComparatorExample {</strong></p>
<p><strong> /**<br />
* @param args<br />
*/<br />
public static void main(String[<wbr />] args) {<br />
List&lt;ComparatorExample.<wbr />Person&gt; personList = new ArrayList&lt;ComparatorExample.<wbr />Person&gt;();<br />
ComparatorExample temp = new ComparatorExample(<wbr />);</p>
<p>personList.add(<wbr />temp.new Person(1, &#8220;abc&#8221;));<br />
personList.add(<wbr />temp.new Person(5, &#8220;mno&#8221;));<br />
personList.add(<wbr />temp.new Person(3, &#8220;xyz&#8221;));</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>System.out.println(<wbr />&#8220;Person List Before sort ::: &#8221; + personList);</p>
<p>IntComparator comparator = new IntComparator(<wbr />);<br />
Collections.<wbr />sort(personList, comparator);<br />
System.out.println(<wbr />&#8220;Person List after Integer sort ::: &#8221; + personList);</p>
<p>Collections.<wbr />sort(personList, new StringComparator(<wbr />));<br />
System.out.println(<wbr />&#8220;Pers on List after String sort ::: &#8221; + personList);<br />
}</p>
<p>class Person {<br />
private int index;</p>
<p>private String name;</p>
<p>Person(int index, String name) {<br />
this.index = index;<br />
this.name = name;<br />
}</p>
<p>public String toString() {<br />
return &#8221; Name :: &#8221; + this.name + &#8221; Index :: &#8221; + this.index;<br />
}<br />
}</p>
<p>static class IntComparator implements Comparator&lt;Person&gt; {</strong></p>
<p><strong> public int compare(Person o1, Person o2) {<br />
int i = o1.index;<br />
int j = o2.index;</p>
<p>if (i &lt; j) {<br />
return -1;<br />
} else if (i == j) {<br />
return 0;<br />
} else {<br />
return 1;<br />
}<br />
}</p>
<p>}</p>
<p>static class StringComparator implements Comparator&lt;Person&gt; {</strong></p>
<p><strong> public int compare(Person o1, Person o2) {<br />
String name1 = o1.name;<br />
String name2 = o2.name;</strong></p>
<p><strong> return name1.compareTo(<wbr />name2);<br />
}<br />
}</strong></p>
<p><strong>}</strong></p>
<p>&nbsp;</p>
<p>In the above given class, the objects have been sorted both based on the index and the name.</p>
<p>For the other question which you asked,</p>
<div><strong>equals() </strong>method is for comparing &#8220;equality&#8221;. <strong>compareTo</strong> is for ordering of objects within a collection. Even if compareTo() returns 0, that does not necessarily mean they are &#8220;equal&#8221;. The concept of &#8220;equality&#8221; can be applied to all objects (hence it&#8217;s defined in the base Object class), but not all objects can have the concept of &#8220;ordering&#8221; (where one object is &#8220;greater than&#8221; another).</div>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fjava%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/java/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/java/feed/" data-count="vertical" data-text="Java" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/example-for-a-class-implementing-comparable-interface-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is super and this keyword in java?</title>
		<link>http://www.javabeat.net/2013/02/what-is-super-and-this-keyword-in-java/</link>
		<comments>http://www.javabeat.net/2013/02/what-is-super-and-this-keyword-in-java/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:16:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5935</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>keyword : this &#8216;this&#8217; is used for pointing the current class instance. It can be used with variables or methods. Look into the following example: class Test{ private int i=10; public void m(){ System.out.println(this.i); } } In the above code this is used for the current instance. Since this is instance of a class it [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><b><i>keyword : this</i></b></p>
<p>&#8216;this&#8217; is used for pointing the current class instance. It can be used with variables or methods. Look into the following example:</p>
<pre><code>
class Test{
	private int i=10;
	public void m(){
		System.out.println(this.i);
	}
}
</code></pre>
<p>In the above code <i>this</i> is used for the current instance. Since <i>this</i> is instance of a class it cannot be used inside a <i>static</i> method.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><b><i>keyword : super</i></b></p>
<p>&#8216;super&#8217; is used for pointing the super class instance. See the following example.</p>
<pre><code>
class A
{
	int k = 10;
}
class Test extends A
{
	public void m()
	{
		System.out.println(super.k);
	}
}
</code></pre>
<p>In the above example the <i>super</i> keyword is used for accessing the <i>super</i> class variable.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/what-is-super-and-this-keyword-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use BitWise shift operator in Java?</title>
		<link>http://www.javabeat.net/2013/02/how-to-use-bitwise-shift-operator-in-java/</link>
		<comments>http://www.javabeat.net/2013/02/how-to-use-bitwise-shift-operator-in-java/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 03:53:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5932</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>They are called shift operators and they operate by shifting the number of bits being specified as an operand in the operation. &#62;&#62; ---&#62; Right shift Operator &#60;&#60; ---&#62; Left Shift Operator &#62;&#62;&#62; ----&#62; Right bit with zero fill operator. The first two maintain the MSB when shifting thereby they maintain the sign of the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>They are called shift operators and they operate by shifting the number of bits being specified as an operand in the operation.</p>
<pre><code>
   &gt;&gt; ---&gt; Right shift Operator
  &lt;&lt; ---&gt; Left Shift Operator
  &gt;&gt;&gt; ----&gt;  Right bit with zero fill operator.
</code></pre>
<p>The first two maintain the MSB when shifting thereby they maintain the sign of the operand. Whereas the third one (zero filled) operator fills the MSB with zeros thats why the special name.</p>
<p>When you say,</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre><code>  
int x = 5 &gt;&gt; 2; // 0000 0101 gets shifted to two positions in the right and the sign bit is maintained. 
int x = -5 &gt;&gt; 2; // now you get to know the difference as the result would still be negative
int x = 5 &lt;&lt; 2; // 0000 0101 gets shifted to two positions to the left
int x = 5 &gt;&gt;&gt; 2; // 2 positions to the right by filling the MSBs zeros and thereby losing the sign bits!
</code></pre>
<p>See the program below for an example.</p>
<pre><code>&lt;
public class ShiftOperatorDemo {
    public static void main(String[] args) {
        int x = 5;
        System.out.println("x is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = x &gt;&gt; 2;
        System.out.println("x &gt;&gt; 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = 5 &lt;&lt; 2;
        System.out.println("5 &lt;&lt; 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = -5 &lt;&lt; 2;
        System.o ut.println("-5 &lt;&lt; 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
        x = 5 &gt;&gt;&gt; 2;
        System.out.println("5 &gt;&gt;&gt; 2 is : "+x+", binaryString : "+Integer.toBinaryString(x));
    }    
}

Output is :
x is : 5, binaryString : 101
x &gt;&gt; 2 is : 1, binaryString : 1
5 &lt;&lt; 2 is : 20, binaryString : 10100
-5 &lt;&lt; 2 is : -20, binaryString : 11111111111111111111111111101100
5 &gt;&gt;&gt; 2 is : 1, binaryString : 1
</code></pre>
<p>NOTE: We do NOT have an operator like &#8220;&lt;&lt;&lt;&#8221; in Java</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/how-to-use-bitwise-shift-operator-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is difference between equals() and == ?</title>
		<link>http://www.javabeat.net/2013/02/what-is-difference-between-equals-and/</link>
		<comments>http://www.javabeat.net/2013/02/what-is-difference-between-equals-and/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 03:48:20 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5928</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Explanation : 1 They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the &#8216;==&#8217; operator is expected to check the actual object instances are same or [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><b>Explanation : 1 </b></p>
<p>They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the &#8216;==&#8217; operator is expected to check the actual object instances are same or not.</p>
<p>For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.</p>
<pre class="brush: java; title: ; notranslate">
 s1 = new String(&quot;abc&quot;);
 s2 = new String(&quot;abc&quot;);
</pre>
<p>Now, if you use the &#8220;equals()&#8221; method to check for their equivalence as</p>
<pre class="brush: java; title: ; notranslate">
 if(s1.equals(s2))
      System.out.println(&quot;s1.equals(s2) is TRUE&quot;);
 else
      System.out.println(&quot;s1.equals(s2) is FALSE&quot;);
</pre>
<p>You will get the output as TRUE as the &#8216;equals()&#8217; method check for the content equality.</p>
<p>Lets check the &#8216;==&#8217; operator..</p>
<pre class="brush: java; title: ; notranslate">
if(s1==s2)
     System.out.printlln(&quot;s1==s2 is TRUE&quot;);
   else
     System.out.println(&quot;s1==s2 is FALSE&quot;);
</pre>
<p>Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of &#8216;new String()&#8217; everytime a new object is created.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Try running the program without &#8216;new String&#8217; and just with</p>
<pre class="brush: java; title: ; notranslate">
   String s1 = &quot;abc&quot;;
   String s2 = &quot;abc&quot;;
</pre>
<p>You will get TRUE for both the tests. <b>Explanation : 2 </b></p>
<p>By definition, the objects are all created on the heap. When you create an object, say,</p>
<pre class="brush: java; title: ; notranslate">
Object ob1 = new SomeObject();
Object ob2 = new SomeObject();
</pre>
<p>We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0&#215;1234 and ob2 is at address 0&#215;2345. Though the contents of the objects are the same, the references differ.</p>
<p>Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0&#215;1234 is compared with ob2 at address 0&#215;2345. Hence, this comparison would fail.</p>
<p>object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/what-is-difference-between-equals-and/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Difference Between List and ArrayList ?</title>
		<link>http://www.javabeat.net/2013/02/difference-between-list-and-arraylist/</link>
		<comments>http://www.javabeat.net/2013/02/difference-between-list-and-arraylist/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 03:44:07 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5925</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>List is an interface and ArrayList is an implementation of the List interface. The arraylist class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>List is an interface and ArrayList is an implementation of the List interface. The arraylist class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second. If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class. Where as, u are free to use all the methods available in the ArrayList, if u use the second one.</p>
<p>To add some more points to this,</p>
<p>1. I would say the first approach is a better one because, when you are developing java applications, when you are supposed to pass the collection framework objects as arguments to the methods, then it is better to go with</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre><code>
List tempList = new ArrayList();
somemethodcall(tempList);
</code></pre>
<p>Why am i saying this because, in future due to performance constraints, if you are changing the implementation to use linkedlist or someother classes which implements List interface, instead of ArrayList, you can change at only one point (i.e) only the instantiation part. Else u ll be supposed to change at all the areas,whereever, u have used the specific class implementation as method arguments.</p>
<p>You cannot check for performance in this. Instead u can check for performances of the implementing classes of List interface in the following link. It explains you about the performance statistics of the collection framework</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/difference-between-list-and-arraylist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is the difference between JRE,JVM and JDK?</title>
		<link>http://www.javabeat.net/2013/02/what-is-the-difference-between-jrejvm-and-jdk/</link>
		<comments>http://www.javabeat.net/2013/02/what-is-the-difference-between-jrejvm-and-jdk/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 02:15:13 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JRE]]></category>
		<category><![CDATA[JVM]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5919</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>JDK (Java Development Kit) Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. You need [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>JDK (Java Development Kit)</h2>
<p>Java Developer Kit contains tools needed to develop the Java programs, and <b><i>JRE</i></b> to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…</p>
<p>Compiler converts java code into byte code. Java application launcher opens a <b><i>JRE</i></b>, loads the class, and invokes its main method.</p>
<p>You need <b><i>JDK</i></b>, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.</p>
<p>JRE is targeted for execution of Java files</p>
<p>i.e. <b>JRE</b> = <b>JVM</b> + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.</p>
<p><b><i>JDK</i></b> is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>JRE (Java Runtime Environment)</h2>
<p>Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system</p>
<p>The <b><i>Java Virtual Machine</i></b> provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.</p>
<p>If u just want to run applets (ex: Online Yahoo games or puzzles), <i>JRE</i> needs to be installed on the machine.</p>
<h2>JVM (Java Virtual Machine)</h2>
<p>As we all aware when we compile a <b><i>Java file</i></b>, output is not an &#8216;exe&#8217; but it&#8217;s a &#8216;.class&#8217; file. &#8216;.class&#8217; file consists of <b><i>Java byte codes</i></b> which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.</p>
<p>The <b><i>JVM</i></b> is called &#8220;virtual&#8221; because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.</p>
<p>There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/what-is-the-difference-between-jrejvm-and-jdk/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to use Socket API for creating Client-Server application in Java</title>
		<link>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/#comments</comments>
		<pubDate>Mon, 20 Aug 2012 17:56:55 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4842</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this example we make use of ServerSocketChannel and SocketChannel to create a simple Echo application where in the Server would print the data sent by the client. The code is explained with the required comments: and the client which connects to the server is:</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this example we make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/ServerSocketChannel.html" target="_blank">ServerSocketChannel</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/SocketChannel.html" target="_blank">SocketChannel</a> to create a simple Echo application where in the Server would print the data sent by the client. </p>
<p>The code is explained with the required comments:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * This creates a server on a particular IP address and the port.
 *
 */
public class ServerClass {

  public static void main(String[] args) {

    // Create a Server socket channel.
    try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {

      // Bind the server socket channel to the IP address and Port
      serverSocket.bind(new InetSocketAddress(&quot;127.0.0.1&quot;, 6667));
      System.out.println(&quot;Waiting for client connections&quot;);

      while (true) {
        
        //Wait and Accept the client socket connection. 
        try (SocketChannel socketChannel = serverSocket.accept()) {
          
          //Printing the address of the client.
          System.out.println(&quot;Obtained connection from: &quot;+socketChannel.getRemoteAddress().toString());
          
          //Creating a reader for reading the content on the socket input stream.
          Scanner socketReader = new Scanner(socketChannel.socket().getInputStream());
          while(socketReader.hasNext()){
            
            //Reading the content of the socket input stream.
            System.out.println(socketReader.nextLine());
            
          }

        } catch(IOException ex){
          ex.printStackTrace();
        }
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

}
</pre>
<p>and the client which connects to the server is:</p>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class CilentClass {
  
  public static void main(String[] args) {
    
    //Create a client socket.
    try(SocketChannel socketChannel = SocketChannel.open()){
      
      //Bind the client socket to the server socket.
      socketChannel.connect(new InetSocketAddress(&quot;127.0.0.1&quot;, 6667));
      
      //Writing to the socket channel.
      PrintWriter writer = new PrintWriter(socketChannel.socket().getOutputStream(), true);
      writer.println(&quot;Client sending instruction 1&quot;);
      writer.println(&quot;Client sending instruction 2&quot;);
      writer.println(&quot;Client sending instruction 3&quot;);
      writer.println(&quot;Client sending instruction 4&quot;);
      
    }catch(IOException ex){
      ex.printStackTrace();
    }
    
  }
}
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to use ByteBuffer in Java?</title>
		<link>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/#comments</comments>
		<pubDate>Mon, 06 Aug 2012 19:13:42 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[nio]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4836</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>ByteBuffer API has been in Java since 1.4. The name itself suggests that these contain bytes of data. The data to be stored in the buffer can be Integer (int, long), Characters (char), Floating value (double), all these are converted into bytes before being stored in the buffer array. ByteBuffer can be of two types- [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>ByteBuffer API has been in Java since 1.4. The name itself suggests that these contain bytes of data. The data to be stored in the buffer can be Integer (int, long), Characters (char), Floating value (double), all these are converted into bytes before being stored in the buffer array. ByteBuffer can be of two types- </p>
<ul>
<li>Direct ByteBuffer</li>
<li>Non-Direct ByteBuffer</li>
</ul>
<p><strong>Direct ByteBuffer</strong>: JVM tries to use Native IO operations on buffers which are created as direct i.e it doesnt load the buffer contents into another buffer and instead tries to use the buffer directly.<br />
There are a few essential properties of ByteBuffer:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>Limit: While writing to a buffer, <em>limit</em> indicates how many more bytes can be written, whereas while reading from a buffer <em>limit</em> indicates how many more bytes can be read.</li>
<li>Position: <em>Position</em> tracks how much data is written or can be read from a buffer.</li>
<li>Capacity: <em>Capacity</em> specifies the number of bytes a buffer can store. </li>
</ul>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html" title="ByteBuffer" target="_blank">ByteBuffer</a> provides plethora of methods to fetch data from the buffer and to add data to the buffer. The below code shows the use of those APIs:</p>
<pre class="brush: java; title: ; notranslate">
import java.nio.ByteBuffer;

public class ByteBufferTest {
  
  public static void main(String[] args) {

    //Create a directBuffer of size 200 bytes
    ByteBuffer directBuffer = ByteBuffer.allocateDirect(200);
    
    //Create a nonDirectBuffer of size 200 bytes
    ByteBuffer nonDirectBuffer = ByteBuffer.allocate(200);
    
    //Get the capacity of the buffer
    System.out.println(&quot;Capacity &quot;+nonDirectBuffer.capacity());
    
    //Get the position of the buffer
    System.out.println(&quot;Position &quot;+nonDirectBuffer.position() );
    
    //Add data of different types to the buffer
    nonDirectBuffer.putChar('A');
    nonDirectBuffer.putInt(10);
    nonDirectBuffer.putDouble(0.98);
    
    //Get the position of the buffer, would print 14 as its has 14 bytes of data
    System.out.println(&quot;Position &quot;+nonDirectBuffer.position() );
    nonDirectBuffer.putFloat(8.9f);
    
    //Fetch the data from buffer
    System.out.println(nonDirectBuffer.getChar(0));
    
    //A char is of 2 bytes, so fetch the integer at index 0+2=2bytes
    System.out.println(nonDirectBuffer.getInt(2));
    
    //A int is of 4 bytes so fetch the double value at index 2+4=6bytes
    System.out.println(nonDirectBuffer.getDouble(6));
    
    //A double is of 8 bytes so fetch the float value at index 6+8=14bytes
    System.out.println(nonDirectBuffer.getFloat(14));
   
  }
}

</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Developing Concurrent applications using ExecutorService Framework in Java</title>
		<link>http://www.javabeat.net/2012/07/executorservice-framework-in-java/</link>
		<comments>http://www.javabeat.net/2012/07/executorservice-framework-in-java/#comments</comments>
		<pubDate>Sun, 01 Jul 2012 19:55:34 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java concurrency]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4548</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We all have used Thread, Runnable to develop multi-threaded applications in Java. While we used Thread and Runnable we had a lot of work to do in terms of assigning the task to the Thread, starting the thread to waiting for it to complete the execution to get the result from each thread. In Java [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We all have used <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html" target="_blank">Thread</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html" target="_blank">Runnable</a> to develop multi-threaded applications in Java. While we used Thread and Runnable we had a lot of work to do in terms of assigning the task to the Thread, starting the thread to waiting for it to complete the execution to get the result from each thread. In Java 5 there were some really good constructs including ExecutorService Framework in Java introduced for developing concurrent applications using the multi-threading support provided by JVM. These were added to the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html" target="_blank">java.util.concurrent</a> package. </p>
<p>There are lots of developers who worked on Pre Java 5 versions and developed their own Concurrent frameworks around the basic support Java provided. Lot of them still continue to use their frameworks. In this post I would like to see how we can evolve a simple problem implemented in a sequential way to make use of Thread and Runnable and then to make use of some advanced constructs in java.util.concurrent package more specifically ExecutorService Framework in Java. </p>
<p><strong>Problem is</strong>: There is a list of 11 integer arrays each of different size. We wish to compute the sum of the integers in each of those arrays. We can do this sequentially picking one array at a time or use multiple threads for each array and compute the sum and add it to a data structure or use the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html" target="_blank">ExecutorService</a> framework to divide the operation into multiple task and obtain the result from each task.<br />
The main aim of this simple problem/activity is to see how we can exploit the power of the language API. </p>
<p>Note: This code sample would work on Java 7 only as I have made use of the Files API provided in Java 7.</p>
<p>Before we start with the calculation on sum, we have stored the arrays in a file and places it in some directory(In this case I have placed it in the file named &#8220;arrays&#8221; in my linux home directory). We then read the file and construct the List of integer arrays. The contents of the file are:</p>
<pre class="brush: java; title: ; notranslate">
4,5,6,7,84,567,1234,678,23,1234,567,89,22,32,56,77,63
67,12,34,21,23,81,49,4,1,9,49,2312
123,78,234,568,98,38,234,9,7,4,2,1,23,67
34,56,78,96,23,58,28,18,235,875,12,6,7,8,4
75,2435,7,345,234,123,1267,4,56,73,4,5,6,7,8
23,78,234,568,98,38,234,9,7,4,2,1,2,67,61,8
534,56,78,96,23,58,28,18,23,875,12,6,7,8,4,12,7
5,255,7,345,24,123,17,4,56,73,4,5,6,7,8
13,78,234,568,98,38,234,9,7,4,2,1,23,67
4,56,78,96,23,58,28,18,235,875,12,6,7,8,4
7,235,7,35,234,123,126,4,56,73,4,5,6,7,8
</pre>
<p>And the code which loads the above data in to a List of List of Integers is:</p>
<pre class="brush: java; title: ; notranslate">
 private static List&lt;List&lt;Integer&gt;&gt; loadDataFromFile()
          throws IOException {
    Path path = Paths.get(&quot;/home/mohamed/arrays&quot;);

    List&lt;String&gt; linesInFile = Files.readAllLines(path, 
        Charset.defaultCharset());

    List&lt;List&lt;Integer&gt;&gt; arrays = new ArrayList&lt;&gt;();

    for ( String s : linesInFile){

      String [] sArray = s.split(&quot;,&quot;);

      List&lt;Integer&gt; integers = new ArrayList&lt;&gt;();

      for ( String sInt : sArray){
        
        integers.add(Integer.parseInt(sInt));
        
      }
      arrays.add(integers);
    }

    return arrays;
  }
</pre>
<h4>Sequential approach to finding the sum of each array</h4>
<p>In each of the examples below I would just give the method which calculates the sum and out put of that method. At the end of the post there is a link to download the complete code. </p>
<pre class="brush: java; title: ; notranslate">
 private static List&lt;Integer&gt; calculateSequentially(
        List&lt;List&lt;Integer&gt;&gt; integerArrays) 
 {
    List&lt;Integer&gt; sumOfEachArray = new ArrayList&lt;&gt;();

    for ( List&lt;Integer&gt; integers : integerArrays)
    {
      int sum = 0;
      for(Integer i : integers)
      {
        sum+=i;
      }

      sumOfEachArray.add(sum);

    }

    return sumOfEachArray;
  }
</pre>
<p>The above code is very straight forward- iterate through each array and find its sum.<br />
<strong>The output is</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
Array 1:4748
Array 2:2662
Array 3:1486
Array 4:1538
Array 5:4649
Array 6:1434
Array 7:1845
Array 8:939
Array 9:1376
Array 10:1508
Array 11:930
</pre>
<p>Before I go into solving the above problem in a concurrent way, let me caution you about some of the performance problems one would encounter related to concurrent applications:</p>
<ul>
<li>Cost incurred due to context switching- When ever the currently running thread is replaced by another thread to execute, there is a context switch involved which includes saving of the state of the thread executing currently and then restoring the state of the thread to be executed. If the CPU spends lot of time in context switching- may be due to frequent thread scheduling or threads completing very quickly then it may not get time to do useful work. </li>
<li>Threads may block due to lock contention which slows down the application.</li>
<li>Memory synchronisation related overhead- as there are multiple threads accessing the shared memory, there is a lot of overhead involved in maintaining the consistent state of the data in the memory. At times there are lot of blocking calls in the APIs used which further delay the execution/completion of the threads. </li>
</ul>
<p>One should avoid premature optimisation and also decide whether concurrency is really required in the application. Adding features which are not really necessary is often an overhead. If the tasks can be completed fast and you dont expect too many of them coming in at the same time its not necessary to execute them concurrently. The examples which follow are just to illustrate the various concepts involved in using the ExecutorService Framework in Java. </p>
<h4>Using Multi-Threaded approach to finding sum</h4>
<p>After a brief insight into the performance aspects of concurrent applications, lets go ahead and make the sum calculation concurrent. Lets spawn one thread for each array and let the thread calculate the sum. In this case we make use of a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" target="_blank">ConcurrentHashMap</a> to allow each thread to update its result into that map.</p>
<p>The Runnable which takes an Array and calculates the sum of its elements is defined below. In addition it has a name of the array which it is dealing with and also a reference to the instance of the ConcurrentHashMap which is shared among multiple threads. </p>
<pre class="brush: java; title: ; notranslate">
class ArraySumCalculator implements Runnable{

  ConcurrentHashMap&lt;String, Integer&gt; sumMap;
  List&lt;Integer&gt; integers;
  String arrayName;
  
  ArraySumCalculator(ConcurrentHashMap&lt;String, Integer&gt; sumMap,
                     List&lt;Integer&gt; integers,
                     String arrayName){

    this.sumMap = sumMap;
    this.integers = integers;
    this.arrayName = arrayName;

  }
  
  @Override
  public void run() {

    int sum = 0;
    for ( Integer i : integers){
      sum += i;
    }

    sumMap.put(arrayName, sum);

  }
}
</pre>
<p>And the below code would create multiple threads and launch them by passing in the corresponding ArraySumCalculator instance. </p>
<pre class="brush: java; title: ; notranslate">
private static ConcurrentHashMap&lt;String, Integer&gt; calculateUsingThreads(
          List&lt;List&lt;Integer&gt;&gt; integerArrays){

    ConcurrentHashMap&lt;String, Integer&gt; sumMap =
            new ConcurrentHashMap&lt;&gt;(integerArrays.size());
    
    List&lt;Thread&gt; threads = new ArrayList&lt;&gt;();
    int i = 1;
    
    //Create thread instances for each array
    for ( List&lt;Integer&gt; integers : integerArrays){
      
      String arrayName = &quot;Array &quot;+i;
      
      Thread thread = new Thread(
              new ArraySumCalculator(sumMap,integers,arrayName));
      threads.add(thread);
      i++;
    }

    //Now launch all the threads at the same time
    for ( Thread thread : threads){
      thread.start();
      try {
        thread.join();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }

    return sumMap;
  }
</pre>
<p>The above code first creates the Thread instances along with the corresponding ArraySumCalculator instance and collects them in a List. And then iterates through this List to launch each thread and then join with the launched thread so that the Main thread would wait until all the threads have completed execution and updated the map.<br />
<strong>The output</strong> of the above method would be:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: bash; title: ; notranslate">
Array 1:4748
Array 2:2662
Array 3:1486
Array 4:1538
Array 5:4649
Array 6:1434
Array 7:1845
Array 8:939
Array 9:1376
Array 10:1508
Array 11:930
</pre>
<p>In this example we had to do 2 things which are not recommended:</p>
<ul>
<li>use a common Map (thought its supports concurrent updates) to store the output generated in each thread.</li>
<li>manage the launching of each thread, which ideally should be managed by a framework. In the above example we created 11 threads i.e one thread for each array. But the underlying processor may support execution of only 2 threads concurrently. So there is lot of context switching involved. We could have used a ThreadPool but managing the ThreadPool would be another liability.</li>
</ul>
<p>As I said at the start of the post that Java 5 provides a concurrency framework called Executor which provides a flexible and powerful framework for asynchronous task execution that supports a wide variety of task execution policies. It provides a standard means of decoupling task submission from task execution, describing tasks with Runnable. </p>
<h4>Using Executor with Runnable</h4>
<p>In this example lets still stick with the idea of multiple Runnables updating the ConcurrentHashMap and instead of we spawning different threads, lets leave it to the Executor to allocate tasks to different threads. <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html" target="_blank">Executor</a> provides static factory methods to create thread pool:</p>
<ul>
<li><strong>newFixedThreadPool</strong>: A fixed-size thread pool creates threads as tasks are submitted, up to the maximum pool size, and then attempts to keep the pool size constant.</li>
<li><strong>newCachedThreadPool</strong>: A cached thread pool has more flexibility to reap idle threads when the current size of the pool exceeds the demand for processing and to add new threads when the demand increases.</li>
<li><strong>newSingleThreadExecutor</strong>: A single threaded executor creates a single worker thread to process tasks, replaces it if it dies unexpectedly.</li>
<li><strong>newScheduledThreadPool</strong>: A fixed-size thread pool that supports delayed and periodic task execution.</li>
</ul>
<p>In the below example we make use of a Fixed sized thread pool where in the size is decided by the number of CPUs available in the hardware. For compute intensive tasks, an N CPU processor system achieves optimum utilisation with a thread pool of N+1 threads. </p>
<p>If we just use Executor, we will not be able to shutdown it. An Executor implementation is likely to create threads for processing tasks. But the JVM cannot exit until all the nondaemon threads have terminated, so failing to shutdown an Executor could prevent the JVM from exiting. The <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html" target="_blank">ExecutorService</a> interface extends Executor adding a number of methods for lifecycle management. We will see how we can use this interface in the below example:</p>
<pre class="brush: java; title: ; notranslate">
private static ConcurrentHashMap&lt;String, Integer&gt; calculateUsingExecutor(
        List&lt;List&lt;Integer&gt;&gt; integerArrays){

  ConcurrentHashMap&lt;String, Integer&gt; sumMap = new
          ConcurrentHashMap&lt;&gt;(integerArrays.size());

  //Number of threads = 1 more than number of processors.
  ExecutorService executor = Executors.newFixedThreadPool(
          Runtime.getRuntime().availableProcessors()+1);

  int i = 1;
  for(List&lt;Integer&gt; integers : integerArrays){

    String arrayName = &quot;Array &quot;+i;

    executor.execute(
            new ArraySumCalculator(sumMap,integers, arrayName));
    i++;
  }

  //Shutdown the executor
  executor.shutdown();

  //Await for sometime so as to allow the pending tasks to be picked
  try {

    executor.awaitTermination(60,TimeUnit.SECONDS);

  } catch (InterruptedException e) {

    Thread.currentThread().interrupt();
  }

  return sumMap;
}
</pre>
<p>In the above example we make use of the static factory method to create an instance of ExecutorService and provide the number of threads to be created in the thread pool. We then ask the executor to execute each of the Runnables. The ExecutorService assigns the tasks to the threads in the thread pool. The shutdown() method of ExecutorService is invoked which allows the tasks already submitted to complete and doesn&#8217;t accept any new tasks. We then wait for termination by invoking awaitTermination and pass the time to wait for. <strong>The output</strong> for the above would be same as that for other cases.</p>
<p>There are a few problems in this approach as well:</p>
<ul>
<li>we still are making use of the common Map for updating the results and still use the same Runnable.</li>
<li>we need to use some timeout to wait so that all the tasks are picked up for execution and not terminate prematurely.</li>
</ul>
<p>There&#8217;s yet another way to overcome the above shortcomings. And this use another class called: <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html" target="_blank">Callable</a>. </p>
<h4>Using ExecutorService with Callable</h4>
<p>The problem with Runnable is that its run method doesn&#8217;t return any result. Callable interface is similar to Runnable but it supports returning value from its call method. In our example we would calculate the sum of the integers in the list and return their sum instead of updating it in the map. </p>
<pre class="brush: java; title: ; notranslate">
class ArraySumCallable implements Callable&lt;Integer&gt;{

  List&lt;Integer&gt; integers;

  ArraySumCallable(List&lt;Integer&gt; integers){
    
    this.integers = integers;
  }
  
  @Override
  public Integer call() throws Exception {
    
    Integer sum = 0;
    
    for (Integer i : integers){
      sum += i;
    }
    
    return sum;

  }
}
</pre>
<p>Lets use the above Callable and ExecutorService to calculate the sum of the elements in various arrays. We initially create all the Callable instances providing the integer array to each one. And then make use of invokeAll method of the ExecutorService to submit all the Callables for execution. The invokeAll method returns a List of <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html" target="_blank">Future</a>. A Future represents a return of the asynchronous operation. In our case the operation is to calculate the sum of the integers in the array. We need not maintain a common map for threads to update. Instead we could get instances of Future for each task and then invoke the get() method on the instance of Future to obtain the result of the task. The get method is the blocking call i.e it waits for the result from the task. Lets have a look at the code:</p>
<pre class="brush: java; title: ; notranslate">
public static List&lt;Integer&gt; calculateSumUsingCallable(
        List&lt;List&lt;Integer&gt;&gt; integerArrays){

  List&lt;Callable&lt;Integer&gt;&gt; callables = new ArrayList&lt;&gt;(integerArrays.size());

  List&lt;Integer&gt; arraySum = new ArrayList&lt;&gt;(integerArrays.size());
  
  //Create callables for each array
  for ( List&lt;Integer&gt; integers : integerArrays){
    Callable&lt;Integer&gt; callable = new ArraySumCallable(integers);
    callables.add(callable);
  }

  //get fixed thread pool executor
  ExecutorService executorService = Executors.newFixedThreadPool(
          Runtime.getRuntime().availableProcessors() + 1);


  try {

    //Submit all the callables and obtain their Futures
    List&lt;Future&lt;Integer&gt;&gt; futures =
            executorService.invokeAll(callables);

    executorService.shutdown();

    //Iterate through the futures and get the sum
    for ( Future&lt;Integer&gt; future : futures){
      Integer sum = future.get();

      arraySum.add(sum);


    }

  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();

  } catch (ExecutionException e) {
    System.out.println(&quot;Exception while calculating sum&quot;);

  }

  return arraySum;

}
</pre>
<p>The output is the same as given in the earlier examples. </p>
<p>To summarise:</p>
<ol>
<li>Creates a sequential program to calculate the sum of the elements of each array from the list of arrays</li>
<li>Used multiple threads to calculate the sum, found that we had to manage the thread creation and also make use of common map which was error prone</li>
<li>We made use of ExecutorService along with Runnable to create different tasks and leave it to framework to allocate threads for each task.</li>
<li>Made use of ExecutorService Framework in Java along with Callable so as to create result bearing tasks and used Future to get the result from each task.</li>
</ol>
<p>One can download the complete sample code from <a href="https://gist.github.com/3029344" target="_blank">here</a>.</p>
<p>If any one is interested to learn more about using ExecutorService Framework in Java and other concurrency constructs, you can pick <a href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" target="_blank">Java Concurrency In Practice</a>. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/executorservice-framework-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java HelloWorld vs Scala HelloWorld</title>
		<link>http://www.javabeat.net/2012/06/java-helloworld-vs-scala-helloworld/</link>
		<comments>http://www.javabeat.net/2012/06/java-helloworld-vs-scala-helloworld/#comments</comments>
		<pubDate>Sun, 17 Jun 2012 01:39:00 +0000</pubDate>
		<dc:creator>Smita</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[compare java scala]]></category>
		<category><![CDATA[main]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4126</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>As a first step into learning Scala and as one who is familiar with Java, let us compare the customary Helloworld programs in Java and Scala. You might already know that to run a Java program, there must be a public class with a main method that takes one parameter, a String[], and has a void return [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>As a first step into learning Scala and as one who is familiar with Java, let us compare the customary Helloworld programs in Java and Scala. You might already know that to run a Java program, there must be a public class with a main method that takes one parameter, a String[], and has a void return type. For example:</p>
<pre class="brush: java; title: ; notranslate">
package javaapplication;
public class Main {
   public static void main(String[] args) {
       System.out.println(&quot;Hello World&quot;);
   }
}
</pre>
<p>In Scala, an equivalent program looks something as follows -</p>
<pre class="brush: java; title: ; notranslate">
 package scalaapplication
 object Main {
def main(args: Array[String]): Unit = {
println(&quot;Hello World&quot;)
}
 }
</pre>
<p>The output of both of the above programs is to print out Hello World. We compare and contrast the first programs in Java and Scala as follows:</p>
<ul>
<li>Both the programs begin with a <span style="color: #993366;">package declaration</span>. While the package statement or rather every statement in the Java program ends with a semi-colon, semicolon is not mandatory in the Scala program. In a Scala program, the compiler does not care whether a statement ends with a semicolon or not. Newline marks end of a statement and beginning of another. Semicolon is required though when multiple statements are written in a single line.</li>
</ul>
<ul>
<li>While <span style="color: #993366;">import statement</span> is not shown in the above simple programs, they can both be part of a program in Java as well as Scala. Scala provides an easier and more concise way to import multiple statements as we will see in a later post.</li>
</ul>
<ul>
<li>The major contrast between the two programs is that while the Java program has a <span style="color: #993366;">class declaration</span>, the Scala program has an <span style="color: #993366;">object declaration</span>.</li>
</ul>
<p>Conceptually, a class is a blueprint for objects. An object is a concrete instance of a class.</p>
<p>In Java, we create an object using the new keyword followed by the class name. In Scala, we can directly define an object as shown above. We can also, of course, define classes and create objects using new keyword as in Java. The reason why we have defined an object instead of a class in the equivalent Scala program is described in a short while.</p>
<ul>
<li>Before we move on, in both programs, the Java class and the Scala object are <span style="color: #993366;">public</span>. In Java, the modifier named public needs to be used to mark a class/class member as public. In Scala, by default a class/class member is public. That is, when there is no access modifier, it means that the class/class member has  public access.</li>
</ul>
<ul>
<li>Main Methods are defined in very similar yet different ways in Java and Scala programs. An illustration for the main method definitions as they compare with each other in the two languages follows -</li>
</ul>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/06/Untitled.jpg"><img class="size-full wp-image-4249 aligncenter" src="http://www.javabeat.net/wp-content/uploads/2012/06/Untitled.jpg" alt="" width="562" height="212" /></a></p>
<p><em>def</em> is the keyword that marks the beginning of any function definition in Scala. There is no such equivalent keyword in Java. The main point of difference is the <span style="color: #800080;">absence of the static</span> keyword in the Scala main method definition.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>As Scala is a purely objected oriented language, there are no static things in Scala. Nevertheless, in order to achieve a similar behavior, Scala allows defining of something called as singleton objects. Just for now, a singleton object is one which looks like a class definition but with keyword object instead of class. In the above Scala program, Main is a standalone singleton object. To put it simplistically, for a Java programmer, a singleton object in Scala, is an equivalent holder of static methods if it were Java. So, now we know why we have defined an object in the above Scala program instead of a class.</p>
<p>The next important thing that can be noticed is the keyword &#8216;<span style="color: #800080;">Unit</span>&#8216; in the Scala main method definition. Unit is a return type for a function. Unit is used as a result type in a method, if all the method does is produce a side effect and not return any specific value as such. In our case, the side effect is printing out &#8220;Hello World&#8221;.</p>
<ul>
<li>Both the programs use curly braces to mark the beginning and end of method or class.</li>
</ul>
<ul>
<li>While Java implicitly imports members of the package java.lang into every Java source file, Scala implicitly imports members of the <span style="color: #800080;">packages java.lang and scala as well as members of the singleton object named Predef</span> into every Scala source file.</li>
</ul>
<p>The println method call in the Scala example above is actually made on Predef.</p>
<ul>
<li>In Java, a public class must be in a file of the same name. In contrast, in Scala, a public class need not necessarily be in a file of the same name. Though, it is thoroughly recommended to have it in a file of the same name just to make it easier for the programmers to locate classes.</li>
</ul>
<ul>
<li>Now, lets try and run the above programs at the command prompt.</li>
</ul>
<p>Java :</p>
<pre class="brush: java; title: ; notranslate">
$ javac Main.java
$ java Main
$ Hello World
</pre>
<p>Scala:</p>
<pre class="brush: java; title: ; notranslate">
$ scalac Main.scala
$ scala Main
$ Hello World
</pre>
<p>As we can see, running the programs in the two languages is pretty similar. The output of a java compiler as well as a scala compiler is a Java class file. This class file can then run on the same JVM to produce the output</p>
<pre class="brush: java; title: ; notranslate">
$ Hello World
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/java-helloworld-vs-scala-helloworld/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
