<?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>Java Blog &#187; Core Java</title>
	<atom:link href="http://javapapers.com/category/core-java/feed/" rel="self" type="application/rss+xml" />
	<link>http://javapapers.com</link>
	<description>Blog on core java, servlets, jsp and design patterns.</description>
	<lastBuildDate>Sun, 03 Jun 2012 11:34:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Java Annotations</title>
		<link>http://javapapers.com/core-java/java-annotations/</link>
		<comments>http://javapapers.com/core-java/java-annotations/#comments</comments>
		<pubDate>Sun, 03 Jun 2012 11:15:41 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=827</guid>
		<description><![CDATA[Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too. We have basic java comments infrastructure using which we add [...]]]></description>
			<content:encoded><![CDATA[<p>Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.</p>
<p>We have basic java comments infrastructure using which we add information about the code / logic so that in future, another programmer or the same programmer can understand the code in a better way. Javadoc is an additional step over it, where we add information about the class, methods, variables in the source code. The way we need to add is organized using a syntax. Therefore, we can use a tool and parse those comments and prepare a javadoc document which can be distributed separately.</p>
<p><img class="alignright size-full wp-image-828" title="tags" src="http://javapapers.com/wp-content/uploads/2012/06/tags.jpg" alt="" width="300" height="297" /></p>
<p>Javadoc facility gives option for understanding the code in an external way, instead of opening the code the javadoc document can be used separately. IDE benefits using this javadoc as it is able to render information about the code as we develop. Annotations were introduced in <a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">JDK 1.5</a></p>
<h2>Uses of Annotations</h2>
<p>Annotations are far more powerful than java comments and javadoc comments. One main difference with annotation is it can be carried over to runtime and the other two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing.</p>
<p><img class="alignright size-full wp-image-829" title="annotation comparison" src="http://javapapers.com/wp-content/uploads/2012/06/annotationsize.png" alt="" width="300" height="342" /></p>
<p>In java we have been passing information to compiler for long. For example take <a title="Java Serialization" href="http://javapapers.com/core-java/java-serialization/">serialization</a>, we have the keyword transient to tell that this field is not serializable. Now instead of having such keywords decorating an attribute annotations provide a generic way of adding information to class/method/field/variable. This is information is meant for programmers, automated tools, java compiler and runtime. Transient is a modifier and annotations are also a kind of modifiers.</p>
<p>More than passing information, we can generate code using these annotations. Take <a title="Soap Web Service – Introduction" href="http://javapapers.com/web-service/soap-web-service-introduction/">webservices</a> where we need to adhere by the service interface contract. The skeleton can be generated using annotations automatically by a annotation parser. This avoids human errors and decreases development time as always with automation.</p>
<p>Frameworks like Hibernate, Spring, Axis make heavy use of annotations. When a language needs to be made popular one of the best thing to do is support development of frameworks based on the language. Annotation is a good step towards that and will help grow Java.</p>
<h2>When Not to Use Annotations</h2>
<ul>
<li>Do not over use annotation as it will pollute the code.</li>
<li>It is better not to try to change the behaviour of objects using annotations. There is sufficient constructs available in oops and annotation is not a better mechanism to deal with it.</li>
<li>We should not what we are parsing. Do not try to over generalize as it may complicate the underlying code. Code is the real program and annotation is meta.</li>
<li>Avoid using annotation to specify environment / application / database related information.</li>
</ul>
<h2>Annotation Structure</h2>
<p>There are two main components in annotations. First is annotation type and the next is the annotation itself which we use in the code to add meaning. Every annotation belongs to a annotation type.</p>
<p><strong> Annotation Type:</strong></p>
<pre class="brush: java;">
@interface &lt;annotation-type-name&gt; {
method declaration;
}
</pre>
<p>Annotation type is very similar to an interface with little difference.</p>
<ul>
<li>We attach &#8216;@&#8217; just before interface keyword.</li>
<li>Methods will not have parameters.</li>
<li>Methods will not have throws clause.</li>
<li>Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.</li>
<li>We can assign a default value to method.</li>
</ul>
<h2>Meta Annotations</h2>
<p>Annotations itself is meta information then what is meta annotations? As you have rightly guessed, it is information about annotation. When we annotate a annotation type then it is called meta annotation. For example, we say that this annotation can be used only for methods.</p>
<pre class="brush: java;">
@Target(ElementType.METHOD)
public @interface MethodInfo { }
</pre>
<h2>Annotation Types</h2>
<ol>
<li><strong>Documented</strong><br />
When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.</li>
<li><strong>Inherited</strong><br />
This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.</li>
<li><strong>Retention</strong><br />
This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:</p>
<pre class="brush: java;">
@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
	String value();
}
</pre>
<ul>
<li><strong>Class</strong><br />
When the annotation value is given as &#8216;class&#8217; then this annotation will be compiled and included in the class file.</li>
<li><strong>Runtime</strong><br />
The value name itself says, when the retention value is &#8216;Runtime&#8217; this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation. I have give an example below.</li>
<li><strong>Source<br />
</strong>This annotation will be removed at compile time and will not be available at compiled class.</li>
</ul>
<li><strong>Target</strong><br />
This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.</p>
<pre class="brush: java;">
@Target(ElementType.FIELD)
public @interface FieldInfo { }
</pre>
</li>
</ol>
<h2>Built-in Java Annotations</h2>
<p>@Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java.</p>
<p>Apart from these meta annotations we have the following annotations.</p>
<p><strong>@Override</strong></p>
<p>When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. This is not mandatory to use @Override when we override a method. But I have seen Eclipse IDE automatically adding this @Override annotation. Though it is not mandatory, it is considered as a best practice.</p>
<p><strong>@Deprecated</strong></p>
<p>When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning.</p>
<p><strong>@SuppressWarnings</strong></p>
<p>This is like saying, &#8220;I know what I am doing, so please shut up!&#8221; We want the compiler not to raise any warnings and then we use this annotation.</p>
<h2>Custom Annotations</h2>
<p>We can create our own annotations and use it. We need to declare a annotation type and then use the respective annotation is java classes.</p>
<p>Following is an example of custom annotation, where this annotation can be used on any element by giving values. Note that I have used @Documented meta-annotation here to say that this annotation should be parsed by javadoc.</p>
<pre class="brush: java;">
/*
 * Describes the team which wrote the code
 */
@Documented
public @interface Team {
    int    teamId();
    String teamName();
    String teamLead() default &quot;[unassigned]&quot;;
    String writeDate();    default &quot;[unimplemented]&quot;;
}
</pre>
<h3>Annotation for the Above Example Type</h3>
<pre class="brush: java;">
... a java class ...
@Team(
    teamId       = 73,
    teamName = &quot;Rambo Mambo&quot;,
    teamLead = &quot;Yo Man&quot;,
    writeDate     = &quot;3/1/2012&quot;
)
public static void readCSV(File inputFile) { ... }
... java class continues ...
</pre>
<h2>Marker Annotations</h2>
<p>We know what a marker interface is. Marker annotations are similar to marker interfaces, yes they don&#8217;t have methods / elements.</p>
<pre class="brush: java;">
/**
 * Code annotated by this team is supreme and need
 * not be unit tested - just for fun!
 */
public @interface SuperTeam { }
</pre>
<pre class="brush: java;">
... a java class ...
@SuperTeam public static void readCSV(File inputFile) { ... }
... java class continues ...
</pre>
<p>In the above see how this annotation is used. It will look like one of the modifiers for this method and also note that the parenthesis {} from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted.</p>
<h2>Single Value Annotations</h2>
<p>There is a chance that an annotation can have only one element. In such a case that element should be named value.</p>
<pre class="brush: java;">
/**
 * Developer
 */
public @interface Developer {
    String value();
}
</pre>
<pre class="brush: java;">
... a java class ...
@Developer(&quot;Popeye&quot;)
public static void readCSV(File inputFile) { ... }
... java class continues ...
</pre>
<h2>How to Parse Annotation</h2>
<p>We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation.</p>
<p><strong>Example</strong>:</p>
<pre class="brush: java;">
package com.javapapers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
	String value();
}
</pre>
<pre class="brush: java;">
package com.javapapers.annotations;
public class BuildHouse {
	@Developer (&quot;Alice&quot;)
	public void aliceMethod() {
		System.out.println(&quot;This method is written by Alice&quot;);
	}
	@Developer (&quot;Popeye&quot;)
	public void buildHouse() {
		System.out.println(&quot;This method is written by Popeye&quot;);
	}
}
</pre>
<pre class="brush: java;">
package com.javapapers.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotation {
	public static void main(String args[]) throws SecurityException,
			ClassNotFoundException {
		for (Method method : Class.forName(
				&quot;com.javapapers.annotations.BuildHouse&quot;).getMethods()) {
			// checks if there is annotation present of the given type Developer
			if (method
					.isAnnotationPresent(com.javapapers.annotations.Developer.class)) {
				try {
					// iterates all the annotations available in the method
					for (Annotation anno : method.getDeclaredAnnotations()) {
						System.out.println(&quot;Annotation in Method '&quot; + method
								+ &quot;' : &quot; + anno);
						Developer a = method.getAnnotation(Developer.class);
						if (&quot;Popeye&quot;.equals(a.value())) {
							System.out.println(&quot;Popeye the sailor man! &quot;
									+ method);
						}
					}
				} catch (Throwable ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
</pre>
<p><strong>Output</strong>:</p>
<pre class="brush: java;">
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.aliceMethod()' : @com.javapapers.annotations.Developer(value=Alice)
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.buildHouse()' : @com.javapapers.annotations.Developer(value=Popeye)
Popeye the sailor man! public void com.javapapers.annotations.BuildHouse.buildHouse()
</pre>
<h3>apt / javac for Annotation Processing</h3>
<p>In previous version of JDK apt was introduced as a tool for annotation processing. Later apt was deprecated and the capabilities are included in javac compiler. javax.annotation.processing and javax.lang.model contains the api for processing.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/java-annotations/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Top 10 Java Classes</title>
		<link>http://javapapers.com/core-java/top-10-java-classes/</link>
		<comments>http://javapapers.com/core-java/top-10-java-classes/#comments</comments>
		<pubDate>Wed, 23 May 2012 16:59:37 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=818</guid>
		<description><![CDATA[Thought of compiling a list of classes that are popular among java programmers. Should I say most essential? There is no strict rules for the selection, in fact there are no rules followed. Classes that popped up on top of mind are listed below. You are welcome to add your own list. This list will [...]]]></description>
			<content:encoded><![CDATA[<p>Thought of compiling a list of classes that are popular among java programmers. Should I say most essential? There is no strict rules for the selection, in fact there are no rules followed. Classes that popped up on top of mind are listed below. You are welcome to add your own list. This list will vary depending on the type of java project you work on. These classes I have listed does not require any introduction and they are as popular as Rajnikanth in java world. Have fun!<br />
<img class="alignright size-full wp-image-819" title="podium" src="http://javapapers.com/wp-content/uploads/2012/05/podium.jpg" alt="" width="300" height="251" /></p>
<ol>
<li><strong>java.lang.String</strong><br />
<a title="Java String" href="http://javapapers.com/core-java/java-string/">String</a> class will be the undisputed champion on any day by popularity and none will deny that. This is a final class and used to create / operate immutable string literals. It was available <a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">from JDK 1.0</a></li>
<li><strong>java.lang.System</strong><br />
Usage of <a title="System.out.println" href="http://javapapers.com/core-java/system-out-println/">System</a> depends on the type of project you work on. You may not be using it in your project but still it is one of the popular java classes around. This is a utility class and cannot be instantiated. Main uses of this class are access to standard input, output, environment variables, etc. Available since JDK 1.0</li>
<li><strong>java.lang.Exception</strong><br />
Throwable is the super class of all Errors and Exceptions. All abnormal conditions that can be handled comes under Exception. <a title="Java null and NullPointerException" href="http://javapapers.com/core-java/nullpointerexception-null-bad-good-and-ugly/">NullPointerException</a> is the most popular among all the exceptions. Exception is at top of hierarchy of all such exceptions. Available since JDK 1.0</li>
<li><strong>java.util.ArrayList</strong><br />
An implementation of array data structure. This class implements List interface and is the most popular member or java collections framework. <a title="Difference between Vector and ArrayList in java?" href="http://javapapers.com/core-java/java-collection/difference-between-vector-and-arraylist-in-java/">Difference between ArrayList and Vector</a> is one popular topic among the beginners and frequently asked question in java interviews. It was introduced in JDK 1.2</li>
<li><strong>java.util.HashMap</strong><br />
An implementation of a key-value pair data structure. This class implements Map interface. As similar to ArrayList vs Vector, we have HashMap vs <a title="Java Hashtable" href="http://javapapers.com/core-java/java-hashtable/">Hashtable </a>popular comparisons. This happens to be a popular collection class that acts as a container for property-value pairs and works as a transport agent between multiple layers of an application. It was introduced in JDK 1.2</li>
<li><strong>java.lang.Object</strong><br />
Great grandfather of all java classes. Every java class is a subclass of Object. It will be used often when we work on a platform/framework. It contains the important methods like equals, hashcode, clone, toString, etc. It is available from day one of java (JDK 1.0)</li>
<li><strong>java.lang.Thread</strong><br />
A thread is a single sequence of execution, where multiple thread can co-exist and share resources. We can extend this Thread class and create our own threads. Using Runnable is also another option. Usage of this class depends on the domain of your application. It is not absolutely necessary to build a usual application. It was available from JDK 1.0</li>
<li><strong>java.lang.Class</strong><br />
Class is a direct subclass of Object. There is no constructor in this class and their objects are loaded in JVM by <a title="Java Class Loader" href="http://javapapers.com/core-java/java-class-loader/">classloaders</a>. Most of us may not have used it directly but I think its an essential class. It is an important class in doing reflection. It is available from JDK 1.0</li>
<li><strong>java.util.Date</strong><br />
This is used to work with date. Sometimes we feel that this class should have added more utility methods and we end up creating those. Every enterprise application we create has a date utility. Introduced in JDK 1.0 and later made huge changes in JDK1.1 by deprecating a whole lot of methods.</li>
<li><strong>java.util.Iterator</strong><br />
This is an interface. It is very popular and came as a replacement for Enumeration. It is a simple to use convenience utility and works in sync with Iterable. It was introduced in JDK 1.2</li>
</ol>
<ul></ul>
<p>Did I miss your favourite?</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/top-10-java-classes/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Java Timer</title>
		<link>http://javapapers.com/core-java/java-timer/</link>
		<comments>http://javapapers.com/core-java/java-timer/#comments</comments>
		<pubDate>Sun, 20 May 2012 12:48:19 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=809</guid>
		<description><![CDATA[When there is a need to trigger a task automatically based on time we should schedule it using a timer api. The requirement can vary from a single execution on a fixed time to high complex recurring event. For example take our regular alarm clock where we fix a time and it beeps coming day [...]]]></description>
			<content:encoded><![CDATA[<p>When there is a need to trigger a task automatically based on time we should schedule it using a timer api. The requirement can vary from a single execution on a fixed time to high complex recurring event. For example take our regular alarm clock where we fix a time and it beeps coming day on the fixed time. Similarly a high complex example would be the MS outlook where we can schedule events with a different combination.</p>
<p>Following are the things in consideration</p>
<ul>
<li> When does the event starts (first time) execution  &#8211; It may be a day / date / time in future.</li>
<li> Is it a one time event or a recurring event?</li>
<li> If recurring, what is the periodicity? -</li>
<li> In recurrence there are two types, like all the events will be on a fixed time which is planned at the time of scheduling. It may be daily / weekly / monthly / yearly / a day of a week / alternate days / only working days.</li>
<li> Second type is, the recurring event can start after the completion of previous occurrence. There can be a delay between events.</li>
<li> When does it end, after a constant number of executions or after a time is reached like till Friday only.</li>
</ul>
<p><img class="alignright size-full wp-image-810" title="alarm" src="http://javapapers.com/wp-content/uploads/2012/05/alarm.png" alt="" width="300" height="416" /></p>
<p>So coming up with a nice scheduler api is a quite challenging task. You can consider this as a project for a summer. I know people will jump on and point out numerous existing apis and say why re-invent the wheel? I really hate the jargon re-inventing the wheel, its one of the most misused one. When Google came into market, there were already established players in the field like Yahoo!, Lycos, Ask Jeeves, Alta Vista. But they did a fantastic job and came to top. When you do something of good quality there is always takers for it, do not worry if it is already existing or not. But try to work towards better than the existing.</p>
<p><img class="alignright size-full wp-image-812" title="Complex Scheduler" src="http://javapapers.com/wp-content/uploads/2012/05/Complex-Scheduler1.png" alt="" width="300" height="252" /></p>
<p>Considering schedulers in java, we have the wonderful Quartz api. If we want to try something from JDK itself, in util package we have <a title="Timer API" href="http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html">Timer</a> and TimerTask and these were available from <a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">JDK 1.3</a> It is a no-nonsense, sleek and simple to use api. Comparison between this utility and Quartz would be un fair. Quartz supports trillions of possibilities and one of the most used open source schedulers. I have committed plan to write a series of articles on Quartz in future then we can explore it in detail.</p>
<h2>java.util.Timer and TimerTask</h2>
<ul>
<li>Gives facility to schedule a task for future execution in a background thread.</li>
<li>Task can be scheduled for single or recurring execution.</li>
<li>In recurrence, consecutive tasks will have regular intervals.</li>
<li>Timer has got a cancel method using which all the scheduled tasks can be cancelled.</li>
<li>Timer can be chosen to run as a daemon thread.</li>
<li>Can be scheduled to start with respect to current time using fixed-delay.</li>
<li>TimerTask is a thread handle using which we register tasks with the timer.</li>
</ul>
<h2>Important Variations</h2>
<p>This api provides two important variations that needs to be noted. </p>
<h3>Fixed-delay</h3>
<p>Each task execution is scheduled relative to the actual execution time of the previous execution. So what is actual execution? This says that, there is no guarantee that the task will be executed at the pre-planned time and it may be delayed due to garbage collection or some background activity.</p>
<p>We should also not confuse with triggering of task and completion of task. Triggering is the moment at which the Timer fires start a task. If a thread is asked to send email, it may wait for access to the resource like mail server. Only after the email is sent this task is considered to be completed. We need to have this duration in mind when we schedule recurrence tasks. If the recurrence time is shorter and already the previous task is not completed, the subsequent tasks will join the queue.</p>
<h3>Fixed-rate</h3>
<p>Here each recurring tasks are scheduled relative to the start time of the timer. If  there is any delay in execution subsequent executions will occur in quick succession to catch up with the original scheduled time. In previous case, subsequent execution will depend on just previous execution time.</p>
<p>The difference between these two can be easily observed using the below sample program by observing the output.</p>
<h2>Sample Java Timer</h2>
<pre class="brush: java;">
package com.javapapers.thread;

import java.util.Timer;

public class TimerPiano {

	Timer dingTimer;
	Timer dongTimer;

	public TimerPiano(int ding,int dong) {

		dingTimer = new Timer();
		dingTimer.schedule(new Sound(&quot;Ding!&quot;), ding * 1000, ding * 1000);
		//dingTimer.scheduleAtFixedRate(...);

		dongTimer = new Timer();
		dongTimer.schedule(new Sound(&quot;Dong!&quot;), dong * 1000, dong * 1000);
		//dongTimer.scheduleAtFixedRate(...);
	}

	public static void main(String args[]) {
		new TimerPiano(2,4);
	}
}
</pre>
<pre class="brush: java;">
package com.javapapers.thread;

import java.awt.Toolkit;
import java.util.TimerTask;

public class Sound extends TimerTask {

	Toolkit toolkit;
	String sound;

	public Sound(String sound) {
		this.sound = sound;
		//toolkit = Toolkit.getDefaultToolkit();
	}

	public void run() {
		System.out.println(sound);
		//toolkit.beep();
	}
}
</pre>
<ul>
<li>If you want to hear cool sound, un-comment the toolkit line.</li>
<li>I have not cancelled the tasks and it will keep on running till you force close.</li>
<li>Replace &#8216;schedule&#8217; with scheduleAtFixedRate to observe different behaviour.</li>
</ul>
<p>ScheduledExecutorService is a latest api available from JDK 1.5 onwards and we can see about that in a coming article.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/java-timer/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>System.out.println</title>
		<link>http://javapapers.com/core-java/system-out-println/</link>
		<comments>http://javapapers.com/core-java/system-out-println/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 13:44:02 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=787</guid>
		<description><![CDATA[It is love at first type. I fell in deep love with it from the first moment I used it. Didn&#8217;t you? How many times have we used it till now? It is one of the most number of times compiled statement in the history of java. We fondly call it SOP. If you want [...]]]></description>
			<content:encoded><![CDATA[<p>It is love at first type. I fell in deep love with it from the first moment I used it. Didn&#8217;t you? How many times have we used it till now? It is one of the most number of times compiled statement in the<a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/"> history of java</a>. We fondly call it SOP. If you want to dive directly to topic, jump to the first heading.</p>
<p>I first<a title="About Me" href="http://javapapers.com/about-me/"> learnt DBase III+</a> and the statement to print is <code>? "Hello World"</code>. Then I went on to to study umpteen number of languages courtesy a poorly planned curriculum. Instead, we should have spent more time on flip-flops.</p>
<p>At the end of this article I have summarized Pascal, C, C++, Lisp, Prolog, Cobol, Basic, Fortran &#8211; I studied all these in a 3 year post graduate program and more than that. As I told, I am still not sure of the difference it made. Learning multiple languages is good, but my humble opinion is, do it after spending more time on fundamentals like data structures, algorithms, discrete maths, computer architecture, etc. Okay, where did I left? Lets continue with our System.out.println for now.<br />
<img class="alignright size-full wp-image-788" title="sop" src="http://javapapers.com/wp-content/uploads/2012/04/sop.jpg" alt="" width="300" height="273" /></p>
<h2>What is System.out.println</h2>
<p>System.out.println prints the argument passed, into the System.out which is generally stdout.</p>
<ul>
<li>System &#8211; is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be <a title="Java Static" href="http://javapapers.com/core-java/explain-the-java-static-modifier/">static </a>and we understand that it is an utility class. As per javadoc, &#8220;&#8230;Among the facilities provided by the <code>System</code> class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an <a title="Java Array" href="http://javapapers.com/core-java/java-array/">array</a>&#8230;&#8221;</li>
<li>out &#8211; is a static member field of <a title="System API" href="http://docs.oracle.com/javase/6/docs/api/java/lang/System.html" target="_blank">System </a>class and is of type <a title="PrintStream API" href="http://docs.oracle.com/javase/1.3/docs/api/java/io/PrintStream.html" target="_blank">PrintStream</a>. Its<a title="Access Modifiers In Java" href="http://javapapers.com/core-java/access-modifiers-in-java-explain/"> access specifiers </a>are public <a title="Java Final Keyword" href="http://javapapers.com/core-java/explain-the-final-keyword-in-java/">final</a>. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data. When running a program from windows command line, it is the standard console.</li>
<li>println &#8211; println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (<a title="Overloading vs Overriding" href="http://javapapers.com/core-java/overloading-and-overriding/">overloading</a>). Every println makes a call to <code>print</code> method and adds a newline. <code>print</code> calls <code>write()</code> and the story goes on like that.</li>
</ul>
<p><img class="alignright size-full wp-image-789" title="System" src="http://javapapers.com/wp-content/uploads/2012/04/System.png" alt="" width="405" height="273" /></p>
<h2>Change out of System.out.println</h2>
<p>&#8216;out&#8217; object can be customized. out gets initialized by <a title="Differentiate JVM JRE JDK JIT" href="http://javapapers.com/core-java/differentiate-jvm-jre-jdk-jit/">java runtime environment </a>at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior using <code>setOut</code> method as below. In the following example, I have redirected the output to a text file in the same directory.</p>
<pre class="brush: java;">
public class ChangeOut {
	public static void main(String args[]) {
		try {
			System.setOut(new PrintStream(new FileOutputStream(&quot;log.txt&quot;)));
			System.out.println(&quot;Now the output is redirected!&quot;);
		} catch(Exception e) {}
	}
}
</pre>
<h2>System.out.println vs loggers like Log4j</h2>
<p>Log4J has mulitple levels for logging. If we are writing a real short program, just for experimental/learning purposes SOPs are fine. When we are developing a production quality software project, we should be aware that a professional logger should be used and SOPs should be avoided. Why?</p>
<ul>
<li>Flexibility: a professional logger like<a title="Log4J Levels" href="http://javapapers.com/log4j/log4j-levels/"> log4j provides different levels </a>for logging. We can seggregate the log message accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.</li>
<li>Configurability: in just one parameter change we can switch off all the logging statements.</li>
<li>Maintainability: imagine if we have hundreds of SOPs littered all through the application, it would be difficult to maintain the program over a period.</li>
<li>Granularity: In an application, every single class can have a different logger and controlled accordingly.</li>
<li>Utility: Option for redirecting the message is limited in System.out, but in case of a logger you have appenders which provides numerous options. We can even create a custom ouput option and redirect it to that.</li>
</ul>
<blockquote><p>Having said all the above, we still use System.out.println for logging and debugging. Which should be strictly avoided. This is driven by (bad)habit. I want to share how a habit became a convention. In this case its a good habit. Its using &#8216;i&#8217;, &#8216;j&#8217; as index in for-loop. In FORTRAN language, we need not declare integer variables. Variable names that start with i, j, k, l, m and n are integer variables. So, FORTRAN developers named for-loop index with i,j,k and that habit carried on to other languages. Just a habit and became a good convention!</p></blockquote>
<h2>System.out.println and Performance</h2>
<p>There is a general notion that SOPs are bad in performance. When we analyze deeply, the sequence of calls are like println -&gt; print -&gt; write() + newLine(). This sequence flow is an implementation of Sun/Oracle JDK. Both write() and newLine() contains a <code>synchronized</code> block. Synchronization has a little overhead, but more than that the cost of adding characters to the buffer and printing is high.</p>
<p>When we run a performance analysis, run multiple number of SOP and record the time, the execution duration increases proportionally. Performance degrades when we print more that 50 characters and print more than 50,000 lines.</p>
<p>It all depends on the scenario we use it. Whatever may be the case, do not use System.out.println for logging to stdout.</p>
<h2>Static Import to Shorten SOP</h2>
<p>Someone complained that System.out.println is a loooong statement to print something. <a href="http://javapapers.com/core-java/what-is-a-static-import-in-java/">static import </a>may shorten it a bit but it is not recommended, because it results in poor readability. I am just using this situation to explain static import and avoid using it in the below scenario.</p>
<pre class="brush: java;">
import static java.lang.System.out;

public class ShortSOP {
public static void main(String[] args) {
out.println(&quot;Hello, world&quot;);
}
}
</pre>
<p>In Eclipse you have programmed <a title="Eclipse Shortcuts" href="http://javapapers.com/core-java/eclipse-shortcuts/">shortcuts </a>like ctrl + spac to help you out.</p>
<h2>System.err and System.in</h2>
<p>As a related section, I wish to discuss about &#8216;err&#8217; and &#8216;in&#8217;. &#8216;in&#8217; is associated with InputStream. Opposite to &#8216;out&#8217;, &#8216;in&#8217; is used to get input from standard console generally keyboard.<br />
&#8216;err&#8217; is associated with PrintStream and prints the argument to the standard error output stream. When you use eclipse kind of IDE you can see the differene in ouput between &#8216;out&#8217; and &#8216;err&#8217;.</p>
<pre class="brush: java;">
public class InOutErr {
public static void main(String args[]) {
try {

BufferedReader reader = new BufferedReader(System.in);
String filename = reader.readLine();

  InputStream input = new FileInputStream(filename);
  System.out.println(&quot;File opened...&quot;);

} catch (IOException e){
  System.err.println(&quot;Where is that file?&quot;);
}
}
}
</pre>
<h2>Print in other languages</h2>
<p>DBASE III+<br />
<code>? "Hello World"</code></p>
<p>C</p>
<pre class="brush: plain;">
 #include &lt;stdio.h&gt;
 #include &lt;stdlib.h&gt;

 int main(void)
 {
  printf(&quot;Hello, world&quot;);
  return EXIT_SUCCESS;
 }
</pre>
<p>CPP</p>
<pre class="brush: plain;">
 #include &lt;iostream&gt;

 int main()
 {
 	std::cout &lt;&lt; &quot;Hello, World.&quot; &lt;&lt; std::endl;
 }
</pre>
<p>BASIC</p>
<pre class="brush: plain;">
10 PRINT &quot;HELLO WORLD&quot;
</pre>
<p>FORTRAN</p>
<pre class="brush: plain;">
 PROGRAM HELLOWORLD
 10 FORMAT (1X,11HHELLO WORLD)
 WRITE(6,10)
 END
</pre>
<p>COBOL</p>
<pre class="brush: plain;">
 IDENTIFICATION DIVISION.
 PROGRAM-ID. Hello.
 ENVIRONMENT DIVISION.
 DATA DIVISION.
 PROCEDURE DIVISION.
	Display 'Hello, World'.
	STOP RUN.
</pre>
<p>LISP</p>
<pre class="brush: plain;">
	(DEFUN HELLO-WORLD ()
	(PRINT (LIST 'HELLO 'WORLD)))
</pre>
<p>PROLOG</p>
<pre class="brush: plain;">
go :-
	writeln('Hello World').
</pre>
<p>Yes, I sourced all this programs from Internet :-) How come you expect me to remember all these! System.out.println(&#8220;Bye&#8221;);</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/system-out-println/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>ThreadLocal</title>
		<link>http://javapapers.com/core-java/threadlocal/</link>
		<comments>http://javapapers.com/core-java/threadlocal/#comments</comments>
		<pubDate>Sun, 22 Apr 2012 17:30:20 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=780</guid>
		<description><![CDATA[Core concept of ThreadLocal is, &#8220;every thread that accesses a ThreadLocal variable via its get or set method has its own, independently initialized copy of the variable&#8221;. In other words, we want to have separate instances(private copy) of a class so that there will not be any conflict among multiple threads. Each instance will be [...]]]></description>
			<content:encoded><![CDATA[<p>Core concept of ThreadLocal is, &#8220;every thread that accesses a ThreadLocal variable via its get or set method has its own, independently initialized copy of the variable&#8221;.</p>
<ul>
<li>In other words, we want to have separate instances(private copy) of a class so that there will not be any conflict among multiple threads. Each instance will be unique for each thread. This is nothing but a way of implementing threadsafety.</li>
<li>An important point about ThreadLocal variable is the global access. It can be accessed from anywhere inside the thread. Also note that, it is declared <a title="Java Static" href="http://javapapers.com/core-java/explain-the-java-static-modifier/">static</a> and <a title="Java Final Keyword" href="http://javapapers.com/core-java/explain-the-final-keyword-in-java/">final</a>.</li>
</ul>
<h2>What is threadsafe?</h2>
<p>A thread is a single line of process. When we refer multi-threaded applications, we mean that there mulitple (sequential flow of control) line of process that runs through the same lines of code. In such situation, there is a possibility of one sequence(thread) accessing/modifying data of other sequence(thread). When data cannot be shared like this, then we make it threadsafe. Following are the some of the different ways of implementing threadsafe operation:</p>
<ul>
<li>Re-entrancy</li>
<li>Mutual exclusion (synchronization)</li>
<li>Thread-local</li>
<li>Atomic operation</li>
</ul>
<p>So, in the above list Thread-local is one option. Hope now we get how ThreadLocal fits in the cube.</p>
<p><img class="alignright size-full wp-image-781" title="ThreadLocal" src="http://javapapers.com/wp-content/uploads/2012/04/ThreadLocal.jpg" alt="" width="300" height="225" /></p>
<h2>Uses of ThreadLocal</h2>
<p>I cannot resist but quote Joshua Bloch (who better I can choose for this section),<br />
in his own words:</p>
<ul>
<li>Genuine per-thread context, such as user id or transaction id. Works great. Easy to clean up when the thread exits the scope. No leaks.</li>
<li>Per-thread instances for performance.</li>
<li>&#8220;Sleazing&#8221; values through callbacks that you don&#8217;t control: sometimes you must call a library method that calls back into your package.  At this point, you need some context that you were unable to pass to yourself, due to deficiencies in the library.  In this rare situation, thread locals can be a lifesaver.</li>
</ul>
<p>Above points, in my own terms: We have an object that is not threadsafe and we want to use it safely. We go for synchronization by enclosing that object in synchronized block. Other way around is using ThreadSafe, what it does is holds separate instance for each thread and makes it safe.</p>
<h2>Example for ThreadLocal</h2>
<pre class="brush: java;">
package com.javapapers;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadLocalExample {
	private static final ThreadLocal&lt;SimpleDateFormat&gt; formatter = new ThreadLocal&lt;SimpleDateFormat&gt;() {

		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat(&quot;yyyyMMdd HHmm&quot;);
		}
	};

	public String formatIt(Date date) {
		return formatter.get().format(date);
	}
}
</pre>
<p>In the above sample code, get() method is key to understanding. It returns the value in the current thread&#8217;s copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue method.</p>
<h3>Example from javadoc</h3>
<p>The class below generates unique identifiers local to each thread. A thread&#8217;s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.</p>
<pre class="brush: java;">
 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal&lt;Integer&gt; threadId =
         new ThreadLocal&lt;Integer&gt;() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }
</pre>
<h2>Use of ThreadLocal in Java API</h2>
<p><a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">In JDK 1.7</a> we have got a new class namely ThreadLocalRandom. It can be used to generate random numbers specific to parallel threads. Seed for random number will be unique for each thread. This is a real cool utility.</p>
<p>Following is the code that implements ThreadLocal in the above class:</p>
<pre class="brush: java;">
    private static final ThreadLocal&lt;ThreadLocalRandom&gt; localRandom =
        new ThreadLocal&lt;ThreadLocalRandom&gt;() {
            protected ThreadLocalRandom initialValue() {
                return new ThreadLocalRandom();
            }
    };
</pre>
<h3>Example using ThreadLocalRandom</h3>
<pre class="brush: java;">
package com.javapapers;

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {

	public static void main(String args[]) throws InterruptedException {

		//tossing 3 coins
		for (int i = 0; i &lt; 3; i++) {
			final Thread thread = new Thread() {

				public void run() {
					System.out.print(Thread.currentThread().getName() + &quot;:&quot;);

					// generating 3 random numbers - random for every thread
					for (int j = 0; j &lt; 3; j++) {
						final int random = ThreadLocalRandom.current().nextInt(
								1, 3);
						System.out.print(random + &quot;,&quot;);
					}
					System.out.println();
				}
			};
			thread.start();
			thread.join();
		}
	}
}
</pre>
<h2>ThreadLocal and Memory Leaks</h2>
<p>ThreadLocal is not evil, it is a nice utility API. It all depends on how we use it. We should learn to choose the right tool for the right situation. We cannot use cannons to burst mosquitoes, but do not blame the cannons.</p>
<p>There are strong complaints all over the web saying ThreadLocals will cause <a title="Java (JVM) Memory Types" href="http://javapapers.com/core-java/java-jvm-memory-types/">memory </a>leaks. &#8216;Mostly&#8217; No!</p>
<p>I wish to <a href="http://old.nabble.com/Re%3A-Threadlocals-and-memory-leaks-in-J2EE-p13109918.html" target="_blank">quote Joshua Bloch</a>,</p>
<blockquote><p>&#8220;&#8230;There is nothing inherently wrong with thread locals: They do not cause memory leaks. They are not slow. They are more local than their non-thread-local counterparts (i.e., they have better information hiding properties).  They can be misused, of course, but so can most other programming tools&#8230;.&#8221;</p></blockquote>
<p>Why &#8216;Mostly&#8217; No? &#8211; In case of &#8216;self-referential structures&#8217;, there is a memory leak. Refer the <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6254531" target="_blank">bug_id 6254531</a></p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/threadlocal/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Java Iterator</title>
		<link>http://javapapers.com/core-java/java-iterator/</link>
		<comments>http://javapapers.com/core-java/java-iterator/#comments</comments>
		<pubDate>Sun, 18 Mar 2012 17:36:32 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=757</guid>
		<description><![CDATA[To generate successive elements from a series, we can use java iterator. It is an improvement over Enumeration interface. Iterator takes the place of Enumeration since jdk 1.2 It is a nice utility for collections. Every collection is unique on its own and imagine if we have have to write logic on our own for [...]]]></description>
			<content:encoded><![CDATA[<p>To generate successive elements from a series, we can use java iterator. It is an improvement over Enumeration interface. Iterator takes the place of Enumeration <a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">since jdk 1.2</a></p>
<p>It is a nice utility for collections. Every collection is unique on its own and imagine if we have have to write logic on our own for every collection when there is a need to iterate it. Instead, java forces a collection to deliver an iterator.</p>
<p>These nice utilities makes java lovable, isn&#8217;t it?</p>
<p>Important points to note:</p>
<ul>
<li>We can iterate only in one direction</li>
<li>Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator.</li>
</ul>
<p><img class="alignright size-full wp-image-758" title="iterator" src="http://javapapers.com/wp-content/uploads/2012/03/iterator.jpg" alt="" width="250" height="187" /></p>
<h2>Iterator Example without Generics</h2>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;
import java.util.Iterator;

public class ExampleIterator {

	public static void main(String args[]){
		ArrayList animal = new ArrayList();
		animal.add(&quot;Horse&quot;);
		animal.add(&quot;Lion&quot;);
		animal.add(&quot;Tiger&quot;);

		Iterator animalItr = animal.iterator();

		while(animalItr.hasNext()) {
			String animalObj = (String)animalItr.next();
			System.out.println(animalObj);
		}
	}

}
</pre>
<p>Without generics, Iterator returns the Object and we need to typecast it.</p>
<h2>Iterator Example using Generics</h2>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;

public class ExampleIterator {

	public static void main(String args[]){
		ArrayList&lt;String&gt; animal = new ArrayList&lt;String&gt;();
		animal.add(&quot;Horse&quot;);
		animal.add(&quot;Lion&quot;);
		animal.add(&quot;Tiger&quot;);

		for(String animalObj : animal) {
			System.out.println(animalObj);
		}
	}

}
</pre>
<p>Output:<br />
Horse<br />
Lion<br />
Tiger</p>
<p>Look how simple it is. There is no reference to the Iterator explicitly since we are using for-each of generics.</p>
<h2>Iterable and Iterator</h2>
<p>To make an object iterable it needs to emit an <a title="Iterator Java API" href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html">Iterator</a> object. To enforce this contract, Iterator interface is to be used. It contains a method named iterator() and it returns Iterator. Hence, any class that implements Iterable will return an Iterator.</p>
<pre class="brush: java;">
public interface Collection&lt;E&gt; extends Iterable&lt;E&gt; {
</pre>
<p>For example take any Collection. A Collection is an interface that represents container for series of elements. Every collections like ArrayList, Vector implements Collection and so Iterator.</p>
<ul>
<li>One advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.</li>
</ul>
<h2>Removing elements using Iterator</h2>
<ul>
<li>Iterator has a remove method using which we can delete elements from the underlying object.</li>
<li>It removes the last element returned by the iterator.</li>
</ul>
<h2>Difference between Iterator and Enumeration interfaces</h2>
<ol>
<li>remove() method is introduced in iterator. Using this method we can remove element from the underlying collection which we are iterating.</li>
<li>Enumeration has two methods and both are available in iterator. Method names for both of them are shortened.</li>
</ol>
<p>ListIterator an even better Iterator for a List containing more utility methods like getting index of elements and adding elements to the base object. Using ListIterator we can iterate in both the directions.</p>
<h2>ConcurrentModificationException</h2>
<p>Look at the following code, it throws ConcurrentModificationException. We cannot add or remove elements to the underlying collection when we are using an iterator.</p>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;

public class ExampleIterator {

	public static void main(String args[]){
		ArrayList&lt;String&gt; animal = new ArrayList&lt;String&gt;();
		animal.add(&quot;Horse&quot;);
		animal.add(&quot;Lion&quot;);
		animal.add(&quot;Tiger&quot;);

		for(String animalObj : animal) {
			System.out.println(animalObj);
			animal.add(&quot;Hyena&quot;);
		}
	}
}

Output:
Horse
Exception in thread &quot;main&quot; java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
	at java.util.ArrayList$Itr.next(Unknown Source)
	at com.javapapers.ExampleIterator.main(ExampleIterator.java:13)
</pre>
<h2>Implementing our own Custom Iterator</h2>
<p>We will create our own custom class and make it implement Iterable, so that it returns an Iterator using which we can iterate the elements.</p>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;
import java.util.Iterator;

public class AnimalIterator&lt;String&gt; implements Iterator&lt;Object&gt; {

	private ArrayList&lt;?&gt; animal;
	private int position;

	public AnimalIterator(Animal animalBase) {
		this.animal = animalBase.getAnimal();
	}

	@Override
	public boolean hasNext() {
		if (position &lt; animal.size())
			return true;
		else
			return false;
	}

	@Override
	public Object next() {
		Object aniObj = animal.get(position);
		position++;
		return aniObj;
	}

	@Override
	public void remove() {
		animal.remove(position);
	}

}
</pre>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;
import java.util.Iterator;

public class Animal implements Iterable&lt;String&gt; {

	private ArrayList&lt;String&gt; animal = new ArrayList&lt;String&gt;();

	public Animal(ArrayList animal){
		this.animal = animal;
	}

	public ArrayList getAnimal() {
		return animal;
	}

	@Override
	public Iterator&lt;String&gt; iterator() {
		return new AnimalIterator(this);
	}

}
</pre>
<pre class="brush: java;">
package com.javapapers;

import java.util.ArrayList;

public class TestIterator {

	public static void main(String args[]) {
		ArrayList&lt;String&gt; animalList = new ArrayList();
		animalList.add(&quot;Horse&quot;);
		animalList.add(&quot;Lion&quot;);
		animalList.add(&quot;Tiger&quot;);
		Animal animal = new Animal(animalList);
		for (String animalObj : animal) {
			System.out.println(animalObj);
		}
	}
}
</pre>
<p>Output:<br />
Horse<br />
Lion<br />
Tiger</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/java-iterator/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
	</channel>
</rss>

