<?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>zParacha.com</title>
	<atom:link href="https://zparacha.com/feed" rel="self" type="application/rss+xml" />
	<link>https://zparacha.com</link>
	<description>Effective Programming Tips</description>
	<lastBuildDate>Mon, 28 Nov 2022 22:10:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.1</generator>

<image>
	<url>https://zparacha.com/wp-content/uploads/2015/12/cropped-zParachaGrayGel-1-100x100.jpg</url>
	<title>zParacha.com</title>
	<link>https://zparacha.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Insertion Sort Algorithm In Java</title>
		<link>https://zparacha.com/insertion-sort-implementation-in-java</link>
					<comments>https://zparacha.com/insertion-sort-implementation-in-java#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Mon, 22 Jan 2018 03:16:32 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[Insertion Sort]]></category>
		<category><![CDATA[Sort]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1635</guid>

					<description><![CDATA[Insertion sort is a simple algorithm.&#160;Insertion sort logic works as follows: To insert an element in an already existing set, we make room for the new item by moving larger items one position to the right. Then insert the new item at the newly available position. The algorithm most often used to sort cards in [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Insertion sort is a simple algorithm.&nbsp;Insertion sort logic works as follows: To insert an element in an already existing set, we make room for the new item by moving larger items one position to the right. Then insert the new item at the newly available position. The algorithm most often used to sort cards in a bridge game is an example of Insertion Sort.</p>
<p>The following Java class shows how to implement Selection sort in Java.</p>
<blockquote>
<pre class="EnlighterJSRAW" data-enlighter-language="java">/**
 * Insertion Sort Implementation In Java
 * 
 * @author zparacha
 *
 * @param &lt;T&gt;
 */

package com.zparacha.algorithms;

import java.util.Arrays;

public class InsertionSort&lt;T extends Comparable&lt;T&gt;&gt; {
	int size;
	T[] data;

	public InsertionSort(int n) {
		data = (T[]) new Comparable[n];
	}

	public void insert(T a) {
		data[size++] = a;

	}

	public boolean isSmaller(T x, T y) {
		return x.compareTo(y) &lt; 0;
	}

	public void swap(int i, int j) {
		T temp = data[i];
		data[i] = data[j];
		data[j] = temp;
	}

	public void sort() {
		for (int i = 1; i &lt; size; i++) {
			for (int j = i; j &gt; 0 &amp;&amp; isSmaller(data[j], data[j - 1]); j--) {
				swap(j, j - 1);
			}
		}
	}

	public static void main(String[] args) {
		InsertionSort&lt;Integer&gt; is = new InsertionSort&lt;&gt;(5);
		is.insert(3);
		is.insert(1);
		is.insert(5);
		is.insert(4);
		is.insert(2);
		System.out.println(Arrays.toString(is.data));
		is.sort();
		System.out.println(Arrays.toString(is.data));
	}
}</pre>
</blockquote>
<p></p>

<div id="themify_builder_content-1635" data-postid="1635" class="themify_builder_content themify_builder_content-1635 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/insertion-sort-implementation-in-java/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1635</post-id>	</item>
		<item>
		<title>Selection Sort Algorithm in Java</title>
		<link>https://zparacha.com/selection-sort-in-java</link>
					<comments>https://zparacha.com/selection-sort-in-java#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Sun, 21 Jan 2018 01:27:53 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[array sort]]></category>
		<category><![CDATA[Selection Sort]]></category>
		<category><![CDATA[Sort]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1626</guid>

					<description><![CDATA[Selection sort is one of the simplest sorting algorithms. It is easy to implement but it is not very efficient. The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Selection sort is one of the simplest sorting algorithms. It is easy to implement but it is not very efficient.</p>
<blockquote>
<p>The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.</p>
<p><a href="https://en.wikipedia.org/wiki/Selection_sort">https://en.wikipedia.org/wiki/Selection_sort</a></p>
</blockquote>
<p>Following Java class shows how to implement Selection sort in Java.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">package com.zparacha.algorithms;

import java.util.Arrays;

/**
 * Selection Sort Implementation In Java
 * 
 * @author zparacha
 *
 * @param &lt;T&gt;
 */
public class SelectionSort&lt;T extends Comparable&lt;T&gt;&gt; {
	int size;
	T[] data;

	public SelectionSort(int n) {
		data = (T[]) new Comparable[n];
	}

	public void insert(T a) {
		data[size++] = a;
	}

	public boolean isSmaller(T x, T y) {
		return x.compareTo(y) &lt; 0;
	}

	public void swap(int i, int y) {
		T temp = data[i];
		data[i] = data[y];
		data[y] = temp;
	}

	public void selectionSort() {
		for (int i = 0; i &lt; size; i++) {
			int minIndex = i; //set the minIndex to current element
			for (int j = i + 1; j &lt; size; j++) {
				//compare the value of current element with remaining elements in 
				// the array. If a value smaller than current value is found, set the
				//minIndex to that value's index and keep comparing until end of 
				//array. 
				if (isSmaller(data[j], data[minIndex])) {
					minIndex = j;
				}
			}
			//if minIndex is different than the current value, it means 
			//that current value is not the smallest, swap it with the smallest value. 
			if (minIndex != i) {
				swap(i, minIndex);
			}
		}
	}

	public static void main(String[] args) {
		SelectionSort&lt;Integer&gt; ss = new SelectionSort&lt;&gt;(5);
		ss.insert(4);
		ss.insert(3);
		ss.insert(1);
		ss.insert(5);
		ss.insert(2);
		System.out.println(Arrays.toString(ss.data));
		ss.selectionSort();
		System.out.println(Arrays.toString(ss.data));
	}
}</pre>
<p> </p>

<div id="themify_builder_content-1626" data-postid="1626" class="themify_builder_content themify_builder_content-1626 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/selection-sort-in-java/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1626</post-id>	</item>
		<item>
		<title>How to calculate the height of a Non-Binary Tree</title>
		<link>https://zparacha.com/calculate-height-of-any-tree-in-java-non-binary-tree</link>
					<comments>https://zparacha.com/calculate-height-of-any-tree-in-java-non-binary-tree#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Mon, 01 Jan 2018 22:10:52 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Binary Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[Datastructure]]></category>
		<category><![CDATA[Height]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[Tree]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1614</guid>

					<description><![CDATA[Computing the height of a tree in Computer Science is very common. Most of the examples and online discussions talk about computing the height of a Binary Tree. The example method I am sharing can be used to compute the height of any tree. So even if you have a non-binary tree, you can use [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Computing the height of a tree in Computer Science is very common. Most of the examples and online discussions talk about computing the height of a Binary Tree.</p>
<p>The example method I am sharing can be used to compute the height of any tree. So even if you have a non-binary tree, you can use this method to get the tree height.</p>
<p>Since we are talking about a non-Binary tree, a node can have more than 2 children hence we have to declare the children as a list in the Node class. Here is the Node class.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">class Node&lt;E&gt; {
	int height;
	Node&lt;E&gt; parent;
	List&lt;Node&lt;E&gt;&gt;childern;
}</pre>
<p>As you can see we have a field of type Node to reference the parent node, and a list of Nodes to reference the children of this node.</p>
<p>Using this class definition with recursion we can compute the height of a tree (including non-Binary tree).</p>
<h4>getTreeHeight:</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="null">public int getTreeHeight(Node&lt;Integer&gt; root) {
   int height = 0;
    if (root == null ) {
	return height;
    }
    if (root.childern == null) {
	return 1;
  }

   for (Node&lt;Integer&gt; child : root.childern) {
	height = Math.max(height, getTreeHeight(child));
  }
   return height + 1;
}
</pre>
<p> </p>

<div id="themify_builder_content-1614" data-postid="1614" class="themify_builder_content themify_builder_content-1614 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/calculate-height-of-any-tree-in-java-non-binary-tree/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1614</post-id>	</item>
		<item>
		<title>Easiest way to calculate elapsed time in Java</title>
		<link>https://zparacha.com/easiest-way-to-calculate-elapsed-time-in-java</link>
					<comments>https://zparacha.com/easiest-way-to-calculate-elapsed-time-in-java#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Sat, 23 Dec 2017 16:53:56 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[elapsed time]]></category>
		<category><![CDATA[execution time]]></category>
		<category><![CDATA[nanoSecond]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1603</guid>

					<description><![CDATA[Quite often in our day-to-day programming, we need to compute how long a specific portion of the code takes to complete. For e.g; you might want to check how long a method takes to complete.  In Java, the simplest way to accomplish this is to use System.nanoTime() method. The following example shows how you can [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Quite often in our day-to-day programming, we need to compute how long a specific portion of the code takes to complete. For e.g; you might want to check how long a method takes to complete.  In Java, the simplest way to accomplish this is to use <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/System.html">System.nanoTime</a>() method.</p>
<p>The following example shows how you can do it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">long startTime = System.nanoTime();
System.out.println("Random string = " + getRandomAlphNumeircString(n));
long endTime = System.nanoTime();
double runTime = (endTime-startTime)/10000000000.0;
NumberFormat formatter = new DecimalFormat("#00.0000000000000000");
System.out.println("RumTIme = "+ formatter.format(runTime));</pre>
<p>Before calling the method for which we want to measure the execution time we record the current time in a local variable (startTime), we then call the method. After the method is complete we call System.nanoTime() to get the current time again. To find the elapsed time we subtract startTime from endTime and divide the result by 1 billion (to convert nanoseconds into seconds).</p>
<p>To display the elapsed time in a more readable format we used NumberFormat class, otherwise, since the values will be too small you will get the result in scientific notation.</p>

<div id="themify_builder_content-1603" data-postid="1603" class="themify_builder_content themify_builder_content-1603 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/easiest-way-to-calculate-elapsed-time-in-java/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1603</post-id>	</item>
		<item>
		<title>Java Regular Expression to Validate Social Security Number (SSN)</title>
		<link>https://zparacha.com/java-regular-expression-to-validate-social-security-number-ssn</link>
					<comments>https://zparacha.com/java-regular-expression-to-validate-social-security-number-ssn#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Fri, 08 Dec 2017 03:17:31 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[RegEx]]></category>
		<category><![CDATA[Regular Exp]]></category>
		<category><![CDATA[Social Security]]></category>
		<category><![CDATA[SSN]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1593</guid>

					<description><![CDATA[Here is a utility method to check if a given String is a valid Social Security number using Java Regular Expression.  /** isSSNValid: Validate Social Security number (SSN) using Java regex. * This method checks if the input string is a valid SSN. * @param email String. Social Security number to validate * @return boolean: [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Here is a utility method to check if a given String is a valid Social Security number using Java Regular Expression. <span id="more-1593"></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">/** isSSNValid: Validate Social Security number (SSN) using Java regex.
* This method checks if the input string is a valid SSN.
* @param email String. Social Security number to validate
* @return boolean: true if social security number is valid, false otherwise.
*/
 public static boolean isSSNValid(String ssn){
boolean isValid = false;
 /*SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx:
         ^\\d{3}: Starts with three numeric digits.
	[- ]?: Followed by an optional "-"
	\\d{2}: Two numeric digits after the optional "-"
	[- ]?: May contain an optional second "-" character.
	\\d{4}: ends with four numeric digits.

        Examples: 879-89-8989; 869878789 etc.
*/

//Initialize regex for SSN. 
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
CharSequence inputStr = ssn;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}</pre>
<p>This method will return true if the given String matches one of these SSN formats <strong>xxx-xx-xxxx</strong>, <strong>xxxxxxxxx</strong>,<strong> xxx-xxxxxx</strong>,<strong> xxxxx-xxxx</strong>:</p>
<h3>Social Security RegEx Explained:</h3>
<p>A String would be considered a valid Social Security Number (SSN) if it satisfies the following conditions:</p>
<p><strong>^\\d{3}</strong>: Starts with three numeric digits.</p>
<p><strong>[- ]?</strong>: Followed by an optional &#8220;-&#8220;</p>
<p><strong>\\d{2}</strong>: Two numeric digits after the optional &#8220;-&#8220;</p>
<p><strong>[- ]?</strong>: May contain an optional second &#8220;-&#8221; character.</p>
<p><strong>\\d{4}</strong>: ends with four numeric digits.</p>
<p> </p>
<p> </p>

<div id="themify_builder_content-1593" data-postid="1593" class="themify_builder_content themify_builder_content-1593 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/java-regular-expression-to-validate-social-security-number-ssn/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1593</post-id>	</item>
		<item>
		<title>Java Regular Expression to check if a String is a numeric value</title>
		<link>https://zparacha.com/java-regular-expression-to-check-if-a-string-is-a-number</link>
					<comments>https://zparacha.com/java-regular-expression-to-check-if-a-string-is-a-number#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Mon, 04 Dec 2017 20:40:45 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Number String]]></category>
		<category><![CDATA[Numeric String]]></category>
		<category><![CDATA[RegEx]]></category>
		<category><![CDATA[Regular Expression]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1579</guid>

					<description><![CDATA[Here is another method from my String utility class. This method uses a regular expression to check if a String is a numeric value. Look at the code, then read through the explanation that follows public static boolean isStringANumber(String str) { String regularExpression = "[-+]?[0-9]*\\.?[0-9]+$"; Pattern pattern = Pattern.compile(regularExpression); Matcher matcher = pattern.matcher(str); return matcher.matches(); } [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Here is another method from my String utility class. This method uses a regular expression to check if a String is a numeric value.</p>
<p>Look at the code, then read through the explanation that follows</p>
<p><span id="more-1579"></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">public static boolean isStringANumber(String str) {
		String regularExpression = "[-+]?[0-9]*\\.?[0-9]+$";
		Pattern pattern = Pattern.compile(regularExpression);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
				
	}</pre>
<p> </p>
<h3>Regular Expression Explained:</h3>
<p>A String would be a numeric value if it satisfies following conditions:</p>
<ol>
<li><strong>[-+]?</strong> can begin with an optional <strong>+</strong> or <strong>&#8211;</strong> sign</li>
<li><strong>[0-9]* </strong>may have any number of digits between 0 and 9.</li>
<li><strong>\\.?</strong> may have a decimal point</li>
<li><strong>[0-9]$</strong> the String must end with a digit.</li>
</ol>
<p> </p>

<div id="themify_builder_content-1579" data-postid="1579" class="themify_builder_content themify_builder_content-1579 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/java-regular-expression-to-check-if-a-string-is-a-number/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1579</post-id>	</item>
		<item>
		<title>How to delete Workspace from Eclipse Launcher Selection</title>
		<link>https://zparacha.com/how-to-delete-workspace-from-eclipse-launcher-selection</link>
					<comments>https://zparacha.com/how-to-delete-workspace-from-eclipse-launcher-selection#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Sun, 03 Dec 2017 23:05:15 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[Java IDE]]></category>
		<category><![CDATA[workspace]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1568</guid>

					<description><![CDATA[Launch Eclipse Click on Recent Workspaces Eclipse will list all previously used workspaces Right click on the workspace name that you want to remove Click on Remove from Launcher Selection text. This will remove the workspace from the drop-down list]]></description>
										<content:encoded><![CDATA[<ol>
<li>Launch Eclipse</li>
<p><img decoding="async" src="http://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces1-300x138.png" alt="" width="300" height="138" class="alignnone size-medium wp-image-1571" srcset="https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces1-300x138.png 300w, https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces1.png 616w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<li>Click on Recent Workspaces</li>
<p><img decoding="async" src="http://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces-300x134.png" alt="" width="300" height
="134" class="alignnone size-medium wp-image-1570" srcset="https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces-300x134.png 300w, https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces.png 614w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<li>Eclipse will list all previously used workspaces</li>
<p><img decoding="async" src="http://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces2-300x153.png" alt="" width="300" height="153" class="alignnone size-medium wp-image-1572" srcset="https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces2-300x153.png 300w, https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces2.png 610w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<li>Right click on the workspace name that you want to remove</li>
<p><img decoding="async" src="http://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces3-300x155.png" alt="" width="300" height="155" class="alignnone size-medium wp-image-1573" srcset="https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces3-300x155.png 300w, https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces3.png 613w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<li>Click on Remove from Launcher Selection text. This will remove the workspace from the drop-down list</li>
<p><img loading="lazy" decoding="async" src="http://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces4-300x145.png" alt="" width="300" height="145" class="alignnone size-medium wp-image-1574" srcset="https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces4-300x145.png 300w, https://zparacha.com/wp-content/uploads/2017/12/recentWorkspaces4.png 616w" sizes="(max-width: 300px) 100vw, 300px" />
</ol>
<div id="themify_builder_content-1568" data-postid="1568" class="themify_builder_content themify_builder_content-1568 themify_builder">

    </div>
<!-- /themify_builder_content -->]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/how-to-delete-workspace-from-eclipse-launcher-selection/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1568</post-id>	</item>
		<item>
		<title>How to generate random alpha numeric String in Java</title>
		<link>https://zparacha.com/how-to-generate-random-alpha-numeric-string-in-java</link>
					<comments>https://zparacha.com/how-to-generate-random-alpha-numeric-string-in-java#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Fri, 01 Dec 2017 22:20:01 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Alpha-nuermic]]></category>
		<category><![CDATA[AlphaNumeric]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1551</guid>

					<description><![CDATA[Following code is an example of generating a random alpha-numeric string using Java Random class. It is designed to generate random String of varying length based on the input parameter. Here is the code package com.zparacha.utils; import java.util.Random; import java.util.Scanner; public class StringUtilities { /** * * @param n * Desired Length of random string [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Following code is an example of generating a random alpha-numeric string using Java <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html">Random</a> class. It is designed to generate random String of varying length based on the input parameter.</p>
<p><span id="more-1551"></span><br />
Here is the code</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">package com.zparacha.utils;

import java.util.Random;
import java.util.Scanner;

public class StringUtilities {


	
	/**
	 * 
	 * @param n
	 *            Desired Length of random string
	 * @return
	 */
	public static String getRandomAlphNumeircString(int n) {
		// Get a n-digit multiplier of 10
		int maxDigit = (int) Math.pow(10, n - 2);
		Random random = new Random();
		/*
		 * Get a random character by getting a number from 0 t0 26 and then adding an
		 * 'A' to make it a character
		 * 
		 */
		char randomCharacter = (char) (random.nextInt(26) + 'A');
		/*
		 * Add 1*maxDigit to ensure that the number is equals to or greater than minimum
		 * value nextInt() method will return the number between 0 and 9*maxDigit
		 */
		int randomNumber = 1 * maxDigit + random.nextInt(9 * maxDigit);
		return String.valueOf(randomCharacter) + randomNumber;

	}
	public static void main(String args[]) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter desired lenght of random string: ");
		int n = in.nextInt();
		in.nextLine();
		System.out.println("Random string = " + getRandomAlphNumeircString(n));

	}
}</pre>
<p>Method getRandomAlphNumeircString accepts a numeric parameter for the desired length of the String.  Using the max length value it creates a variable maxDigit to a 10 muliple number.</p>
<p>It then calls <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html">Random.</a>nextInt() method to get a number between 0 and 26 (number of English alphabets) and then adds an &#8216;A&#8217; to convert that number into a character.</p>
<p>Next, it generates a Random number by calling <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html">Random.nextIn</a>t() method again.</p>
<p>Finally, it concatenates random character and the random number to generate a random alpha-numeric String.</p>
<p>main method is included to test getRandomAlphNumeircString method.</p>
<p>A sample run produced following output.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Enter desired lenght of random string: 10
Random string = W742681415
</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div id="themify_builder_content-1551" data-postid="1551" class="themify_builder_content themify_builder_content-1551 themify_builder">

    </div>
<!-- /themify_builder_content -->]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/how-to-generate-random-alpha-numeric-string-in-java/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1551</post-id>	</item>
		<item>
		<title>Java Scanner&#8217;s unexpected behavior following nextInt or nextDouble call</title>
		<link>https://zparacha.com/java-scanner-class-not-reading-correctly-after-nextint-or-nextdouble-method-call</link>
					<comments>https://zparacha.com/java-scanner-class-not-reading-correctly-after-nextint-or-nextdouble-method-call#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Tue, 28 Nov 2017 03:45:57 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[getDouble()]]></category>
		<category><![CDATA[getInt()]]></category>
		<category><![CDATA[Scaner]]></category>
		<category><![CDATA[system.in]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1536</guid>

					<description><![CDATA[Scanner is a utility class that provides methods to read command-line input. It is a very useful class, but you need to be aware of its unexpected behavior while reading numeric inputs. Consider the following example. try (Scanner in = new Scanner(System.in)) { System.out.print("Enter Item ID: "); String itemID = in.nextLine(); System.out.print("Enter item price: "); [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html">Scanner</a> is a utility class that provides methods to read command-line input. It is a very useful class, but you need to be aware of its unexpected behavior while reading numeric inputs.</p>
<p>Consider the following example.<span id="more-1536"></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">try (Scanner in = new Scanner(System.in)) {
	System.out.print("Enter Item ID: ");
	String itemID = in.nextLine();
	System.out.print("Enter item price: ");
	double price = in.nextDouble();
	System.out.println("Price of item " + itemID + " is $" + price);
} catch (Exception e) {
	e.printStackTrace();
}</pre>
<p>As expected the output from this code will look something like:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Enter Item ID: XY1234
Enter item price: 99.99
Price of item XY1234 is $99.99</pre>
<p>Everything worked as expected. The program prompted the user to enter an item ID and price. It read the values and then displayed them on console correctly.  Now, let&#8217;s see what happens if we ask the user to enter the price first followed by item ID.</p>
<pre class="EnlighterJSRAW">try (Scanner in = new Scanner(System.in)) {
	System.out.print("Enter item price: ");
	double price = in.nextDouble();
	System.out.print("Enter Item ID: ");
	String itemID = in.nextLine();
	System.out.println("Price of item " + itemID + " is $ " + price);
} catch (Exception e) {
			e.printStackTrace();
}</pre>
<p>This version resulted in a bizarre output.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Enter item price: 85.79
Enter Item ID: Price of item  is $ 85.79</pre>
<p>What happened here? The program didn&#8217;t wait for the user to enter item ID. After prompting the user to enter the item ID, it right away printed the final message with a blank item ID.</p>
<h4>Understanding Scanner.getDouble() and Scanner.getInt()</h4>
<p>What caused this behavior? To solve this mystery we have to understand how <strong>Scanner.getDouble()</strong> or <strong>Scanner.getInt()</strong> methods work.  Basically, Scanner&#8217;s get methods read the input character by character instead of reading the entire line at once. <strong>getDouble</strong> and <strong>getInt</strong> methods read input until they reach a non-numeric character. In this example, the user entered 99.99 and then hit enter (&#8220;<strong>\n</strong>&#8220;). So the character sequence would be <em>99.99\n</em>.  The method <strong>getDouble()</strong> reads the characters up to the last &#8220;9&#8221;. Since the next character is a non-numeric value (\n), the method stopped and returned the value 85.79 to be saved in the price variable. That left \n character in the buffer. Next, the program called nextLine() method. This method reads the input until it reaches the newline character (<strong>\n</strong>). Since the input stream had the \n character from the last input, the method reads it and returns immediately without allowing the user to input the ID.</p>
<p>To overcome this issue you have two options.</p>
<ol>
<li>Always call nextLine() method after calling nextInt() or nextDouble() method to consume line feed.</li>
<li>Always read command line input using nextLine() method and then converts numeric values from String to appropriate numeric type.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-highlight="4">try (Scanner in = new Scanner(System.in)) {
			System.out.print("Enter item price: ");
			double price = in.nextDouble();
			in.nextLine();
			System.out.print("Enter Item ID: ");
			String itemID = in.nextLine();
			System.out.println("Price of item " + itemID + " is $ " + price);
		} catch (Exception e) {
			e.printStackTrace();
		}</pre>
<p>Which gives correct results.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Enter item price: 85.79
Enter Item ID: XY1234
Price of item XY1234 is $ 85.79</pre>
<pre class="EnlighterJSRAW" data-enlighter-highlight="4">try (Scanner in = new Scanner(System.in)) {
			System.out.print("Enter item price: ");
			String priceStr = in.nextLine();
			double price = Double.valueOf(priceStr);
			System.out.print("Enter Item ID: ");
			String itemID = in.nextLine();
			System.out.println("Price of item " + itemID + " is $ " + price);
		} catch (Exception e) {
			e.printStackTrace();
		}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="null">Enter item price: 85.99
Enter Item ID: AB2314
Price of item AB2314 is $ 85.99</pre>
<p>Personally, I prefer the first approach.</p>

<div id="themify_builder_content-1536" data-postid="1536" class="themify_builder_content themify_builder_content-1536 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/java-scanner-class-not-reading-correctly-after-nextint-or-nextdouble-method-call/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1536</post-id>	</item>
		<item>
		<title>How to compare Java Strings correctly</title>
		<link>https://zparacha.com/how-to-compare-strings-in-java</link>
					<comments>https://zparacha.com/how-to-compare-strings-in-java#respond</comments>
		
		<dc:creator><![CDATA[parachaz]]></dc:creator>
		<pubDate>Sat, 25 Nov 2017 20:07:31 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://zparacha.com/?p=1505</guid>

					<description><![CDATA[One of the most common bugs I&#8217;ve seen in Java programs is the use of the == operator to compare two String objects. Most of the time the result may be accurate but it is not always guaranteed.We need to understand the difference between == and the Object.equals method. The == operator checks the reference [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the most common bugs I&#8217;ve seen in Java programs is the use of the <strong>==</strong> operator to compare two String objects. Most of the time the result may be accurate but it is not always guaranteed.<br />We need to understand the difference between <strong>==</strong> and the <strong>Object.equals</strong> method.</p>
<p><span id="more-1505"></span>The <strong>==</strong> operator checks the reference of two objects, i.e. it checks if both operands are the same objects. The <strong>Object.equals</strong> method, on the other hand, compares the value of the two operands.</p>
<p>Consider following example</p>
<pre class="EnlighterJSRAW" data-enlighter-language="java">package com.zparacha.utils; 
public class StringUtilities { 
  public static void main(String args[]) { 
     String a = new String("ABC"); 
     String b = "abc"; 
     String c = "abc"; 
     System.out.println("a = " + a + ", b = " + b + ", c = " + c); 
     System.out.println("a==b is " + (a==b)); 
     System.out.println("a==c is " + (a==c)); 
     System.out.println("b==c is " + (b==c)); 
     System.out.println("a.equals(c) is " + a.equals(c)); 
     System.out.println("b.equals(c) is " + b.equals(c)); 
  } 
}</pre>
<p> </p>
<p>Here is the output of this program</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">a = abc, b = abc, c = abc
a==b is false
a==c is false
b==c is true
a.equals(c) is true
b.equals(c) is true</pre>
<p>As you can see, all three String variables have the same value of &#8220;abc&#8221;, but the two comparison methods gave different results.</p>
<p>It depends on how the object is initialized. If a String object is created using String literal (e.g.; String b = &#8220;abc&#8221;; and String c = &#8220;abc&#8221;;), it may be <a href="https://en.wikipedia.org/wiki/String_interning">interned</a>. Interned means that the character sequence <code>"abc"</code>will be stored at a specific memory location, and whenever the same literal is used again, the JVM will not create a new String object instead it will use the reference of the first String object created with the same value. This is the most efficient way of creating String objects.</p>
<p>If you use a String constructor (like  <code class="EnlighterJSRAW" data-enlighter-language="java">String a = new String("abc");</code>), Java will always create a new object. Then, if you try to compare this String with another String using the == operator, you will always get a &#8220;<em>false</em>&#8221; return, since you are checking references to two distinct objects.</p>
<p>So, it is highly recommended to use String literals to create new String objects for efficiency and use Object.equals method to compare String to ensure that you get the expected results.</p>
<p> </p>

<div id="themify_builder_content-1505" data-postid="1505" class="themify_builder_content themify_builder_content-1505 themify_builder">

    </div>
]]></content:encoded>
					
					<wfw:commentRss>https://zparacha.com/how-to-compare-strings-in-java/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1505</post-id>	</item>
	</channel>
</rss>
