<?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 Tutorial Hub</title>
	<atom:link href="http://www.javatutorialhub.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javatutorialhub.com</link>
	<description>Training &#38; Tutorials for Java Beginners</description>
	<lastBuildDate>Wed, 06 Mar 2013 10:08:36 +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>Buffered Reader in Java</title>
		<link>http://www.javatutorialhub.com/buffered-reader-in-java</link>
		<comments>http://www.javatutorialhub.com/buffered-reader-in-java#comments</comments>
		<pubDate>Tue, 12 Feb 2013 12:42:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1155</guid>
		<description><![CDATA[Buffered Reader in Java Java provides several mechanism to read Files. The most useful package that is provided for this is thejava.io.Reader. This class contains the Class BufferedReader under package java.io.BufferedReader Let us see what this class has in store for us. This class reads the text [...]]]></description>
				<content:encoded><![CDATA[<h1><b>Buffered Reader in </b><b>Java</b></h1>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2013/01/br12.jpg" rel="wp-prettyPhoto[1165]"><img class="alignnone size-full wp-image-1168" alt="br1" src="http://cdn.javatutorialhub.com/wp-content/uploads/2013/01/br12.jpg" width="380" height="193" /></a></p>
<p>Java provides several mechanism to read Files. The most useful package that is provided for this is the<b>java.io.Reader. </b>This class contains the Class <b>BufferedReader </b>under package <b>java.io.BufferedReader</b><b> </b></p>
<p>Let us see what this class has in store for us.</p>
<p>This class reads the text from an <b>Input stream (like file)</b> by buffering characters that efficiently reads characters, arrays or lines.</p>
<p>In general, each <b>read request</b> made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a <b>BufferedReader</b> around any Reader whose <b>read() operations may be costly</b>, such as <b>FileReaders</b> and InputStreamReaders.</p>
<p>A typical usage would involve passing the file path to the BufferedReader as follows:</p>
<p>The code will look like: (Assuming you have a text file in D drive)</p>
<pre class="brush: java; title: ; notranslate">objReader = new BufferedReader(new FileReader(&quot;D:\DukesDiary.txt&quot;));</pre>
<p>This basically <b>loads </b>your file in the <b>objReader. </b>Now, you will need to iterate through the contents of the file and print it. The <b>while </b>loop in the below code will read the file until it has reached the end of file i. e. there is no contents in the <b>objReader.readLine() – </b>that basically returns a string. Hence, the loop will iterate until it’s not null.</p>
<p>The below code shows the complete implementation.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {

	public static void main(String[] args) {

		BufferedReader objReader = null;

		try {
			String strCurrentLine;

			objReader = new BufferedReader(new FileReader(&quot;D:\DukesDiary.txt&quot;));

			while ((strCurrentLine = objReader.readLine()) != null) {

				System.out.println(strCurrentLine);
			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {
				if (objReader != null)
					objReader.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
</pre>
<p><b>Note:</b></p>
<p>The above code has some very important handlings especially in the <b>finally block</b> of the code. This code will ensure that the memory management is done efficiently and the objReader.close() method is called that releases the memory.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/buffered-reader-in-java/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java Date</title>
		<link>http://www.javatutorialhub.com/java-date/</link>
		<comments>http://www.javatutorialhub.com/java-date/#comments</comments>
		<pubDate>Wed, 26 Dec 2012 08:59:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1139</guid>
		<description><![CDATA[Interesting tips and tricks with the Java Date Let us first understand the parameters that consist of a Date. It will primarily contain - The year (in either 2 or 4 digits) The month (in either 2 digits, First 3 letters of the month or the entire [...]]]></description>
				<content:encoded><![CDATA[<h1><b>Interesting tips and tricks with the Java Date</b></h1>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java12.jpg" rel="wp-prettyPhoto[1139]"><img class="size-full wp-image-1140 alignnone" alt="java1" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java12.jpg" width="542" height="317" /></a></p>
<p>Let us first understand the parameters that consist of a <b>Date</b>.</p>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java21.jpg" rel="wp-prettyPhoto[1139]"><img class="alignnone size-full wp-image-1141" alt="java2" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java21.jpg" width="225" height="226" /></a></p>
<p>It will primarily contain -</p>
<ul>
<li>The <b>year</b> (in either 2 or 4 digits)</li>
<li>The <b>month</b> (in either 2 digits, First 3 letters of the month or the entire word of the month).</li>
<li> The <b>date</b> (it will be the actual date of the month).</li>
<li>The <b>day</b> (the day at the given date – like Sun, Mon, Tue etc).</li>
</ul>
<p>In terms of computer systems, there are quite a lot of parameters that can be used to associate with a date. We shall see them in the later parts of this topic.</p>
<h5>Displaying a Date in Java</h5>
<p>Now let us see how Java provide us the <b>Date</b>, first we shall see how to get the <b>current date-</b></p>
<p>Java provides a Date class under the <b>java.util package</b>, The package provides several methods to play around with the date.</p>
<p>You can use the Date object by invoking the <b>constructor of Date class</b> as follows:</p>
<pre class="brush: java; title: ; notranslate">
import java.util.Date;

class Date_Ex1 {
public static void main(String args[]) {

// Instantiate a Date object by invoking its constructor
Date objDate = new Date();

// Display the Date &amp; Time using toString()
 System.out.println(objDate.toString());
}
}
</pre>
<p>This will result in the following output-</p>
<pre class="brush: plain; title: ; notranslate">Wed Sep 26 05:40:45 PST 2012</pre>
<h5>Show the date in the specified format:</h5>
<p>You all must have learnt the alphabets in your kindergarten ….</p>
<p><span style="text-align: center;">Let us now learn the ABC’s of the date format.</span></p>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java31.jpg" rel="wp-prettyPhoto[1139]"><img class="size-full wp-image-1147 alignnone" alt="java3" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java31.jpg" width="378" height="290" /></a></p>
<p>Don’t worry, you don’t need to remember all of these, they can be referred anytime you need to format a particular date.</p>
<h5><b><i>How Dates Formats can be used?</i></b></h5>
<p>Java provides a class called a SimpleDateFormat that allows you to format and parse dates in the as per your requirements.</p>
<p><b>You can use the above characters to specify the format-</b></p>
<p>For example:</p>
<ol>
<li>Date format required: <strong>2012.10.23 20:20:45 PST</strong></li>
</ol>
<p>The appropriate date format specified will be- <strong>yyyy.MM.dd HH:mm:ss zzz</strong></p>
<p>2 .  Date format required:<strong>09:30:00 AM 23-May-2012</strong></p>
<p>The appropriate date format specified will be-<strong>hh:mm:ss a dd-MMM-yyyy</strong></p>
<p>Tip: Be careful with the letter capitalization . If you mistake M with m , you will undesired results!</p>
<p>Lets learn this with a code example</p>
<pre class="brush: java; title: ; notranslate">
import java.text.SimpleDateFormat;
import java.util.Date;

class TestDates_Format {
 public static void main(String args[]) {

 Date objDate = new Date( ); // Current System Date and time is assigned to objDate
 System.out.println(objDate);

String strDateFormat = &quot;hh:mm:ss a dd-MMM-yyyy&quot;;//Date format is Specified
 SimpleDateFormat objSDF = new SimpleDateFormat (strDateFormat);//Date format string is passed as an argument to the Date format object
 System.out.println(objSDF.format(objDate));//Date formatting is applied to the current date

 }

}

</pre>
<p>Output of above code will be the current date in the specified format:</p>
<pre class="brush: plain; title: ; notranslate">

Wed Dec 26 09:11:08 GMT 2012
09:11:08 AM 26-Dec-2012

</pre>
<h5><b>Comparison of Dates</b></h5>
<p>The most useful method of comparing dates is by using the method – compareTo()</p>
<p>Let us take a look at the below code snippet-</p>
<pre class="brush: java; title: ; notranslate">
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

class TestDates_Compare{
public static void main(String args[]) throws ParseException{

SimpleDateFormat objSDF = new SimpleDateFormat(&quot;dd-mm-yyyy&quot;);
Date dt_1 = objSDF.parse(&quot;20-08-1981&quot;);
Date dt_2 = objSDF.parse(&quot;12-10-2012&quot;);

System.out.println(&quot;Date1 : &quot; + objSDF.format(dt_1));
System.out.println(&quot;Date2 : &quot; + objSDF.format(dt_2));

if (dt_1.compareTo(dt_2)&gt;0){
System.out.println(&quot;Date 1 occurs after Date 2&quot;);
}// compareTo method returns the value greater than 0 if this Date is after the Date argument.

else if (dt_1.compareTo(dt_2)&lt;0){
System.out.println(&quot;Date 1 occurs before Date 2&quot;);
}// compareTo method returns the value less than 0 if this Date is before the Date argument;

else if (dt_1.compareTo(dt_2)==0){
System.out.println(&quot;Both are same dates&quot;);
}// compareTo method returns the value 0 if the argument Date is equal to the second Date;
else{
System.out.println(&quot;You seem to be a time traveller !!&quot;);
}
}
}
</pre>
<p>Thus the output of the above code will be as –</p>
<pre class="brush: plain; title: ; notranslate">

Date1 : 20-08-1981
Date2 : 12-10-2012
Date 1 occurs before Date 2

</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/java-date/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with HashMaps</title>
		<link>http://www.javatutorialhub.com/working-with-hashmaps/</link>
		<comments>http://www.javatutorialhub.com/working-with-hashmaps/#comments</comments>
		<pubDate>Fri, 21 Dec 2012 10:22:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1113</guid>
		<description><![CDATA[Working with HashMaps A HashMap basically designates unique keys to corresponding values that can be retrieved at any given point. Some core features of the HashMap are- a)      The values can be stored in a map by forming a key-value pair. The value can be retrieved using [...]]]></description>
				<content:encoded><![CDATA[<h1><b>Working with HashMaps</b></h1>
<p><a href="http://www.javatutorialhub.com/working-with-hashmaps/java-8/" rel="attachment wp-att-1119"><img class="size-full wp-image-1119 alignnone" alt="java" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java6.jpg" width="379" height="231" /></a></p>
<p>A HashMap basically designates <b>unique keys</b> to corresponding <b>values</b> that can be retrieved at any given point. Some core features of the <b>HashMap</b> are-</p>
<p>a)      The <b>values</b> can be stored in a map by forming a <b>key-value</b> pair. The value can be retrieved using the key by passing it to the correct method.</p>
<p>b)      If <b>no element</b> exists in the Map, it will throw a ‘<b>NoSuchElementException’</b>.</p>
<p>c)       HashMap stores only <b>object</b> <b>references</b>. That&#8217;s why, it&#8217;s impossible to use <b>primitive data types</b> like double or int. Use wrapper class (like Integer or Double) instead.</p>
<p><a href="http://www.javatutorialhub.com/working-with-hashmaps/java1/" rel="attachment wp-att-1120"><img class="aligncenter size-full wp-image-1120" alt="java1" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java11.jpg" width="594" height="393" /></a></p>
<h2>Using Maps in Java Programs:</h2>
<p>Following are the two ways to declare a HashMap:</p>
<pre class="brush: java; title: ; notranslate">
HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
</pre>
<p>The most important methods of HashMap are-</p>
<ul>
<li><b>get(Object KEY)</b> – This will return the value associated with specified key in this hash map.</li>
<li><b>put(Object KEY, String VALUE)</b> – This method stores the specified value and associates it with the specified key in this map.</li>
</ul>
<p><b>Following is a sample implementation of HashMap:</b></p>
<pre class="brush: java; title: ; notranslate">
  import java.util.HashMap;
  import java.util.Map;

public class Sample_TestMaps{

    public static void main(String[] args){

      Map&lt;String, String&gt; objMap = new HashMap&lt;String, String&gt;();
      objMap.put(&quot;Name&quot;, &quot;Suzuki&quot;);
      objMap.put(&quot;Power&quot;, &quot;220&quot;);
      objMap.put(&quot;Type&quot;, &quot;2-wheeler&quot;);
      objMap.put(&quot;Price&quot;, &quot;85000&quot;);

      System.out.println(&quot;Elements of the Map:&quot;);
      System.out.println(objMap);

    }
}
</pre>
<p><b><span style="text-decoration: underline;"><br />
Output of the above code:</span></b></p>
<p>Elements of the Map:<br />
{Name=Suzuki, Type=2-wheeler, Power=220, Price=85000}</p>
<h2>Lets us ask a few queries to the HashMap itself to know it better </h2>
<p><b><i>Q: So Mr.HashMap, how can I find if a particular key has been assigned to you?</i></b></p>
<p>A: Cool, you can use the containsKey(Object KEY) method with me, it will return a Boolean value if I have a value for the given key.</p>
<p><b><i>Q: How do I find all the available keys that are present in the Map?</i></b></p>
<p>A: I have a method called as <b>keyset</b>() that will return all the keys in the map. In the above example, if you write a line as –<br />
<b>System.out.println(objMap.keySet());</b></p>
<p>It will return an <b>output</b> as-<br />
[Name, Type, Power, Price]
<p>Similarly, if you need all the values only, I have a method as <b>values</b>().<br />
<b>System.out.println(objMap.values());</b></p>
<p>It will return an <b>output</b> as-<br />
[Suzuki, 2-wheeler, 220, 85000]
<p><b><i>Q: Suppose, I need to remove only a particular key from the Map, do I need to delete the entire Map?</i></b></p>
<p>A: No buddy!! I have a method as <b>remove</b>(Object KEY) that will remove only that particular key-value pair.</p>
<p><b><i>Q: How can we check if you actually contain some key-value pairs?</i></b></p>
<p>A: Just check if I am empty or not!! In short, use <b>isEmpty</b>() method against me <img src='http://cdn.javatutorialhub.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/working-with-hashmaps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Math Simplified with Java</title>
		<link>http://www.javatutorialhub.com/math-java</link>
		<comments>http://www.javatutorialhub.com/math-java#comments</comments>
		<pubDate>Thu, 20 Dec 2012 11:12:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1084</guid>
		<description><![CDATA[Math Simplified with Java Java has had several advanced usage application  including working with complex calculations in physics, architecture/designing of structures, working with Maps and corresponding latitudes/longitudes etc. All such applications require using complex calculations/equations that are tedious to perform manually. Programmatically, such calculations, would involve usage [...]]]></description>
				<content:encoded><![CDATA[<h1>Math Simplified with Java</h1>
<p><a href="http://www.javatutorialhub.com/math-java/java-2/" rel="attachment wp-att-1092"><img class="aligncenter size-full wp-image-1092" alt="java" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/12/java.jpg" width="547" height="207" /></a><br />
Java has had several advanced usage application  including working with complex calculations in physics, architecture/designing of structures, working with Maps and corresponding latitudes/longitudes etc. All such applications require using complex calculations/equations that are tedious to perform manually. Programmatically, such calculations, would involve usage of logarithms, trigonometry, exponential equations etc.</p>
<p>Now, you cannot have all the log or trigonometry tables hard-coded somewhere in your application or data. The data would be enormous and complex to maintain.<span id="more-1084"></span></p>
<p>Java provides a very useful class for this purpose. It is the Math class (java.lang.Math).</p>
<p>This class provides methods for performing the operations like exponential, logarithm, roots and trigonometric equations too.</p>
<p>Let us have a look at the methods provided by the Math class.</p>
<p>The 2 most fundamental elements in Math are the ‘e’ (base of the natural logarithm) and ‘pi’ (ratio of the circumference of a circle to its diameter). These 2 constants are often required in the above calculations/operations.</p>
<p>Hence the Math class provides these 2 constants as double fields.</p>
<p><b> </b></p>
<p><b>Math.E</b>  &#8211; having a value as <b>2.718281828459045</b></p>
<p><b>Math.PI &#8211; </b>having a value as <b>3.141592653589793</b></p>
<p>A) Let us have a look at the table below that shows us the <b>Basic methods</b> and its description</p>

<table class="custom-table"  class="custom-table" summary="Sample Table">
<thead>
<tr>
<th scope="col">Method</th>
<th scope="col">Description</th>
<th scope="col">Arguments</th>
</tr>
</thead>
<tbody>
<tr>
<td>abs</td>
<td>Returns the absolute value of the argument</td>
<td>Double, float, int, long</td>
</tr>
<tr>
<td>round</td>
<td>Returns the closed int or long (as per the argument)</td>
<td>double or float</td>
</tr>
<tr>
<td>ceil</td>
<td>Returns the smallest integer that is greater than or equal to the argument</td>
<td>Double</td>
</tr>
<tr>
<td>floor</td>
<td>Returns the largest integer that is less than or equal to the argument</td>
<td>Double</td>
</tr>
<tr>
<td>min</td>
<td>Returns the smallest of the two arguments</td>
<td>Double, float, int, long</td>
</tr>
<tr>
<td>max</td>
<td>Returns the largest of the two arguments</td>
<td>Double, float, int, long</td>
</tr>
</tbody>
</table>

<p>Below is the code implementation for the above methods:</p>
<p>Note: There is no  need to explicitly import java.lang.Math as its imported implicitly. All its methods are static</p>
<p>//Simple integer variables</p>
<pre class="brush: java; title: ; notranslate">

int i1 = 27;
int i2 = -45;
</pre>
<p>//Simple double(decimal) variables</p>
<pre class="brush: java; title: ; notranslate">
double d1 = 84.6;
double d2 = 0.45;
</pre>
<p>/*****      ABSOLUTE VALUES ******/</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Absolute value of i1: &quot; + Math.abs(i1));
Absolute value of i1: 27

System.out.println(&quot;Absolute value of i2: &quot; + Math.abs(i2));
Absolute value of i2: 45

System.out.println(&quot;Absolute value of d1: &quot; + Math.abs(d1));
Absolute value of d1: 84.6

System.out.println(&quot;Absolute value of d2: &quot; + Math.abs(d2));
Absolute value of d2: 0.45

</pre>
<p>/*****  ROUND OFF  ******/</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Round off for d1: &quot; + Math.round(d1));
Round off for d1: 85

System.out.println(&quot;Round off for d2: &quot; + Math.round(d2));
Round off for d2: 0
</pre>
<p>/***** CEIL AND FLOOR *****/</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Ceiling of '&quot;+ d1 + &quot;' = &quot; + Math.ceil(d1));
Ceiling of '84.6' = 85.0

System.out.println(&quot;Floor of '&quot;+ d1 + &quot;' = &quot; + Math.floor(d1));
Floor of '84.6' = 84.0

System.out.println(&quot;Ceiling of '&quot;+ d2 + &quot;' = &quot; + Math.ceil(d2));
Ceiling of '0.45' = 1.0

System.out.println(&quot;Floor of '&quot;+ d2 + &quot;' = &quot; + Math.floor(d2));
Floor of '0.45' = 0.0
</pre>
<p>/*****  MIN AND MAX *****/</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Minimum out of '&quot;+ i1 +&quot;' and '&quot; + i2+&quot;' = &quot;+ Math.min(i1, i2));
Minimum out of '27' and '-45' = -45

System.out.println(&quot;Maximum out of '&quot;+ i1 +&quot;' and '&quot; + i2+&quot;' = &quot;+ Math.max(i1, i2));
Maximum out of '27' and '-45' = 27

System.out.println(&quot;Minimum out of '&quot;+ d1 +&quot;' and '&quot; + d2+&quot;' = &quot;+ Math.min(d1, d2));
Minimum out of '84.6' and '0.45' = 0.45

System.out.println(&quot;Maximum out of '&quot;+ d1 +&quot;' and '&quot; + d2+&quot;' = &quot;+ Math.max(d1, d2));
Maximum out of '84.6' and '0.45' = 84.6
</pre>
<p>B)      Let us have a look at the table below that shows us the <b>Exponential and Logarithmic methods</b> and its description-</p>

<table class="custom-table"  class="custom-table" summary="Sample Table">
<thead>
<tr>
<th scope="col">Method</th>
<th scope="col">Description</th>
<th scope="col">Arguments</th>
</tr>
</thead>
<tbody>
<tr>
<td>exp</td>
<td>Returns the base of natural log (e) to the power of argument</td>
<td>Double</td>
</tr>
<tr>
<td>Log</td>
<td>Returns the natural log of the argument</td>
<td>double</td>
</tr>
<tr>
<td>Pow</td>
<td>Takes 2 arguments as input and returns the value of the first argument raised to the power of the second argument</td>
<td>Double</td>
</tr>
<tr>
<td>floor</td>
<td>Returns the largest integer that is less than or equal to the argument</td>
<td>Double</td>
</tr>
<tr>
<td>Sqrt</td>
<td>Returns the square root of the argument</td>
<td>Double</td>
</tr>
</tbody>
</table>

<p>Below is the code implementation for the above methods: (The same variables are used as above)</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;exp(&quot; + d2 + &quot;) = &quot; + Math.exp(d2));
exp(0.45) = 1.5683121854901687

System.out.println(&quot;log(&quot; + d2 + &quot;) = &quot; + Math.log(d2));
log(0.45) = -0.7985076962177716

System.out.println(&quot;pow(5, 3) = &quot; + Math.pow(5.0, 3.0));
pow(5, 3) = 125.0

System.out.println(&quot;sqrt(16) = &quot; + Math.sqrt(16));
sqrt(16) = 4.0
</pre>
<p>C) Let us have a look at the table below that shows us the <b>Trigonometric methods</b> and its description-</p>

<table class="custom-table"  class="custom-table" summary="Sample Table">
<thead>
<tr>
<th scope="col">Method</th>
<th scope="col">Description</th>
<th scope="col">Arguments</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sin</td>
<td>Returns the Sine of the specified argument</td>
<td>Double</td>
</tr>
<tr>
<td>Cos</td>
<td>Returns the Cosine of the specified argument</td>
<td>double</td>
</tr>
<tr>
<td>Tan</td>
<td>Returns the Tangent of the specified argument</td>
<td>Double</td>
</tr>
<tr>
<td>Atan2</td>
<td>Converts rectangular co-ordinates (x, y) to polar(r, theta) and returns theta</td>
<td>Double</td>
</tr>
<tr>
<td>toDegrees</td>
<td>Converts the arguments to degrees</td>
<td>Double</td>
</tr>
<tr>
<td>Sqrt</td>
<td>Returns the square root of the argument</td>
<td>Double</td>
</tr>
<tr>
<td>toRadians</td>
<td>Converts the arguments to radians</td>
<td>Double</td>
</tr>
</tbody>
</table>

Default Arguments are in Radians</p>
<p>Below is the code implementation:</p>
<pre class="brush: java; title: ; notranslate">
double angle_30 = 30.0;
double radian_30 = Math.toRadians(angle_30);

System.out.println(&quot;sin(30) = &quot; + Math.sin(radian_30));
sin(30) = 0.49999999999999994

System.out.println(&quot;cos(30) = &quot; + Math.cos(radian_30));
cos(30) = 0.8660254037844387

System.out.println(&quot;tan(30) = &quot; + Math.tan(radian_30));
tan(30) = 0.5773502691896257

System.out.println(&quot;Theta = &quot; + Math.atan2(4, 2));
Theta = 1.1071487177940904
</pre>
<p>Now, with the above, you can also design your own scientific calculator in java.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/math-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Let’s go Random with Java</title>
		<link>http://www.javatutorialhub.com/random-class-java</link>
		<comments>http://www.javatutorialhub.com/random-class-java#comments</comments>
		<pubDate>Tue, 18 Sep 2012 06:41:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1049</guid>
		<description><![CDATA[Let’s go Random with Java Ever wondered how these Random numbers get generated. Who sits behind this and punches in all the numbers? Well, Java does provide some interesting ways to generate random numbers, not only for gambling but also several other applications esp. related to gaming, [...]]]></description>
				<content:encoded><![CDATA[<h1>Let’s go Random with Java</h1>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/random_1.png" rel="wp-prettyPhoto[1049]"><img class="alignnone size-full wp-image-1050" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/random_1.png" alt="" width="622" height="277" /></a></p>
<p>Ever wondered how these Random numbers get generated. Who sits behind this and punches in all the numbers?</p>
<p>Well, Java does provide some interesting ways to generate random numbers, not only for gambling but also several other applications esp. related to gaming, security, math’s etc.</p>
<p><strong><em>Let’s see how it’s done!!</em></strong></p>
<p>There are basically two ways to do it-</p>

<ul class="list-4">
<li>Using <strong>Randomclass</strong> (in package <strong>java.util</strong>).</li>
<li>Using <strong>Math.random</strong> class (however this will generate <strong>double</strong> in the range of <strong>0.0</strong> to <strong>1.0</strong> and <strong>not integers</strong>).</li>
</ul>

<p>Lets look at them one by one -</p>
<h2><strong>Using Random Class</strong></h2>
<p>First we will see the implementation using <strong>java.util.Random</strong>-</p>
<p>Assume we need to generate <strong>10 random numbers</strong> between <strong>0 to 100</strong>.</p>
<pre class="brush: java; title: ; notranslate">
import java.util.Random;

public class RandomNumbers{

       public static void main(String[] args) {

              Random objGenerator = new Random();

              for (intiCount = 0; iCount&lt; 10; iCount++){

                  intrandomNumber = objGenerator.nextInt(100);

                  System.out.println(&quot;Random No : &quot; + randomNumber);

             }
     }
}
</pre>
<p>The above code will generate some random numbers like-</p>
<pre class="brush: plain; title: ; notranslate">
Random No : 48
Random No : 22
Random No : 72
Random No : 28
Random No : 48
Random No : 81
Random No : 24
Random No : 14
Random No : 98
Random No : 1

</pre>
<p>An object of Random class is initialized as <strong>objGenerator</strong>. The <strong>Random class has a method as nextInt</strong>. This will provide a random number based on the <strong>argument</strong> specified as the <strong>upper limit, </strong>whereas it takes <strong>lower limit is 0</strong>.Thus, we get 10 random numbers displayed.</p>
<h2>Using Math.Random</h2>
<p>Now, if we want <strong>10random numbers</strong> but in the range of <strong>0.0</strong> to <strong>1.0</strong>, then we should make use of <strong>math.random()</strong></p>
<p>You can use the following loop to generate them-</p>
<pre class="brush: java; title: ; notranslate">
for(int xCount = 0; xCount&lt;10; xCount++){

      System.out.println(Math.random());

}
</pre>
<p>The output of this will be 10 random numbers between 0.0 and 1.0</p>
<pre class="brush: plain; title: ; notranslate">
0.9644527856979734
0.09997966059020202
0.5537801448715082
0.6781655016328573
0.5951250412997393
0.4863822453592379
0.38608567647631464
0.4520340091060806
0.7167327389890008
0.9767837414574334
</pre>
<p><strong><em>Now, you know how those strange numbers are generated!!!</em></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/random-class-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Java timer for your programs.</title>
		<link>http://www.javatutorialhub.com/timers-java</link>
		<comments>http://www.javatutorialhub.com/timers-java#comments</comments>
		<pubDate>Tue, 18 Sep 2012 06:19:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1041</guid>
		<description><![CDATA[Using the Java timer for your programs!! Using the Java timer for your programs In Java, we have several ways of Timer implementation or rather its uses, a few of them are- Before jumping into the Timer implementation, we need to understand a few concepts like – [...]]]></description>
				<content:encoded><![CDATA[<h1>Using the Java timer for your programs!!</h1>
<p>Using the Java timer for your programs</p>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_1.png" rel="wp-prettyPhoto[1041]"><img class="alignnone size-full wp-image-1043" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_1.png" alt="" width="600" height="351" /></a></p>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_2.png" rel="wp-prettyPhoto[1041]"><img class="alignnone size-full wp-image-1044" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_2.png" alt="" width="600" height="300" /></a></p>
<p>In Java, we have several ways of Timer implementation or rather its uses, a few of them are-</p>

<ul class="list-1">
<li>To set up a <strong>specific amount</strong> of <strong>delay</strong> until a task is executed.</li>
<li>To find the <strong>time difference</strong> between <strong>two specific events</strong>.</li>
</ul>

<p>Before jumping into the <strong>Timer implementation</strong>, we need to understand a few concepts like –</p>
<ul>
<li>It can <strong>only be a future event</strong> that <strong>can be timed</strong>.</li>
<li>Will the <strong>event</strong> occur <strong>once</strong> or <strong>repeatedly</strong>?</li>
<li><strong>How long</strong> is the Timer required?</li>
<li>There may be several <strong>Timers</strong> required <strong>in parallel</strong>.</li>
<li>The timers should have the facility to <strong>stop</strong> or even <strong>cancel</strong> at any given point.</li>
</ul>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_3.png" rel="wp-prettyPhoto[1041]"><img class="alignnone size-full wp-image-1042" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/timer_3.png" alt="" width="591" height="213" /></a></p>
<p><strong><em>The Timer in java is provided within the <span style="text-decoration: underline;">java.util</span> package.</em></strong></p>
<p>Let us have a look at using Timer for 2 tasks that we need to schedule-</p>
<p><span style="text-decoration: underline;"><strong>Step 1)</strong></span> But before that lets create the class that will contain some task that we need to do-</p>
<pre class="brush: java; title: ; notranslate">
importjava.util.TimerTask;

importjava.util.Timer;

public class TaskMaster extends TimerTask{

       String strObject;

       publicTaskMaster(String strObject){

           this.strObject = strObject;

       }

       public void run(){

           System.out.println(&quot;Inside Run task-&quot; + strObject);

       }
}

</pre>
<p>This is a simple class that uses the <strong>run()</strong> method of <strong>Threads</strong> when the task is invoked. The String <strong>strObject</strong> will help us identify which task is running.</p>
<p><strong>Step 2) </strong>Create <strong>2 timers</strong> as follows in a <strong>class</strong> called <strong>Timers</strong>:</p>
<pre class="brush: java; title: ; notranslate">
Timer timer_1;

Timer timer_2;
</pre>
<p><strong>Step 3) </strong>Create a <strong>constructor</strong> of this class having <strong>2 integer</strong> parameters as <strong>input</strong>-</p>
<pre class="brush: java; title: ; notranslate">
public Timers(int t1,int t2) {
}
</pre>
<p>This constructor will have <strong>the code to invoke the 2 timers</strong> declared earlier to use for the tasks we created in <strong>TaskMaster</strong> class.</p>
<p><strong>Step 4) </strong>Initiate the timers as follows –</p>
<pre class="brush: java; title: ; notranslate">
timer_1 = new Timer();
</pre>
<p>Similarly do this for <strong>timer_2</strong>.</p>
<p><strong>Step 5) </strong>Now if you use this <strong>timer</strong> object, you will see several methods in it.</p>
<p>We will first make use of the <strong>schedule</strong> method that takes in arguments as –</p>
<p><strong>task</strong> &#8211; task to be scheduled.</p>
<p><strong>delay</strong> &#8211; delay in milliseconds before task is to be executed.</p>
<p><strong>period</strong> &#8211; time in milliseconds between successive task executions.</p>
<p>The delay and period will be the <strong>2 integer arguments</strong> that we have passed in the constructor (created in step 3).</p>
<p>So the constructor now has the code as</p>
<pre class="brush: java; title: ; notranslate">
timer_1 = new Timer();

timer_1.schedule(new TaskMaster(&quot;Alpha&quot;), t1 * 1000, t1 * 1000);
</pre>
<p><span style="text-decoration: underline;"><strong>Step 6) </strong></span>Repeat step 5 for <strong>timer_2</strong> and pass some different string say “Delta”.</p>
<p>Your constructor should now be looking something like-</p>
<pre class="brush: java; title: ; notranslate">
public Timers(int t1,int t2) {

       timer_1 = new Timer();

       timer_1.schedule(new TaskMaster(&quot;Alpha&quot;), t1 * 1000, t1 * 1000);

       //timer_1.scheduleAtFixedRate(new TaskMaster(&quot;Alpha&quot;), t1 * 1000, t1 * 1000);

       timer_2 = new Timer();

       timer_2.schedule(new TaskMaster(&quot;Delta&quot;), t2 * 1000, t2 * 1000);

       //timer_2.scheduleAtFixedRate(new TaskMaster(&quot;Delta&quot;), t2 * 1000, t2 * 1000);

}
</pre>
<p>Ignore the commented lines for now. We shall see that after executing this code in step 8.</p>
<p><strong>Step 7)</strong> Now create the <strong>main</strong> method and call the <strong>Timers</strong>class with <strong>2 arguments as integers</strong>.</p>
<p>public static void main(String args[]) {</p>
<p>new Timers(1,5);</p>
<p>}</p>
<p><span style="text-decoration: underline;"><strong>  Step 8) </strong></span>On executing this <strong>main</strong> method, the result will appear something like this-</p>
<pre class="brush: plain; title: ; notranslate">
Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Delta

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Delta

Inside Run task-Alpha

Inside Run task-Alpha

Inside Run task-Alpha
</pre>
<p><strong><em>…… This will continue until you don’t terminate the program.</em></strong></p>
<p>This was the Schedule method of timer that schedules the specified task for repeated <strong><em>fixed-delay execution</em></strong>, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.</p>
<p>In fixed-delay execution, each execution is scheduled <strong><em><span style="text-decoration: underline;">relative to the actual execution time of the previous execution</span></em></strong></p>
<p><strong><em></em><span style="text-decoration: underline;">Step 9)</span></strong> Now <strong>comment the line with schedule method</strong> and uncomment the <strong>scheduleAtFixedRate</strong>.</p>
<p>The output will be quite similar.</p>
<p>This method too schedules the specified task for repeated <strong><em>fixed-rate execution</em></strong>, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.</p>
<p>In fixed-rate execution, each execution is scheduled <strong><em><span style="text-decoration: underline;">relative to the scheduled execution time of the initial execution</span></em></strong>.</p>
<p>Oh yes!! You can programmatically stop the timers by calling the <strong>cancel() method of the timer.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/timers-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Let us understand Switch in Java</title>
		<link>http://www.javatutorialhub.com/switch-java</link>
		<comments>http://www.javatutorialhub.com/switch-java#comments</comments>
		<pubDate>Mon, 17 Sep 2012 06:30:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1032</guid>
		<description><![CDATA[Let us understand Switch in Java. We all use switches regularly in our lives. Yes, I am talking about electrical switches we use for our lights and fans. As you see from the above picture, each switch is assigned to operate for particular electrical equipment. For example, [...]]]></description>
				<content:encoded><![CDATA[<h1>Let us understand Switch in Java.</h1>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/switchboard1.png" rel="wp-prettyPhoto[1032]"><img class="size-full wp-image-1039 alignnone" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/switchboard1.png" alt="" width="554" height="306" /></a></p>
<p>We all use switches regularly in our lives. Yes, I am talking about electrical switches we use for our lights and fans.</p>
<p>As you see from the above picture, <strong>each switch</strong> <strong>is assigned</strong> to operate for particular <strong>electrical equipment</strong>.</p>
<p>For example, in the picture, the <strong>first switch is for fan</strong>, next for light and so on.</p>
<p>Thus, we can see that each <strong>switch</strong> <strong>can activate/deactivate only 1 item.</strong></p>
<p>Similarly, <strong>switch in java</strong> is a type of <strong>conditional statement</strong> <strong>that activates</strong> only the <strong>matching condition</strong> out of the given input.</p>
<p>Let us consider the example of a program where the user gives <strong>input</strong> as a <strong>numeric value </strong>(only 1 digit in this example) and the <strong>output</strong> should be the <strong>number in words</strong>.</p>
<p>The integer variable <strong>iSwitch</strong> ,is the input for the switch to work.</p>
<p>The various available options (read <strong>cases</strong>) are then written as case <strong>&lt;value&gt;</strong>alongwith a colon “<strong>:</strong>”</p>
<p>This will then have the <strong>statement</strong> to be <strong>executed</strong> if the <strong>case</strong> and the input to the switch <strong>match</strong>.</p>
<pre class="brush: java; title: ; notranslate">
public class SwitchBoard {

   public static void main(String[] args) {

        intiSwitch = 4;

        switch (iSwitch){

               case 0:

                      System.out.println(&quot;ZERO&quot;);

                      break;

               case 1:

                      System.out.println(&quot;ONE&quot;);

                      break;

               case 2:

                      System.out.println(&quot;TWO&quot;);

                      break;

               case 3:

                      System.out.println(&quot;THREE&quot;);

                      break;

               case 4:

                      System.out.println(&quot;FOUR&quot;);

                      break;

               default:

                      System.out.println(&quot;Not in list&quot;);

                      break;

        }

    }

}

</pre>
<p>The output of the following code will be :</p>
<pre class="brush: plain; title: ; notranslate">
FOUR
</pre>
<p>Now what are those 2 words <strong>break</strong> and <strong>default</strong> lying out there do?</p>
<ul>
<li>The first one “<strong>break</strong>” – <strong>will simply break out from the switch block</strong> once a condition is satisfied<strong>.</strong></li>
<li><strong>“<strong>Default</strong>” – This will be executed in case none of the conditions match the given input.</strong></li>
</ul>
<div>In the given example these are simple print statements, however they can also refer to more complex situations like calling a method etc.</div>
<h2>What if you do not provide a break?</h2>
<p>In case the break is not provided, it will execute the matching conditions as well as the default condition. Your logic will go haywire if that occurs.</p>
<p>I will leave it to the users to experiment without using break.</p>
<div>
<h2>Need for Switch statements:</h2>

<ul class="list-1">
<li>As a <strong>standard</strong> programming <strong>logic</strong>, it can simply be <strong>achieved</strong> by using <strong>if…else</strong> conditions, but then it will <strong>not be optimized </strong>for good programming practice<strong>nor</strong> does the <strong>code look readable</strong>.</li>
<li>In programs involving more <strong>complex cases</strong>, scenarios will not be so simple and would require <strong>calling several methods</strong>.<strong>Switch</strong> solves this problem and <strong>avoids several nested if…else statements</strong>.Also, while using if….else, it is recommended to use the most highly expected condition to be on top and then go ahead in a nested manner.</li>
<li><strong><em>Some benchmarking tests have proven that in case of high number of iterations, the switch is faster as compared to if….else statements.</em></strong></li>
</ul>

</div>
<h2>Points to Note</h2>
<ul>
<li>There is <strong>no limit on the number of cases</strong> you can have.</li>
<li>Switch can take <strong>input</strong> only as <strong>integers or characters</strong>.</li>
<li>The latest version of <strong>Java8</strong>, also introduces the much awaited support for <strong>strings in switch</strong> statement.</li>
</ul>
<p>So now go ahead and wire your own switch board!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/switch-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interesting trick with For Loop – Using the Foreach loop in Java</title>
		<link>http://www.javatutorialhub.com/foreach-loop-java</link>
		<comments>http://www.javatutorialhub.com/foreach-loop-java#comments</comments>
		<pubDate>Thu, 13 Sep 2012 09:17:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=1012</guid>
		<description><![CDATA[Interesting trick with For Loop – Using the Foreach loop in Java. Let us take the example using a String array that you want to iterate over without using any counters. Consider a String array arrData initialized as follows: Although, you might know methods like finding the [...]]]></description>
				<content:encoded><![CDATA[<h1>Interesting trick with For Loop – Using the Foreach loop in Java.</h1>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/ForEach1.png" rel="wp-prettyPhoto[1012]"><img class="aligncenter size-full wp-image-1027" title="ForEach" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/ForEach1.png" alt="" width="595" height="343" /></a></p>
<p><em>Let us take the example using a String array that you want to iterate over without using any counters.</em></p>
<p><span id="more-1012"></span></p>
<p>Consider a String array arrData initialized as follows:</p>
<pre class="brush: java; title: ; notranslate">
String[] arrData = {&quot;Alpha&quot;, &quot;Beta&quot;, &quot;Gamma&quot;, &quot;Delta&quot;, &quot;Sigma&quot;};
</pre>
<p>Although, you might know methods like finding the size of the array and then iterating through each element of the array using the traditional for loop (counter, condition and increment), we need to find a more optimized approach that will not use any such counter.</p>
<p>This is the conventional approach of the “for” loop:</p>
<pre class="brush: java; title: ; notranslate">
for(int i=0; i&lt;arrData.length; i++){

System.out.println(arrData[i]);

}
</pre>
<p>You can see the use of the counter and then using it as the index for the array.</p>
<p>Java provides a way to use the “for” loop that will iterate through each element of the array as shown below.</p>
<p>Following will be the syntactical template:</p>
<pre class="brush: java; title: ; notranslate">
For(&lt;DataType of array/List&gt;&lt;Temp variable name&gt;   : &lt;Array/List to be iterated&gt;){
    System.out.println();
//Any other operation can be done with this temp variable.
}
</pre>
<p>Here is the code for the array that we had declared earlier-</p>
<pre class="brush: java; title: ; notranslate">
for (String strTemp : arrData){

System.out.println(strTemp);

}
</pre>
<p>You can see the difference between the loops. The <strong><em>code</em></strong> has <strong><em>reduced</em></strong> significantly. Also there is <strong><em>no use of the index</em></strong> or rather the <strong><em>counter in the loop</em></strong>.</p>
<p>Do ensure that, the <strong><em>data type</em></strong> declared in the foreach loop <strong><em>must match</em></strong> the data type of the <strong><em>array/list that you are iterating</em></strong>.<br />
<strong><em>Here we have the entire class showing the above explanation-</em></strong></p>
<pre class="brush: java; title: ; notranslate">
public class UsingForEach {

public static void main(String[] args) {

String[] arrData = {&quot;Alpha&quot;, &quot;Beta&quot;, &quot;Gamma&quot;, &quot;Delta&quot;, &quot;Sigma&quot;};

//The conventional approach of using the for loop

System.out.println(&quot;Using conventional For Loop:&quot;);

for(int i=0; i&lt;arrData.length; i++){

System.out.println(arrData[i]);

}

System.out.println(&quot;\nUsing Foreach loop:&quot;);

//The optimized method of using the for loop - also called the foreach loop

for (String strTemp : arrData){

System.out.println(strTemp);

}

}

}

</pre>
<p>Following will be output that you will get on executing this code:</p>
<pre class="brush: plain; title: ; notranslate">

Using conventional For Loop:

Alpha

Beta

Gamma

Delta

Sigma

Using Foreach loop:

Alpha

Beta

Gamma

Delta

Sigma
</pre>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/ForEach2.png" rel="wp-prettyPhoto[1012]"><img class="aligncenter size-full wp-image-1029" title="ForEach2" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/09/ForEach2.png" alt="" width="427" height="282" /></a><br />
&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/foreach-loop-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to I convert a String to Integer?</title>
		<link>http://www.javatutorialhub.com/convert-string-to-integer</link>
		<comments>http://www.javatutorialhub.com/convert-string-to-integer#comments</comments>
		<pubDate>Sat, 25 Aug 2012 17:21:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=995</guid>
		<description><![CDATA[How to I convert a String to Integer? Let’s say you have a string – strTest &#8211; that contains a numeric value. Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error. Now make use of ParseInt method as [...]]]></description>
				<content:encoded><![CDATA[<h1>How to I convert a String to Integer?</h1>
<p style="text-align: center;"><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/StringToInt.png" rel="wp-prettyPhoto[995]"><img class="aligncenter  wp-image-996" title="StringToInt" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/StringToInt.png" alt="" width="657" height="237" /></a></p>
<p>Let’s say you have a string – strTest &#8211; that contains a numeric value.</p>
<pre class="brush: java; title: ; notranslate">

String strTest = “100”;

</pre>
<p>Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.</p>
<p>Now make use of ParseInt method as follows:</p>
<pre class="brush: java; title: ; notranslate">

int &lt;IntVariableName&gt; = Integer.parseInt(&lt;StringVariableName&gt;);

</pre>
<p>Pass the string variable as the argument.</p>
<p>This will convert the String to Integer and store it into the specified integer variable</p>
<p>Check the below code snippet-</p>
<pre class="brush: java; title: ; notranslate">
String strTest = &quot;100&quot;;

		//This statement results in a compilation error as you
		//cannot do arithmetic operation on Strings
		//System.out.println(&quot;Using String:&quot; + (strTest/4));

		//Convert the String to Integer
		int iTest = Integer.parseInt(strTest);

		System.out.println(&quot;Actual String:&quot;+ strTest);

		System.out.println(&quot;Converted to Int:&quot; + iTest);

		//This will now execute some arithmetic operation
		System.out.println(&quot;Arithmetic Operation on Int:&quot; + (iTest/4));

</pre>
<table>
<tbody>
<tr>
<td>&nbsp;</p>
<p><span style="text-decoration: underline;"><strong>Output of the above code snippet</strong>-</span></p>
<p>Actual String:100</p>
<p>Converted to Int:100</p>
<p>Arithmetic Operation on Int:25</td>
<td><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/StringToInt1.png" rel="wp-prettyPhoto[995]"><img class=" wp-image-997 alignright" style="margin-left: 15px; margin-right: 15px;" title="StringToInt1" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/StringToInt1.png" alt="" width="256" height="229" /></a></td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/convert-string-to-integer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Split a String in Java</title>
		<link>http://www.javatutorialhub.com/how-to-split-a-string-in-java</link>
		<comments>http://www.javatutorialhub.com/how-to-split-a-string-in-java#comments</comments>
		<pubDate>Thu, 23 Aug 2012 16:47:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javatutorialhub.com/?p=979</guid>
		<description><![CDATA[How to Split a String in Java In  earlier topics, we have seen how we joined/concatenated strings, similarly we may also need to break some string based on some attributes. Mainly this attribute will be something like a separator or a common pattern with which you want [...]]]></description>
				<content:encoded><![CDATA[<h1>How to Split a String in Java</h1>
<p>In  earlier topics, we have seen how we joined/concatenated strings, similarly we may also need to break some string based on some attributes. Mainly this attribute will be something like a separator or a common pattern with which you want to break or split the string.</p>
<p>Let’s consider an example here:</p>
<p>Suppose we have a string variable named <strong>strMain</strong> formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by comma (,).</p>
<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/SplitString.png" rel="wp-prettyPhoto[979]"><img class="aligncenter size-full wp-image-980" title="SplitString" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/SplitString.png" alt="" width="684" height="196" /></a></p>
<p>Here if we want all individual strings, the best possible pattern would be to split it based on comma. So we will get 5 separate strings as follows:</p>

<ul class="list-1">
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
<li>Delta</li>
<li>Sigma</li>
</ul>

<p><a href="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/SplitString1.png" rel="wp-prettyPhoto[979]"><img class="aligncenter size-full wp-image-981" title="SplitString1" src="http://cdn.javatutorialhub.com/wp-content/uploads/2012/08/SplitString1.png" alt="" width="527" height="221" /></a></p>
<p>Use the <strong>split</strong> method against the string that needs to be divided and provide the separator as argument.</p>
<p>In this case, the separator is comma (,) and the result of the split operation will give you an array of the split strings.</p>
<pre class="brush: java; title: ; notranslate">
String strMain = &quot;Alpha, Beta, Delta, Gamma, Sigma&quot;;

String[] arrSplit = strMain.split(&quot;, &quot;);

for (int i=0; i&lt;arrSplit.length; i++)
{
	System.out.println(arrSplit[i]);
}
</pre>
<p>The loop in the code just prints each string (element of array) after the split operation, as shown below-</p>
<div class="divider"></div>
<p><strong>Alpha</strong></p>
<p><strong>Beta</strong></p>
<p><strong>Delta</strong></p>
<p><strong>Gamma</strong></p>
<p><strong>Sigma</strong></p>
<div class="divider"></div>
<p>Consider a situation, wherein you require only the first ‘n’ elements after the split operation but want the rest of the string remain as it is. An output something like this-</p>

<ul class="list-1">
<li>Alpha</li>
<li>Beta</li>
<li>Delta, Gamma, Sigma</li>
</ul>

<p>This can be achieved by passing another argument along with the split operation and that will be the limit of strings required. Actually, it is the 1 greater than the number of times the string will be split into.</p>
<p>See the following code –</p>
<pre class="brush: java; title: ; notranslate">
String strMain = &quot;Alpha, Beta, Delta, Gamma, Sigma&quot;;

String[] arrSplit_2 = strMain.split(&quot;, &quot;, 3);
for (int i=0; i&lt;arrSplit_2.length; i++)
{
	System.out.println(arrSplit_2[i]);
}

</pre>
<p><strong><span style="text-decoration: underline;">Output on console:</span></strong><strong> </strong></p>
<p>Alpha</p>
<p>Beta</p>
<p>Delta, Gamma, Sigma<strong></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.javatutorialhub.com/how-to-split-a-string-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Database Caching 4/21 queries in 0.003 seconds using disk
Object Caching 1228/1259 objects using disk
Content Delivery Network via cdn.javatutorialhub.com

 Served from: www.javatutorialhub.com @ 2013-05-20 00:25:12 by W3 Total Cache -->