<?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; Christy</title>
	<atom:link href="http://www.javabeat.net/author/christy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +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>Knowing about your Database</title>
		<link>http://www.javabeat.net/2007/10/knowing-about-your-database/</link>
		<comments>http://www.javabeat.net/2007/10/knowing-about-your-database/#comments</comments>
		<pubDate>Fri, 26 Oct 2007 02:17:51 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=78</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 use the Jdbc APIs for accessing the data from the database system. However, the different databases from different vendors will vary a lot in their underlying model and functionalities. For example, a feature supported in one database might not be supported in another database. So, even before working with a database, it is important [...]</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 align="justify">
We use the Jdbc APIs for accessing the data from the database system. However, the different databases from different vendors will vary a lot in their underlying model and functionalities. For example, a feature supported in one database might not be supported in another database. So, even before working with a database, it is important to know the supported features and other related information. Java provides an interface called <code>DatabaseMetaData</code> to achieve this.
</p>
<p align="justify">
The implementation for this interface will give the Driver vendor itself and the information obtained from this interface will help both the Tool Vendors and Application Developers. Let us see how to get a reference to this interface,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Class.forName(&amp;quot;sun.jdbc.odbc.JdbcOdbcDriver&amp;quot;);
Connection connection = DriverManager.getConnection(&quot;jdbc:odbcEmployeeDS&quot;);
DatabaseMetaData metadata  = connection.getMetaData();</pre></td></tr></table></div>

</p>
<p align="justify">
Now, let us see how to make use of this metadata interface to get information about the database. Consider the following code snippet which prints the product name and version information related to a database.
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">System.out.println(metaData.getDatabaseProductName());
System.out.println(metaData.getDatabaseProductVersion());
System.out.println(metaData.getDatabaseMajorVersion());
System.out.println(metaData.getDatabaseMinorVersion());</pre></td></tr></table></div>

</p>
<p align="justify">
It is important to understand that the methods may or may not support the requested operation. Say, for example, if a particular database doesn&#8217;t have the notion of minor or major version for its product, then they possibly return null or may throw <code>UnsupportedOperationException</code> at the run-time.
</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 align="justify">
This metadata interface has a huge list of <code>&quot;supports*&quot;</code> method to check whether a particular feature or an operation is supported by the database. For example, consider the following code snippet,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">System.out.println(metaData.supportsAlterTableWithDropColumn());
System.out.println(metaData.supportsColumnAliasing());
System.out.println(metaData.supportsGroupBy());
System.out.println(metaData.supportsTransactions());
System.out.println(metaData.supportsMultipleTransactions());
System.out.println(metaData.supportsOuterJoins());
System.out.println(metaData.supportsSavepoints());</pre></td></tr></table></div>

</p>
<p align="justify">
The first statement will return true if the database supports dropping of a column while making modifications to the table structure. The second statement returns true if the column names are referred through multiple identifiers, which is called as column aliasing. The third one will return true if the GROUP BY clause can be used in SQL query. The fourth and the fifth statements are related to supporting single and multiple transactions. The seventh statement will return true if outer joins can be mentioned in a query. And the final statement returns true if the database supports save points which refers to some point in a database session, after which all the statements can be committed or can be roll backed.
</p>
<p align="justify">
In this section, we have discussed only a very few methods as there are so may methods available in this interface. To know about this in detail, it is advised to have a glance over the Java documentation.</p>
<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%2Fauthor%2Fchristy%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/author/christy/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/author/christy/feed/" data-count="vertical" data-text="" 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/2007/10/knowing-about-your-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customizing Dragging and Dropping for Swing Components</title>
		<link>http://www.javabeat.net/2007/10/customizing-dragging-and-dropping-for-swing-components/</link>
		<comments>http://www.javabeat.net/2007/10/customizing-dragging-and-dropping-for-swing-components/#comments</comments>
		<pubDate>Fri, 26 Oct 2007 02:17:12 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=76</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>Swing&#8217;s Drop and Drop API can be used for customizing Drag and Drop support. For most of the commonly used components like Text Components, Color Chooser, File Chooser etc, the dropping support is enabled by default. We have to explicitly enable the dragging support by calling the setDragEnabled() method. Before getting into customizing them, let [...]</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 align="justify">
<i><b>Swing&#8217;s Drop and Drop API</b></i> can be used for customizing Drag and Drop support. For most of the commonly used components like Text Components, Color Chooser, File Chooser etc, the dropping support is enabled by default. We have to explicitly enable the dragging support by calling the <code>setDragEnabled()</code> method. Before getting into customizing them, let us see a simple example,
</p>
<p>
<b>SimpleDragAndDrop.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.swing.dnd;
&nbsp;
import java.awt.FlowLayout;
&nbsp;
import javax.swing.*;
&nbsp;
public class SimpleDragAndDrop {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        JFrame frame = new JFrame(&amp;quot;Drag and Drop Demo&amp;quot;);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
&nbsp;
        JTextField source = new JTextField(&amp;quot;Type some text here&amp;quot;);
        source.setDragEnabled(true);
        JTextField destination = new JTextField(18);
        destination.setDragEnabled(true);
&nbsp;
        frame.setLayout(new FlowLayout());
&nbsp;
        frame.getContentPane().add(source);
        frame.getContentPane().add(destination);
&nbsp;
        frame.setSize(500, 500);
        frame.pack();
        frame.setVisible(true);
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
When you run the above program, two text-fields will be presented, and it is now possible to drag the text from one text-field to the other text-field and vice-versa. Now, let us see how this can be customized. By default, an implicit transfer handler is set for the components that provides this drag and drop functionality. For text components, this implicit transfer handler transfers the text from the source to the destination. Now, have a look at the following code that replaces the implicit transfer handler with a custom one.
</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>CustomizedDragAndDrop.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.swing.dnd;
&nbsp;
import java.awt.*;
&nbsp;
import javax.swing.*;
&nbsp;
public class CustomizedDragAndDrop {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        JFrame frame = new JFrame(&quot;Drag and Drop Demo&quot;);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
&nbsp;
        JTextField source = new JTextField(&quot;Some text here&quot;);
        source.setDragEnabled(true);
        source.setBackground(Color.RED);
        source.setForeground(Color.BLUE);
        source.setTransferHandler(new TransferHandler(&quot;foreground&quot;));
&nbsp;
        JTextField destination = new JTextField(&quot;Some text here&quot;);
        destination.setDragEnabled(true);
        destination.setBackground(Color.RED);
        destination.setForeground(Color.BLUE);
        destination.setTransferHandler(new TransferHandler(&amp;quot;background&amp;quot;));
&nbsp;
        frame.setLayout(new FlowLayout());
&nbsp;
        frame.getContentPane().add(source);
        frame.getContentPane().add(destination);
&nbsp;
        frame.setSize(500, 500);
        frame.pack();
        frame.setVisible(true);
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
In the above code, we have explicitly called the <code>setTransferHandler()</code> method, by passing an new <code>TransferHandler</code> object along with a java bean property name. For the source text field, a java bean property called <code>foreground</code> is passed and for the second one, the java bean property is <code>background</code>. Now, when an attempt is made for transferring the content, instead of the text being transferred, the color is transferred between the text components.</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/2007/10/customizing-dragging-and-dropping-for-swing-components/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Locking Files using Java</title>
		<link>http://www.javabeat.net/2007/10/locking-files-using-java/</link>
		<comments>http://www.javabeat.net/2007/10/locking-files-using-java/#comments</comments>
		<pubDate>Fri, 26 Oct 2007 02:16:37 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=74</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>File Locking can be achieved in java by making use of the New I/O API (nio). Before the advent of New I/O API, there was no direct support in Java for locking a file. It is important to understand that File locking is hugely dependent on the native operating system on which the program 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 align="justify">
File Locking can be achieved in java by making use of the <i><b>New I/O API (nio)</b></i>. Before the advent of New I/O API, there was no direct support in Java for locking a file. It is important to understand that File locking is hugely dependent on the native operating system on which the program is executing.
</p>
<p align="justify">
File Locks can either be <i><b>exclusive</b></i> or <i><b>shared</b></i>. An exclusive lock can be acquired on a file only if there are no processes or applications accessing the file. It is possible for one or more processes to have any number of locks on the same file but in different region of a file in the case of a shared lock. Some operating systems doesn&#8217;t support the concept of shared locking.
</p>
<p align="justify">
Java provides <code>lock()</code> and <code>tryLock()</code> methods in <code>FileChannel</code> class for getting a lock over the file object. Whether the lock is an exclusive lock or a shared lock depends on the flavor of the methods taking arguments which represents the region of the file to be locked. The method <code>lock()</code> blocks execution until it gets a lock whereas the method <code>tryLock()</code> doesn&#8217;t block and returns immediately. If a lock cannot be cannot be acquired on a file, then the <code>tryLock()</code> method will return null.
</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>FileLockTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.javabeat.nio.lock;
&nbsp;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
&nbsp;
public class FileLockTest {
&nbsp;
    public static void main(String[] args) throws Exception {
&nbsp;
        RandomAccessFile file = null;
        FileLock fileLock = null;
        try
        {
            file = new RandomAccessFile(&quot;FileToBeLocked&quot;, &quot;rw&quot;);
            FileChannel fileChannel = file.getChannel();
&nbsp;
            fileLock = fileChannel.tryLock();
            if (fileLock != null){
                System.out.println(&quot;File is locked&quot;);
                accessTheLockedFile();
            }
        }finally{
            if (fileLock != null){
                fileLock.release();
            }
        }
    }
&nbsp;
    static void accessTheLockedFile(){
&nbsp;
        try{
            FileInputStream input = new FileInputStream(&quot;FileToBeLocked&quot;);
            int data = input.read();
            System.out.println(data);
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
The above program tries to lock a file called &#8220;FileToBeLocked&#8221; by calling the <code>lock()</code> method on the associated File Channel object. The <code>lock()</code> method blocks the thread until it gets a lock on the file. Then, in order to ensure that the file is locked, the method <code>accessTheLockedFile()</code> is called which tries to read the file contents. Since the lock acquired is an exclusive lock, an IOException is thrown.</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/2007/10/locking-files-using-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Precise rounding of decimals using Rounding Mode Enumeration</title>
		<link>http://www.javabeat.net/2007/10/precise-rounding-of-decimals-using-rounding-mode-enumeration/</link>
		<comments>http://www.javabeat.net/2007/10/precise-rounding-of-decimals-using-rounding-mode-enumeration/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:15:52 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=72</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>The Rounding Mode Enum in java.math package is used to perform precise rounding of decimal values. It was introduced in Java 5.0. This Enum provides various constants each of which is used for different modes of rounding. The decimal value would be rounded off to the number of decimal places based on the scale that [...]</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 align="justify">
The Rounding Mode Enum in <code>java.math</code> package is used to perform precise rounding of decimal values. It was introduced in Java 5.0.<br />
This Enum provides various constants each of which is used for different modes  of rounding. The decimal value would be rounded off to the number of decimal places based on the scale that is defined for the decimal value.
</p>
<p align="justify">
The Rounding Mode Enum constants are <i><b>UP</b></i>, <i><b>DOWN</b></i>, <i><b>CEILING</b></i>, <i><b>FLOOR</b></i>, <i><b>HALF_DOWN</b></i>, <i><b>HALF_EVEN</b></i>, <i><b>HALF_UP</b></i>, and <i><b>UNNECESSARY</b></i>.
</p>
<p align="justify">
<h2>UP</h2>
</p>
<p align="justify">
This rounds off any given decimal value away from zero. It basically increments the decimal value. Let us see a simple example,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.3&quot;);
value = value.setScale(0, RoundingMode.UP);
BigDecimal value1 = new BigDecimal(&quot;-2.3&quot;);
value1 = value1.setScale(0, RoundingMode.UP);
System.out.println(value + &quot;n&quot; + value1);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">3
-3</pre></td></tr></table></div>

</p>
<p align="justify">
In this example, we have specified the scale as 0. Hence, the rounded value does not have any decimal places.
</p>
<p><h2>DOWN</h2>
</p>
<p align="justify">
This rounds off any given decimal value towards zero. It does not increment the value. Let us see a simple example,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.3&quot;);
value = value.setScale(0, RoundingMode.DOWN);
BigDecimal value1 = new BigDecimal(&quot;-2.3&quot;);
value1 = value1.setScale(0, RoundingMode.DOWN);
System.out.println(value + &quot;n&quot; + value1);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2
-2</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>CEILING</h2>
</p>
<p align="justify">
It rounds off any decimal value towards positive infinity. For a positive decimal, it performs the same rounding  as  RoundingMode.UP. In case of a negative decimal, it performs the same rounding  as  as for RoundingMode.DOWN. It does not decrement the value. Let us see a sample,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.3&quot;);
value = value.setScale(0, RoundingMode.CEILING);
BigDecimal value1 = new BigDecimal(&quot;-2.3&quot;);
value1 = value1.setScale(0, RoundingMode.CEILING);
System.out.println(value + &quot;n&quot; + value1);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">3
2</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>FLOOR</h2>
</p>
<p align="justify">
It rounds off any decimal value towards negative infinity. For a positive decimal, it performs the same rounding  as  RoundingMode.DOWN. In case of a negative decimal, it performs the same rounding  as  as for RoundingMode.UP. It does not increment the value. Let us see a sample that illustrates this,
</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>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.3&quot;);
value = value.setScale(0, RoundingMode.FLOOR);
BigDecimal value1 = new BigDecimal(&quot;-2.3&quot;);
value1 = value1.setScale(0, RoundingMode.FLOOR);
System.out.println(value + &quot;n&quot; + value1);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2
-3</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>HALF_UP</h2>
</p>
<p align="justify">
This rounds off a  decimal value towards the nearest neighbouring value apart from the case when both neighbouring values are equidistant, in which case it just rounds up the value. It performs the same rounding as RoundingMode.UP if the discarded fractional part is &gt;= 0.5, else it performs the same rounding as RoundingMode.DOWN. Let us see a sample that illustrates this,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.4&quot;);
value = value.setScale(0, RoundingMode.HALF_UP);
BigDecimal value1 = new BigDecimal(&quot;2.5&quot;);
value1 = value1.setScale(0, RoundingMode.HALF_UP);
BigDecimal value2 = new BigDecimal(&quot;2.6&quot;);
value2 = value2.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + &quot;n&quot; + value1 + &quot;n&quot; + value2);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of this code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2
3
3</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>
<h2>HALF_DOWN</h2>
</h2>
<p align="justify">
This rounds off a  decimal value towards the nearest neighbouring value apart from the case when both neighbouring values are equidistant, in which case it just rounds down the value. It performs the same rounding as RoundingMode.DOWN if the discarded fractional part is &gt; 0.5, else it performs the same rounding as RoundingMode.UP. Let us see an example for this,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.4&quot;);
value = value.setScale(0, RoundingMode.HALF_DOWN);
BigDecimal value1 = new BigDecimal(&quot;2.5&quot;);
value1 = value1.setScale(0, RoundingMode.HALF_DOWN);
BigDecimal value2 = new BigDecimal(&quot;2.6&quot;);
value2 = value2.setScale(0, RoundingMode.HALF_DOWN);
System.out.println(value + &quot;n&quot; + value1 + &quot;n&quot; + value2);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2
2
3</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>HALF_EVEN</h2>
</p>
<p align="justify">
This rounds off a  decimal value towards the nearest neighbouring value apart from the case when both neighbouring values are equidistant, in which case it just rounds towards the nearest even number. It performs the same rounding as RoundingMode.HALF_UP if the digit to the left of the discarded fractional part is odd, and performs the same rounding as RoundingMode.HALF_DOWN if it&#8217;s even. Let us see an example for this,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">BigDecimal value = new BigDecimal(&quot;2.4&quot;);
value = value.setScale(0, RoundingMode.HALF_EVEN);
BigDecimal value2 = new BigDecimal(&quot;2.6&quot;);
value2 = value2.setScale(0, RoundingMode.HALF_EVEN);
BigDecimal value3 = new BigDecimal(&quot;7.5&quot;);
value3 = value3.setScale(0, RoundingMode.HALF_EVEN);
BigDecimal value4 = new BigDecimal(&quot;6.5&quot;);
value4 = value4.setScale(0, RoundingMode.HALF_EVEN);
System.out.println(value + &quot;n&quot; + value2+ &quot;n&quot; + value3+ &quot;n&quot; + value4);</pre></td></tr></table></div>

</p>
<p align="justify">
The output of the above code is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2
3
8
6</pre></td></tr></table></div>

</p>
<p align="justify">
<h2>UNNECESSARY</h2>
</p>
<p align="justify">
This Rounding mode is used to insist that a value does not need rounding, and this can be possible only when the value has no decimals. If it is used in cases where in the value has decimal places i.e. when rounding is needed, then this will throw Arithmetic Exception stating that rounding is necessary.</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/2007/10/precise-rounding-of-decimals-using-rounding-mode-enumeration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Prototype pattern to clone objects</title>
		<link>http://www.javabeat.net/2007/10/using-the-prototype-pattern-to-clone-objects/</link>
		<comments>http://www.javabeat.net/2007/10/using-the-prototype-pattern-to-clone-objects/#comments</comments>
		<pubDate>Mon, 08 Oct 2007 20:43:47 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=70</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>Prototype pattern is one of the creational patterns that concentrate on duplicating objects if needed. Assuming that we are in process of creating a template. Most of the times, we copy an existing template, do some changes in it and then will use it. Technically, we make a copy of the source, make some changes [...]</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 align="justify">
<i><b>Prototype pattern</b></i> is one of the creational patterns that concentrate on duplicating objects if needed. Assuming that we are in process of creating a template. Most of the times, we copy an existing template, do some changes in it and then will use it. Technically, we make a copy of the source, make some changes and will use according to the requirements. This is the core concept of the prototype pattern.
</p>
<p align="justify">
<p>For example, assuming that we are creating an <i><b>Online Leave Application</b></i>, where someone is asked to fill-in the reason for the leave, start and end date of his/her leave along with details of the approver. A smart thing is for the very first time, we can ask the person to fill in the details and for the subsequent time we can provide an option to copy the first template, do some changes (like changing the start and end date) and allow him to submit.</p>
<p align="justify">
One important thing that has to be considered in designing prototype pattern is regarding the depth to which we want the object to be copied. In Java terms, whether we want shallow copying or deep copying. In shallow copying, only the primitive properties of the outer object will be copied during the cloning operation, and not the object references. It means that changes made to the target object will be reflected back to the original source object. Whereas, in the case of deep copying, all the primitive and the object references will be copied bit-by-bit, so that it can be ensured that changes done to the target object is not reflected back to the source.
</p>
<p align="justify">
Now, let us see an example for the Prototype pattern what we have discussed till now. Given below is the complete example,
</p>
<p>
<b>LeaveApplication.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">import java.text.SimpleDateFormat;
import java.util.Date;
&nbsp;
public class LeaveApplication implements Cloneable {
&nbsp;
	private String reason;
	private Date startDate;
	private Date endDate;
	private Approver approver;
&nbsp;
	public LeaveApplication(
			String reason, Date startDate, Date endDate, Approver approver){
&nbsp;
		this.reason = reason;
		this.startDate = startDate;
		this.endDate = endDate;
		this.approver = approver;
	}
&nbsp;
	public LeaveApplication clone(){
&nbsp;
		Approver copyApprover = new Approver(
			approver.getName(), approver.getDesignation());
		LeaveApplication copyApplication = new LeaveApplication(
			reason, ((Date)startDate.clone()), ((Date)endDate.clone()), copyApprover);
		return copyApplication;
	}
&nbsp;
	public String toString(){
		return &quot;[Leave Application:&quot; + reason + &quot;,&quot; + toString(startDate)
			+ &quot;,&quot; + toString(endDate) + approver + &quot;]&quot;;
	}
&nbsp;
	private String toString(Date date){
&nbsp;
		SimpleDateFormat format = new SimpleDateFormat(&quot;dd-MMM-yy&quot;);
		return format.format(date);
	}
&nbsp;
	public String getReason() {
		return reason;
	}
&nbsp;
	public void setReason(String reason) {
		this.reason = reason;
	}
&nbsp;
	public Date getStartDate() {
		return startDate;
	}
&nbsp;
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}
&nbsp;
	public Date getEndDate() {
		return endDate;
	}
&nbsp;
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
&nbsp;
	public Approver getApprover() {
		return approver;
	}
&nbsp;
	public void setApprover(Approver approver) {
		this.approver = approver;
	}
}</pre></td></tr></table></div>

</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 align="justify">
This <code>LeaveApplication</code> is the class that we want to clone. It has 3 simple properties namely <code>reason</code>, <code>startDate</code> and <code>endDate</code> and 1 composite property called <code>Approver</code>. Later on we see the class definition for <code>Approver</code> class. Now, let us have a look over the <code>clone()</code> method. Within this method, we create a new instance for the <code>LeaveApplication</code> class and set its properties to the value of the properties of the original object. In this way, we are making a deep cloning of the object and not a shallow cloning. Given below is the class definition for the <code>Approver</code> class,
</p>
<p>
<b>Approver.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.pattern.prototype;
&nbsp;
public class Approver {
&nbsp;
	private String name;
	private String designation;
&nbsp;
	public Approver(String name, String designation){
		this.name = name;
		this.designation = designation;
	}
&nbsp;
	public String toString(){
		return &quot;[Approver: &quot; + name + &quot;,&quot; + designation + &quot;]&quot;;
	}
&nbsp;
	public String getName() {
		return name;
	}
&nbsp;
	public void setName(String name) {
		this.name = name;
	}
&nbsp;
	public String getDesignation() {
		return designation;
	}
&nbsp;
	public void setDesignation(String designation) {
		this.designation = designation;
	}
}</pre></td></tr></table></div>

</p>
<p align="justify">
Then, we define the main class <code>PrototypeTest</code> for testing the prototype pattern. It creates a new instance of the <code>LeaveApplication</code> class for setting the sickLeave properties. After that, it makes a clone of the <code>sickLeave</code> instance as a <code>casualLeave</code> and modifies some of its properties like the reason and the dates.
</p>
<p>
<b>PrototypeTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.pattern.prototype;
&nbsp;
import java.util.Date;
&nbsp;
public class PrototypeTest {
&nbsp;
	public static void main(String[] args) {
&nbsp;
		Approver manager = new Approver(&quot;Johny&quot;, &quot;manager&quot;);
		LeaveApplication sickLeave =
			new LeaveApplication(&quot;Fever&quot;, new Date(2007, 3, 20), new Date(2007, 3, 22), manager);
		System.out.println(sickLeave);
&nbsp;
		LeaveApplication casualLeave = sickLeave.clone();
		casualLeave.setReason(&quot;Vacation&quot;);
		casualLeave.setStartDate(new Date(2007, 10, 10));
		casualLeave.setEndDate(new Date(2007, 10, 20));
		System.out.println(casualLeave);
	}
}</pre></td></tr></table></div>
</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/2007/10/using-the-prototype-pattern-to-clone-objects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to send mail using Java Mail API?</title>
		<link>http://www.javabeat.net/2007/10/sending-mail-from-java/</link>
		<comments>http://www.javabeat.net/2007/10/sending-mail-from-java/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:13:07 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=68</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>The Java Mail API provides support for sending and receiving electronic mail messages. The API provides a plug-in architecture where vendor&#8217;s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols namely, Internet Mail Access Protocol (IMAP) Simple [...]</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 align="justify">The <em><strong>Java Mail API</strong></em> provides support for sending and receiving electronic mail messages. The API provides a plug-in architecture where vendor&#8217;s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols namely,</p>
<ul>
<li>Internet Mail Access Protocol (IMAP)</li>
<li>Simple Mail Transfer Protocol (SMTP)</li>
<li>Post Office Protocol 3(POP 3)</li>
</ul>
<p align="justify">In this tip, let us see how to send mail using the <em><strong>Java Mail API</strong></em>. Following is the complete code listing for sending a mail from a Java Application,</p>
<ul>
<li><a href="http://www.flipkart.com/java-j2ee-interview-questions-8183331734/p/itmdyuqzunuphdjz?pid=9788183331739&amp;affid=suthukrish" target="_blank"> JAVA/J2EE Interview Questions (With CD) </a></li>
<li><a href="http://www.flipkart.com/jdbc-pocket-reference-160-pages-8173666717/p/itmczzj3zs2kxyf2?pid=9788173666711&amp;affid=suthukrish" target="_blank">JDBC Pocket Reference</a></li>
</ul>
<p><strong>SendMail.java</strong></p>
<pre class="brush: java; title: ; notranslate">package tips.mails;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

	private String from;
	private String to;
	private String subject;
	private String text;

	public SendMail(String from, String to, String subject, String text){
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.text = text;
	}

	public void send(){

		Properties props = new Properties();
		props.put(&quot;mail.smtp.host&quot;, &quot;smtp.gmail.com&quot;);
		props.put(&quot;mail.smtp.port&quot;, &quot;465&quot;);

		Session mailSession = Session.getDefaultInstance(props);
		Message simpleMessage = new MimeMessage(mailSession);

		InternetAddress fromAddress = null;
		InternetAddress toAddress = null;
		try {
			fromAddress = new InternetAddress(from);
			toAddress = new InternetAddress(to);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			simpleMessage.setFrom(fromAddress);
			simpleMessage.setRecipient(RecipientType.TO, toAddress);
			simpleMessage.setSubject(subject);
			simpleMessage.setText(text);

			Transport.send(simpleMessage);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}</pre>
<p align="justify">The above program accepts the sender, receiver, subject and the data in its constructor. After giving this information, the mail can be sent by calling the <code>SendMail.send()</code> method. Let us have a deeper look into the implementation of this method.</p>
<p align="justify">The first thing is that a Mail Session has to be established with some properties for sending or receiving a mail. The mandatory property is the server name. In the above code, we have given the SMTP Mail server of Google. Then, it is optional to provide the port information, and it is needed if it is different from the default port of 25. Then we construct a Message object for the Mail session by populating the information like sender, receiver, subject and text. Then the message is sent by calling the <code>Transport.send()</code> 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 align="justify">Let us test the above code by writing a simple test class which is given below,</p>
<p><strong>SendMailTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package tips.mails;

public class SendMailTest {

	public static void main(String[] args) {

		String from = &quot;abc@gmail.com&quot;;
		String to = &quot;xyz@gmail.com&quot;;
		String subject = &quot;Test&quot;;
		String message = &quot;A test message&quot;;

		SendMail sendMail = new SendMail(from, to, subject, message);
		sendMail.send();
	}
}</pre>
<blockquote><p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2010/08/how-to-send-email-using-spring-framework/">How to send EMail using Spring Framework?</a></li>
<li><a href="http://www.javabeat.net/2007/10/file-upload-and-download-using-java/">File Upload and Download using Java</a></li>
</ul>
</blockquote>
<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/2007/10/sending-mail-from-java/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Passing arguments and properties from command line</title>
		<link>http://www.javabeat.net/2007/10/passing-arguments-and-properties-from-command-line/</link>
		<comments>http://www.javabeat.net/2007/10/passing-arguments-and-properties-from-command-line/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:12:33 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=66</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>Arguments and properties can be passed to a java application from command line. In this techical tip, let us see how to pass arguments as well as properties from command line. Passing arguments from command line The syntax to pass arguments from command line is as follows, 1 2 &#160; java &#60;classname&#62; &#60;argument1&#62; &#60;argument2&#62; &#60;argument3&#62; [...]</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 align="justify">
Arguments and properties can be passed to a java application from command line.<br />
In this techical tip, let us see how to pass arguments as well as properties from command line.
</p>
<h2>Passing arguments from command line</h2>
<p align="justify">
The syntax to pass arguments from command line is as follows,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&nbsp;
java &lt;classname&gt;  &lt;argument1&gt;  &lt;argument2&gt;  &lt;argument3&gt; ........</pre></td></tr></table></div>

</p>
<p align="justify">
The following example shows the usage of command line arguments.
</p>
<p>
<b>ArithmeticOperationTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&nbsp;
public class ArithmeticOperationTest {
&nbsp;
    public static void main(String[] arguments) {
&nbsp;
        if(arguments.length &gt; 0)
        {
            float numberOne = getNumber(arguments[0]);
            float numberTwo = getNumber(arguments[1]);
            char operator = getOperator(arguments[2]);
            float result = 0.00f;
&nbsp;
            if (operator == '+'){
                result = numberOne + numberTwo;
            }else if (operator == '-'){
                result = numberOne - numberTwo;
            }else if (operator == '/'){
                result = numberOne / numberTwo;
            }
&nbsp;
            System.out.println(&quot;result of &quot; +  numberOne + &quot; &quot; + operator
                + &quot; &quot; + numberTwo + &quot; is &quot; + result);
        }
    }
&nbsp;
    static float getNumber(String number){
&nbsp;
        float retNumber = 0.0f;
        retNumber = Float.parseFloat(number.trim());
        return retNumber;
    }
&nbsp;
    static char getOperator(String argument){
        char retOperator = ' ';
        retOperator = argument.trim().charAt(0);
        return retOperator;
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
To run the above program issue the following at command line,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">java ArithmeticOperationTest 10 5 /</pre></td></tr></table></div>

</p>
<p align="justify">
The output is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">result of 10.0 / 5.0 is 2.0</pre></td></tr></table></div>

</p>
<p align="justify">
Now, let us see how to pass properties from command line.
</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 align="justify">
<h2>Passing properties from command line</h2>
</p>
<p align="justify">
The syntax to pass properties from command line is as follows,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&nbsp;
java â€“D&lt;property1-name&gt;=&lt;property1-value&gt; â€“D&lt;property2-name&gt;=&lt;property2-value&gt; ....... &lt;class-Name&gt;</pre></td></tr></table></div>

</p>
<p align="justify">
The getProperty(
<property-name>) method in System class is used to get the value of a property by specifying the property name as key.
</p>
<p align="justify">
Consider the following example,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class ScoreCardPropertiesTest {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        String subject = System.getProperty(&quot;subject&quot;);
        System.out.println(&quot;subject is &quot; +subject);
        String score = System.getProperty(&quot;score&quot;);
        System.out.println(&quot;score is &quot; +score);
        String grade = System.getProperty(&quot;grade&quot;);
        System.out.println(&quot;grade is &quot; +grade);
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
We pass properties subject, score and grade to the above ScoreCardPropertiesTest class as follows,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">java -Dsubject=Maths -Dscore=95 -Dgrade=A ScoreCardPropertiesTest</pre></td></tr></table></div>

</p>
<p align="justify">
The output is,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">subject is Maths
score is 95
grade is A</pre></td></tr></table></div>
</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/2007/10/passing-arguments-and-properties-from-command-line/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generation of Random Numbers</title>
		<link>http://www.javabeat.net/2007/10/generation-of-random-numbers/</link>
		<comments>http://www.javabeat.net/2007/10/generation-of-random-numbers/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:11:50 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=64</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>Random numbers in java can be generated either by using the Random class in java.util package or by using the random() method in the Math class in java.lang package. In both these approaches, we only get a pseudo random number and not a true random number because it is all generated based on some mathematical [...]</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 align="justify">
Random numbers in java can be generated either by using the <i><b>Random</b></i> class in <code>java.util</code> package or by using the <i><b>random()</b></i> method in the <code>Math</code> class in <code>java.lang</code> package.
</p>
<p align="justify">
In both these approaches, we only get a pseudo random number and not a true random number because it is all generated based on some mathematical computation, and hence the number can be predicted if the logic behind the computation is known. In spite of this, we can use any of these two approaches itself for random number generation for most of our application needs.
</p>
<h2>Using the Random class</h2>
<p align="justify">
The <code>Random</code> class in <code>java.util</code> package can be used in order to generate random numbers. A seed value can be specfied, which would be used for generating random numbers. This seed value can be specified while creating the <code>Random</code> object. If it is not specified, then the default seed value would be the current time in a day.
</p>
<p align="justify">
There are several methods such as <code>next()</code>, <code>nextInt()</code>, <code>nextDouble()</code>, <code>nextFloat()</code>, <code>nextLong()</code>, <code>nextBytes()</code>, <code>nextBoolean()</code> and <code>nextGaussian()</code> etc.. which can be used to generate random numbers of different data types.
</p>
<p align="justify">
Let us see a simple example for generating random numbers using the <code>Random</code> class,
</p>
<p>
<b>RandomNumberTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">import java.util.Random;
&nbsp;
public class RandomNumberTest {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        Random random = new Random();
        int randomVal1 = random.nextInt();
        long randomVal2 = random.nextLong();
        float randomVal3 = random.nextFloat();
        System.out.println(randomVal1 + &quot;n&quot;  + randomVal2+ &quot;n&quot;  + randomVal3);
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
The above code would generate random int, long and float values.
</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>Using the random() method in Math class</h2>
<p align="justify">
The <code>random()</code> method in <code>Math</code> class returns a random positive decimal value that ranges between <code>0.0</code> and <code>1.0</code>. It is a static synchronized method.
</p>
<p align="justify">
The following code shows how to generate random numbers using the <code>random()</code> method,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">double randomValue = Math.random();
System.out.println(randomValue);</pre></td></tr></table></div>

</p>
<p align="justify">
If we need to generate a random number in a particular range, we can do so by using the following syntax,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;lower-bound in the range&gt; + Math.random() * &lt;count of numbers in the range&gt;</pre></td></tr></table></div>

</p>
<p align="justify">
The following code is an example of generating random numbers within a range of 10 to 15,
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">double randomValue = 10 + Math.random() * 5;
System.out.println(randomValue);</pre></td></tr></table></div>
</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/2007/10/generation-of-random-numbers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Downloading Content from the Internet</title>
		<link>http://www.javabeat.net/2007/10/downloading-content-from-the-internet/</link>
		<comments>http://www.javabeat.net/2007/10/downloading-content-from-the-internet/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:11:06 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=62</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>Let us write a Simple Downloader in this techincal tip by making use of the classes with java.net package. URL stands for Uniform Resource Locator and it is used to locate a resource in the Web in a standard fashion. A resource in the Web can be anything; it can be as simple as Html [...]</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 align="justify">
Let us write a Simple Downloader in this techincal tip by making use of the classes with <code>java.net</code> package. <i><b>URL </b></i>stands for <i><b>Uniform Resource Locator</b></i> and it is used to locate a resource in the Web in a standard fashion. A resource in the Web can be anything; it can be as simple as Html Document or can be a complex multimedia content such as audio/video file. For example, <a href="http://www.javabeat.net"><code>www.javabeat.net</code></a> represents a URL which is a simple Html Resource. Likewise, <a href="http://java.com/en/download/windows_xpi.jsp?begindownload=true"><code>http://java.com/en/download/windows_xpi.jsp?begindownload=true</code></a> represents a URL which is a downloadable file resource.
</p>
<p align="justify">
In Java, an <code>URL</code> is represented by the URL class. Another API that is closely associated with the URL class is the <code>URLConnection</code> object. It represents an open connection to the target resource. Given below is the complete code listing for the Simple Downloader.
</p>
<p>
<b>ContentDownloader.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.network.download;
&nbsp;
import java.io.*;
import java.net.*;
&nbsp;
public class ContentDownloader {
&nbsp;
    private String url;
    private static final int SIZE = 1024;
    private String destinationFile;
&nbsp;
    public ContentDownloader(String url){
        this.url = url;
    }
&nbsp;
    public void downloadContentsTo(String destinationFile){
        this.destinationFile = destinationFile;
&nbsp;
        URL urlObject = null;
        try {
            urlObject = new URL(url);
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }
&nbsp;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        BufferedInputStream bufferedInput = null;
&nbsp;
        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutput = null;
&nbsp;
        try{
            urlConnection = urlObject.openConnection();
            inputStream = urlConnection.getInputStream();
            bufferedInput = new BufferedInputStream(inputStream);
&nbsp;
            outputStream = new FileOutputStream(this.destinationFile);
            bufferedOutput = new BufferedOutputStream(outputStream);
&nbsp;
            byte[] buffer = new byte[SIZE];
            while (true){
                int noOfBytesRead = bufferedInput.read(buffer, 0, buffer.length);
                if (noOfBytesRead == -1){
                    break;
                }
                bufferedOutput.write(buffer, 0, noOfBytesRead);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            closeStreams(new InputStream[]{bufferedInput, inputStream},
                new OutputStream[]{bufferedOutput, outputStream});
        }
        System.out.println(&amp;quot;Downloading completed&amp;quot;);
    }
&nbsp;
    private void closeStreams(
        InputStream[] inputStreams, OutputStream[] outputStreams){
&nbsp;
        try{
            for (InputStream inputStream : inputStreams){
                if (inputStream != null){
                    inputStream.close();
                }
            }
            for (OutputStream outputStream : outputStreams){
                if (outputStream != null){
                    outputStream.close();
                }
            }
        }catch(IOException exception){
            exception.printStackTrace();
        }
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
The above class has a constructor that accepts the URL of the resource whose content we wish to download. The section of interest is the <code>downloadContentsTo()</code> method which accepts the name of the file in the local machine to which the content of the URL has to be stored. Now, let us look into the implementation of the method. The code tries to represent the URL string that we passed as a URL object. If the URL string is not valid, then a <code>MalformedURLException</code> will be thrown.
</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 align="justify">
It then tries to open a connection to the URL object by calling the <code>URL.openConnection()</code> method which returns a <code>InputStream</code> object. We have decorated the returned input stream to the <code>BufferedInputStream</code> object for faster reading from the underlying stream. We read the contents of the input stream and at the same time write the contents to the output stream as pointed by the destination file.
</p>
<p align="justify">
Now, let us run the above program, by having the following test class,
</p>
<p>
<b>ContentDownloaderTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package tips.network.download;
&nbsp;
public class ContentDownloaderTest {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        String url = &quot;http://www.google.com&quot;;
        String destinationFile = &amp;quot;C:\googleHomePage.html&amp;quot;;
&nbsp;
        ContentDownloader downloader = new ContentDownloader(url);
        downloader.downloadContentsTo(destinationFile);
    }
}</pre></td></tr></table></div>

</p>
<p align="justify">
A file called <code>googleHomePage.html</code> will be generated in the specified location with the content same as that of the home page of google.</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/2007/10/downloading-content-from-the-internet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating user defined exceptions</title>
		<link>http://www.javabeat.net/2007/10/creating-user-defined-exceptions/</link>
		<comments>http://www.javabeat.net/2007/10/creating-user-defined-exceptions/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 02:09:58 +0000</pubDate>
		<dc:creator>Christy</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=60</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>Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter. While defining an user defined exception, we need to take care of the following aspects: The user defined exception class [...]</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 align="justify">
    Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.
</p>
<p align="justify">
While defining an user defined exception, we need to take care of the following aspects:</p>
<ul>
<li>The user defined exception class should extend from Exception class.</li>
<li>The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.</li>
</ul>
<p align="justify">
Let us see a simple example to learn how to define and make use of user defined exceptions.
</p>
<p>
<b>NegativeAgeException.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class NegativeAgeException extends Exception {
&nbsp;
    private int age;
&nbsp;
    public NegativeAgeException(int age){
        this.age = age;
    }
&nbsp;
    public String toString(){
        return &quot;Age cannot be negative&quot; + &quot; &quot; +age ;
    }
}</pre></td></tr></table></div>

</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>CustomExceptionTest.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class CustomExceptionTest {
&nbsp;
    public static void main(String[] args) throws Exception{
&nbsp;
        int age = getAge();
&nbsp;
        if (age &lt; 0){
            throw new NegativeAgeException(age);
        }else{
            System.out.println(&quot;Age entered is &quot; + age);
        }
    }
&nbsp;
    static int getAge(){
        return -10;
    }
}&lt;/code&gt;</pre></td></tr></table></div>

</p>
<p align="justify">
In the <code>CustomExceptionTest</code> class, the age is expected to be a positive number. It would throw the user defined exception <code>NegativeAgeException</code> if the age is assigned a negative number.
</p>
<p align="justify">
At runtime, we get the following exception since the age is a negative number.
</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Exception in thread &quot;main&quot; Age cannot be negative -10
	at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)</pre></td></tr></table></div>
</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/2007/10/creating-user-defined-exceptions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
