<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0">

<channel>
	<title>Crunchify</title>
	<atom:link href="https://crunchify.com/feed/" rel="self" type="application/rss+xml"/>
	<link>https://crunchify.com/</link>
	<description>Largest free Technical and Blogging resource site for Beginner. We help clients transform their great ideas into reality!</description>
	<lastBuildDate>Tue, 03 Feb 2026 16:06:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://crunchify.com/wp-content/uploads/2017/07/cropped-favicon-small-1.png</url>
	<title>Crunchify</title>
	<link>https://crunchify.com/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<itunes:explicit>no</itunes:explicit><itunes:subtitle>Largest free Technical and Blogging resource site for Beginner. We help clients transform their great ideas into reality!</itunes:subtitle><item>
		<title>In Java How to get list of files and search files from given folder? java.io.FilenameFilter Interface Example</title>
		<link>https://crunchify.com/in-java-how-to-get-list-of-files-and-search-a-file-providing-folder-path-filenamefilter-interface-example/</link>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Sat, 15 Mar 2025 06:34:30 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<category><![CDATA[Java8]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=13872</guid>

					<description><![CDATA[<p>In this tutorial we will go over FilenameFilter interface to search a file and list of files with given file extension (i.e. .png, .jpg, .jpeg, .txt, .pdf). lifeFiles returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of [&#8230;]</p>
<p>The post <a href="https://crunchify.com/in-java-how-to-get-list-of-files-and-search-a-file-providing-folder-path-filenamefilter-interface-example/">In Java How to get list of files and search files from given folder? java.io.FilenameFilter Interface Example</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example.png"><img fetchpriority="high" decoding="async" width="2794" height="1360" src="https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example.png" alt="In Java How to get list of files and search a file providing folder path? FilenameFilter Interface Example" class="wp-image-13873" srcset="https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example.png 2794w, https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example-768x374.png 768w, https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example-1536x748.png 1536w, https://crunchify.com/wp-content/uploads/2021/06/In-Java-How-to-get-list-of-files-and-search-a-file-providing-folder-path-FilenameFilter-Interface-Example-2048x997.png 2048w" sizes="(max-width: 2794px) 100vw, 2794px" /></a></figure>



<p>In this tutorial we will go over <code>FilenameFilter interface</code> to search a file and list of files with given file extension (i.e. .png, <a href="https://crunchify.com/in-java-how-to-convert-png-image-to-jpg-using-imageio-and-bufferedimage/" target="_blank" rel="noreferrer noopener">.jpg</a>, .jpeg, .txt, .pdf).</p>



<p><code>lifeFiles</code> returns an array of <a href="https://crunchify.com/what-is-an-abstract-class-and-abstract-method-in-java-when-should-i-use-it/" target="_blank" rel="noreferrer noopener">abstract</a> pathnames denoting the <a href="https://crunchify.com/executable-java-jar-on-linux/" target="_blank" rel="noreferrer noopener">files and directories</a> in the directory denoted by this abstract pathname that satisfy the specified filter. </p>



<p>The behavior of this <a href="https://crunchify.com/java-method-hiding-and-overriding-override-static-method-in-java/" target="_blank" rel="noreferrer noopener">method</a> is the same as that of the listFiles() method, except that the pathnames in the returned <a href="https://crunchify.com/in-java-how-to-join-arrays-3-ways-apache-commons-arrayutils-java-8-streams-and-simple-apis/" target="_blank" rel="noreferrer noopener">array</a> must satisfy the filter. </p>



<p>If the given <a href="https://crunchify.com/wordpress-how-to-redirect-author-archive-link-to-your-about-page/" target="_blank" rel="noreferrer noopener">filter</a> is null then all pathnames are accepted. Otherwise, a pathname satisfies the filter if and only if the value true results when the <code>FilenameFilter.accept</code>(File, <a href="https://crunchify.com/java8-stringjoiner-string-join-and-collectors-joining-tutorial-with-all-details-5-different-ways/" target="_blank" rel="noreferrer noopener">String</a>) method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Some time back we have published a similar tutorial on how to <a href="https://crunchify.com/in-java-how-to-perform-file-search-operation-using-java-nio-file-interface-tutorial-on-file-and-directory-operations/" target="_blank" rel="noreferrer noopener">search a file using java.nio.file package</a>. Take a look at that too when you get a chance. java.nio.file defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.</p></blockquote>



<h3 class="wp-block-heading">Let&#8217;s get started:</h3>



<h3 class="wp-block-heading">Create CrunchifyFileSearchUsingFilenameFilter.java</h3>



<pre class="EnlighterJSRAW">package crunchify.com.tutorial;

import java.io.File;
import java.io.FilenameFilter;

/**
 * @author Crunchify.com
 * In Java How to get list of files and search a file providing folder path?
 * FilenameFilter Interface Example
 */

public class CrunchifyFileSearchUsingFilenameFilter {
	
	public static void main(String&#091;] args) {
		String crunchifyDirectory = &quot;/Users/app/Download&quot;;
		String crunchifyExt = &quot;.txt&quot;;
		
		crunchifySearchFilesWithExtension(crunchifyDirectory, crunchifyExt);
	}
	
	// FileNameFilter: Instances of classes that implement this interface are used to filter filenames.
	// These instances are used to filter directory listings in the list method of class File, and by the Abstract Window
	// Toolkit&#039;s file dialog component.
	public static class crunchifyFileNameFiler implements FilenameFilter {
		
		private final String crunchifyExt;
		
		public crunchifyFileNameFiler(String crunchifyExt) {
			
			// toLoverCase() Converts all of the characters in this String to lower case using the rules of the default locale.
			// This is equivalent to calling toLowerCase(Locale.getDefault()).
			this.crunchifyExt = crunchifyExt.toLowerCase();
		}
		
		@Override
		public boolean accept(File crunchifyDirectory, String crunchifyName) {
			
			// endsWith(): Tests if this string ends with the specified suffix.
			return crunchifyName.toLowerCase().endsWith(crunchifyExt);
		}
		
	}
	
	private static void crunchifySearchFilesWithExtension(String crunchifyDirectory, String crunchifyExt) {
		
		// File class - Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
		File crunchifyFiles = new File(crunchifyDirectory);
		
		// exists(): Tests whether the file or directory denoted by this abstract pathname exists.
		if (!crunchifyFiles.exists())
			crunchifyPrint(crunchifyDirectory + &quot; Hmm.. Wrong Directory. Directory doesn&#039;t exists...&quot; + crunchifyDirectory);
		
		// lifeFiles: Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of the crunchifyListOfFiles() method, except that the pathnames in the returned array must satisfy the filter.
		// If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the filter if and only if the value true results when the FilenameFilter.accept(File, String) method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes.
		File&#091;] crunchifyListOfFiles = crunchifyFiles.listFiles(new crunchifyFileNameFiler(crunchifyExt));
		
		assert crunchifyListOfFiles != null;
		int crunchifyCounter = 0;
		if (crunchifyListOfFiles.length == 0) {
			crunchifyPrint(crunchifyDirectory + &quot;Hmm.. Sorry. No file exist with given file extension: &quot; + crunchifyExt);
		} else {
			for (File crunchifyFile : crunchifyListOfFiles) {
				crunchifyCounter++;
				// separator: The system-dependent default name-separator character, represented as a string for convenience.
				// This string contains a single character, namely separatorChar.
				crunchifyPrint(&quot;File # &quot; + crunchifyCounter + &quot;: &quot; + crunchifyDirectory + File.separator + crunchifyFile.getName());
			}
		}
	}
	
	// Simple Print Utility
	private static void crunchifyPrint(String print) {
		System.out.println(print);
	}
	
}</pre>



<p>Just run above program as a <a href="https://crunchify.com/better-logging-for-your-enterprise-java-application-crunchifybetterlog4jlogging-java/" target="_blank" rel="noreferrer noopener">Java Application</a>.</p>



<h3 class="wp-block-heading">IntelliJ IDEA console result:</h3>



<pre class="EnlighterJSRAW">File # 1: /Users/app/Download/task.txt
File # 2: /Users/app/Download/robots_files_copy.txt
File # 3: /Users/app/Download/robots_nio.txt
File # 4: /Users/app/Download/robots_httpcomponents.txt
File # 5: /Users/app/Download/robots.txt
File # 6: /Users/app/Download/robots_commons_io.txt
File # 7: /Users/app/Download/robots_stream.txt
File # 8: /Users/app/Download/docs-cpt-crunchify.txt

Process finished with exit code 0</pre>



<p>Let me know if you face any <a href="https://crunchify.com/how-to-fix-access-control-allow-origin-issue-for-your-https-enabled-wordpress-site-and-maxcdn/" target="_blank" rel="noreferrer noopener">issue</a> running above <a href="https://crunchify.com/write-java-program-to-print-fibonacci-series-upto-n-number/" target="_blank" rel="noreferrer noopener">Java Program</a>.</p>



<hr class="wp-block-separator is-style-wide"/>



<h3 class="wp-block-heading">Option-2) as mentioned above search file using java.nio.file package.</h3>



<figure class="wp-block-embed is-type-wp-embed is-provider-crunchify wp-block-embed-crunchify"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="5tlv9bJm7K"><a href="https://crunchify.com/in-java-how-to-perform-file-search-operation-using-java-nio-file-interface-tutorial-on-file-and-directory-operations/">In Java How to Perform File Search Operation using java.nio.file interface? Tutorial on File and Directory Operations</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;In Java How to Perform File Search Operation using java.nio.file interface? Tutorial on File and Directory Operations&#8221; &#8212; Crunchify" src="https://crunchify.com/in-java-how-to-perform-file-search-operation-using-java-nio-file-interface-tutorial-on-file-and-directory-operations/embed/#?secret=0WpmJM0tCJ#?secret=5tlv9bJm7K" data-secret="5tlv9bJm7K" width="500" height="282" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>
<p>The post <a href="https://crunchify.com/in-java-how-to-get-list-of-files-and-search-a-file-providing-folder-path-filenamefilter-interface-example/">In Java How to get list of files and search files from given folder? java.io.FilenameFilter Interface Example</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Optimize Code Using Binary Notation?</title>
		<link>https://crunchify.com/optimize-code-using-binary-notation/</link>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Sat, 08 Mar 2025 22:07:20 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=15132</guid>

					<description><![CDATA[<p>Efficient programming often involves optimizing code for speed and memory usage. One powerful but underutilized technique is leveraging binary notation to optimize operations at a low level. Binary operations can lead to significant performance improvements, especially in systems programming, embedded development, and high-performance applications. Why Use Binary Notation? Binary notation allows for more efficient computations, [&#8230;]</p>
<p>The post <a href="https://crunchify.com/optimize-code-using-binary-notation/">How to Optimize Code Using Binary Notation?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><img decoding="async" width="660" height="301" src="https://crunchify.com/wp-content/uploads/2025/03/Optimize-Code-Using-Binary-Notation.png" alt="" class="wp-image-15133"/></figure>



<p>Efficient <a href="https://crunchify.com/java-primitive-data-types-details/">programming</a> often involves optimizing code for speed and memory usage. One powerful but underutilized technique is leveraging <strong>binary notation</strong> to optimize operations at a low level. Binary operations can lead to significant performance improvements, especially in systems programming, embedded development, and high-performance applications.</p>



<h3 class="wp-block-heading">Why Use Binary Notation?</h3>



<p>Binary notation allows for more efficient computations, reducing reliance on arithmetic operations that consume extra <a href="https://crunchify.com/finding-the-3rd-smallest-number-in-java-a-complete-guide/">processing power</a>. Many modern processors handle bitwise operations faster than traditional arithmetic calculations.</p>



<h3 class="wp-block-heading">Common Binary Operations for Optimization</h3>



<h3 class="wp-block-heading">1. Bitwise AND (<code>&amp;</code>) and OR (<code>|</code>) for Conditional Checks</h3>



<p>Instead of using multiple <a href="https://crunchify.com/java-runtime-get-free-used-and-total-memory-in-java/">conditional statements</a>, you can optimize checks with bitwise operations.</p>



<h4 class="wp-block-heading">Example:</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Check if a number is even
if (num &amp; 1 == 0) {
    printf("Even number");
}</pre>



<p>This avoids modulus (<code>%</code>) operations, which are generally more expensive than bitwise operations.</p>



<h3 class="wp-block-heading">2. Bitwise Shift (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>) for Fast Multiplication and Division</h3>



<p>Bitwise shifts provide a faster way to multiply or divide by <a href="https://crunchify.com/optimize-code-using-binary-notation/">powers</a> of two.</p>



<h4 class="wp-block-heading">Example:</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">int multiplyBy8 = num &lt;&lt; 3; // Equivalent to num * 8
int divideBy4 = num >> 2;   // Equivalent to num / 4</pre>



<p>This is much faster than using <code>*</code> or <code>/</code>, as shifting only requires a single <a href="https://crunchify.com/maven-artifacts-error-jms-jmxtools-jmxri-dependencies/">CPU cycle</a>.</p>



<h3 class="wp-block-heading">3. Using XOR (<code>^</code>) for Swapping Variables Without a Temp Variable</h3>



<p>XOR can be used to swap two variables without needing extra memory.</p>



<h4 class="wp-block-heading">Example:</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = x ^ y;
y = x ^ y;
x = x ^ y;</pre>



<p>This can be useful in constrained <a href="https://crunchify.com/kinsta-modern-secure-and-super-fast-wordpress-hosting/">environments</a> like <a href="https://crunchify.com/wp-content/uploads/2022/01/Create-new-Mailerlite-Embedded-Form.png">embedded</a> systems.</p>



<h3 class="wp-block-heading">4. Checking if a Number is a Power of Two</h3>



<p>A quick way to determine if a number is a power of two is using the following condition:</p>



<h4 class="wp-block-heading">Example:</h4>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if ((num &amp; (num - 1)) == 0 &amp;&amp; num != 0) {
    printf("Power of two");
}</pre>



<p>This takes advantage of the binary representation of powers of two, where only a <a href="https://crunchify.com/embracing-the-gutenberg-revolution-why-its-time-to-bid-adieu-to-classic-editing-in-wordpress/">single bit</a> is set.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>Utilizing binary notation and bitwise operations can significantly optimize code performance. These <a href="https://crunchify.com/on-page-seo-rank-first-on-google/">techniques</a> are especially useful in low-level programming, graphics rendering, cryptography, and embedded systems. By understanding and applying binary optimizations, <a href="https://crunchify.com/wp-content/uploads/2012/11/Create-New-Facebook-App-Crunchify-Developers1.png">developers</a> can write faster and more efficient code.</p>



<h3 class="wp-block-heading">Full Java program:</h3>



<pre class="EnlighterJSRAW">public class CrunchifyBinaryOptimization {
    public static void main(String&#091;] args) {
        int crunchifyNum = 8;

        // Check if a number is even using bitwise AND
        if ((crunchifyNum &amp; 1) == 0) {
            System.out.println(crunchifyNum + &quot; is even&quot;);
        } else {
            System.out.println(crunchifyNum + &quot; is odd&quot;);
        }

        // Multiply and divide using bitwise shift
        int crunchifyMultiplyBy8 = crunchifyNum &lt;&lt; 3; // num * 8
        int crunchifyDivideBy4 = crunchifyNum &gt;&gt; 2;   // num / 4
        System.out.println(&quot;Multiply by 8: &quot; + crunchifyMultiplyBy8);
        System.out.println(&quot;Divide by 4: &quot; + crunchifyDivideBy4);

        // Swap two numbers using XOR
        int crunchifyA = 5, crunchifyB = 3;
        System.out.println(&quot;Before swap: a = &quot; + crunchifyA + &quot;, b = &quot; + crunchifyB);
        crunchifyA = crunchifyA ^ crunchifyB;
        crunchifyB = crunchifyA ^ crunchifyB;
        crunchifyA = crunchifyA ^ crunchifyB;
        System.out.println(&quot;After swap: a = &quot; + crunchifyA + &quot;, b = &quot; + crunchifyB);

        // Check if a number is a power of two
        if ((crunchifyNum &amp; (crunchifyNum - 1)) == 0 &amp;&amp; crunchifyNum != 0) {
            System.out.println(crunchifyNum + &quot; is a power of two&quot;);
        } else {
            System.out.println(crunchifyNum + &quot; is not a power of two&quot;);
        }
    }
}</pre>



<h3 class="wp-block-heading">Console Result:</h3>



<pre class="EnlighterJSRAW">8 is even
Multiply by 8: 64
Divide by 4: 2
Before swap: a = 5, b = 3
After swap: a = 3, b = 5
8 is a power of two</pre>
<p>The post <a href="https://crunchify.com/optimize-code-using-binary-notation/">How to Optimize Code Using Binary Notation?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Delete a Local Git Branch?</title>
		<link>https://crunchify.com/how-to-delete-a-local-git-branch/</link>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Sat, 08 Mar 2025 22:01:19 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<category><![CDATA[GitHub]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=15130</guid>

					<description><![CDATA[<p>When working with Git, managing branches efficiently is crucial for keeping your repository clean and organized. If you no longer need a local branch, deleting it can help maintain clarity in your project. This guide will walk you through the steps to safely delete a local Git branch. Checking Your Existing Branches Before deleting a [&#8230;]</p>
<p>The post <a href="https://crunchify.com/how-to-delete-a-local-git-branch/">How to Delete a Local Git Branch?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://crunchify.com/wp-content/uploads/2025/03/How-to-Delete-a-Local-Git-Branch.png"><img loading="lazy" decoding="async" width="1548" height="1378" src="https://crunchify.com/wp-content/uploads/2025/03/How-to-Delete-a-Local-Git-Branch.png" alt="" class="wp-image-15131" srcset="https://crunchify.com/wp-content/uploads/2025/03/How-to-Delete-a-Local-Git-Branch.png 1548w, https://crunchify.com/wp-content/uploads/2025/03/How-to-Delete-a-Local-Git-Branch-768x684.png 768w, https://crunchify.com/wp-content/uploads/2025/03/How-to-Delete-a-Local-Git-Branch-1536x1367.png 1536w" sizes="auto, (max-width: 1548px) 100vw, 1548px" /></a></figure>



<p>When working with <a href="https://crunchify.com/tag/github/">Git</a>, managing branches efficiently is crucial for keeping your repository clean and organized. If you no longer need a <a href="https://crunchify.com/how-to-install-and-configure-prometheus-on-linux-ubuntu-and-centos/">local branch</a>, deleting it can help maintain clarity in your project. This guide will walk you through the steps to safely delete a local Git branch.</p>



<h3 class="wp-block-heading">Checking Your Existing Branches</h3>



<p>Before deleting a branch, it&#8217;s a good practice to check your existing branches to ensure you are removing the correct one. Use the following command to list all local branches:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git branch</pre>



<p>This <a href="https://crunchify.com/wp-content/uploads/2017/10/Linux-Systemd-Command-CheatSheet.png">command</a> will display all local branches, with an asterisk (*) indicating the currently active branch.</p>



<h3 class="wp-block-heading">Deleting a Local Git Branch</h3>



<p>To delete a local branch, ensure that you are <strong>not currently on</strong> the branch you want to remove. If necessary, switch to another branch using:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git checkout main  # or any other branch</pre>



<p>Then, delete the target branch with the <a href="https://crunchify.com/setup-wordpress-amazon-aws-ec2/">following command</a>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git branch -d branch_name</pre>



<p>Replace <code>branch_name</code> with the actual branch name you wish to delete.</p>



<h3 class="wp-block-heading">Forcing Branch Deletion</h3>



<p>If the branch you are trying to delete contains unmerged changes, Git will prevent deletion to avoid potential <a href="https://crunchify.com/best-way-to-optimize-all-wordpress-images-using-optimus-plugin-we-tried-and-loved-it-speed-optimization-goal/">data loss</a>. If you are certain that you want to delete the branch, use the <strong>force delete</strong> command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git branch -D branch_name</pre>



<p>This will forcefully delete the branch regardless of its merge status.</p>



<h3 class="wp-block-heading">Verifying Branch Deletion</h3>



<p>After deletion, confirm that the branch is removed by <a href="https://crunchify.com/wp-content/uploads/2020/09/crunchifyHttpClient.send-java-API.png">running</a>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git branch</pre>



<p>This will list the remaining branches, ensuring the deleted branch no longer appears.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>Deleting a local Git branch is a simple yet essential task for repository <a href="https://crunchify.com/memcached-java-client-tutorial-using-com-whalin-memcached-java-client-and-com-googlecode-xmemcached-libraries/">maintenance</a>. By following these steps, you can keep your Git workspace organized and clutter-free. Always double-check before forcing a deletion to avoid accidental data loss.</p>



<h3 class="wp-block-heading">Here is a complete Java Program:</h3>



<pre class="EnlighterJSRAW">import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CrunchifyGitHubBranchDeletion {
    public static void main(String&#091;] args) {
        String crunchifyRepoOwner = &quot;your-username&quot;; // Change this to your GitHub username or organization
        String crunchifyRepoName = &quot;your-repo&quot;;      // Change this to your repository name
        String crunchifyBranchName = &quot;your-branch&quot;;  // Change this to the branch you want to delete
        String crunchifyToken = &quot;your-github-token&quot;; // Change this to your personal access token

        crunchifyDeleteGitHubBranch(crunchifyRepoOwner, crunchifyRepoName, crunchifyBranchName, crunchifyToken);
    }

    public static void crunchifyDeleteGitHubBranch(String crunchifyOwner, String crunchifyRepo, String crunchifyBranch, String crunchifyToken) {
        try {
            String crunchifyUrlString = &quot;https://api.github.com/repos/&quot; + crunchifyOwner + &quot;/&quot; + crunchifyRepo + &quot;/git/refs/heads/&quot; + crunchifyBranch;
            URL crunchifyUrl = new URL(crunchifyUrlString);
            HttpURLConnection crunchifyConn = (HttpURLConnection) crunchifyUrl.openConnection();
            crunchifyConn.setRequestMethod(&quot;DELETE&quot;);
            crunchifyConn.setRequestProperty(&quot;Authorization&quot;, &quot;token &quot; + crunchifyToken);
            crunchifyConn.setRequestProperty(&quot;Accept&quot;, &quot;application/vnd.github.v3+json&quot;);
            crunchifyConn.setDoOutput(true);

            int crunchifyResponseCode = crunchifyConn.getResponseCode();
            if (crunchifyResponseCode == 204) {
                System.out.println(&quot;Crunchify branch deleted successfully.&quot;);
            } else {
                System.out.println(&quot;Failed to delete crunchify branch. Response Code: &quot; + crunchifyResponseCode);
            }
        } catch (Exception crunchifyE) {
            System.out.println(&quot;Crunchify Error: &quot; + crunchifyE.getMessage());
        }
    }
}</pre>
<p>The post <a href="https://crunchify.com/how-to-delete-a-local-git-branch/">How to Delete a Local Git Branch?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>In Java How to Find Maximum Occurrence of Words from Text File?</title>
		<link>https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/</link>
					<comments>https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Wed, 05 Mar 2025 21:34:00 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=4221</guid>

					<description><![CDATA[<p>In this Java tutorial, you will learn&#160;How to Find Maximum Occurrence of Words from given Text File? Here is a logic for getting top element: Create a class CrunchifyComparable that can store the String value of the word and the number of occurrences it appears. Implement the Comparable interface for this class to sort by occurrences first [&#8230;]</p>
<p>The post <a href="https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/">In Java How to Find Maximum Occurrence of Words from Text File?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File.png"><img loading="lazy" decoding="async" width="2836" height="1462" src="https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File.png" alt="In Java How to Find Maximum Occurrence of Words from Text File?" class="wp-image-13971" srcset="https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File.png 2836w, https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File-768x396.png 768w, https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File-1536x792.png 1536w, https://crunchify.com/wp-content/uploads/2021/09/In-Java-How-to-Find-Maximum-Occurrence-of-Words-from-Text-File-2048x1056.png 2048w" sizes="auto, (max-width: 2836px) 100vw, 2836px" /></a></figure>



<p>In this <a href="https://crunchify.com/microsoft-translator-text-api-example/" target="_blank" rel="noreferrer noopener">Java tutorial</a>, you will learn&nbsp;How to Find <a href="https://crunchify.com/java-find-line-with-maximum-words/" target="_blank" rel="noreferrer noopener">Maximum Occurrence</a> of Words from given <a href="https://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/" target="_blank" rel="noreferrer noopener">Text File</a>?</p>



<h3 class="wp-block-heading">Here is a logic for getting top element:</h3>



<ol class="wp-block-list"><li>Create a class <code>CrunchifyComparable</code> that can store the <a href="https://crunchify.com/convert-primitive-array-to-list-in-java8/" target="_blank" rel="noreferrer noopener">String</a> value of the word and the number of occurrences it appears.</li><li>Implement the <a href="https://crunchify.com/how-to-sort-hashmap-by-key-and-value-in-java8-complete-tutorial/" target="_blank" rel="noreferrer noopener">Comparable</a> <a href="https://crunchify.com/what-is-an-interface-in-java-how-its-used-java-tutorial-example-attached/" target="_blank" rel="noreferrer noopener">interface</a> for this class to <code>sort by occurrences first and then alphabetically</code> if the number of occurrences is the same</li><li><code>crunchifyFindMaxOccurrence</code> method, you create a new List of <code>CrunchifyComparable</code> from your original <a href="https://crunchify.com/java-hashmap-containskeyobject-key-and-containsvalueobject-value-check-if-key-exists-in-map/" target="_blank" rel="noreferrer noopener">map</a>. You add the entries of this to your List</li><li><a href="https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/" target="_blank" rel="noreferrer noopener">Sort this list</a></li><li>Take the n-first items of this list using subList</li><li>Add <a href="https://crunchify.com/5-different-ways-to-download-a-file-from-any-given-url-in-java/" target="_blank" rel="noreferrer noopener">Strings</a> to the <code>List&lt;String></code> and you return it</li></ol>



<p><code>Another most read</code>: Find more information on <a href="https://crunchify.com/how-to-override-equals-and-hashcode-method-in-java/" target="_blank" rel="noopener noreferrer">equals() and hashcode()</a></p>



<h3 class="wp-block-heading"><strong>Java Code:</strong></h3>



<p>Create class CrunchifyFindMaxOccurrence.java. Put <a href="https://crunchify.com/simple-way-to-add-any-html-code-to-header-body-and-footer-in-wordpress/" target="_blank" rel="noreferrer noopener">below code</a> into file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-title="">package crunchify.com.tutorials;

import java.io.*;
import java.util.*;

public class CrunchifyFindMaxOccurrence {
	
	/**
	 * @author Crunchify.com
	 * In Java How to Find Maximum Occurrence of Words from Text File?
	 */
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		// File: An abstract representation of file and directory pathnames.
		// User interfaces and operating systems use system-dependent pathname strings to name files and directories.
		// This class presents an abstract, system-independent view of hierarchical pathnames.
		File file = new File(&quot;/Users/app/Download/crunchify.txt&quot;);
		
		// BufferedReader: Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
		// The buffer size may be specified, or the default size may be used.
		// The default is large enough for most purposes.
		BufferedReader bufferedReader = null;
		bufferedReader = new BufferedReader(new FileReader(file));
		String inputLine = null;
		
		// Map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
		Map&lt;String, Integer&gt; crunchifyMap = new HashMap&lt;&gt;();
		
		try {
			while ((inputLine = bufferedReader.readLine()) != null) {
				
				// split(): Splits this string around matches of the given regular expression.
				// This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero.
				// Trailing empty strings are therefore not included in the resulting array.
				String[] words = inputLine.split(&quot;[ \n\t\r.,;:!?(){}]&quot;);
				
				for (String word : words) {
					String key = word.toLowerCase(); // remove .toLowerCase for Case Sensitive result.
					if (key.length() &gt; 0) {
						if (crunchifyMap.get(key) == null) {
							crunchifyMap.put(key, 1);
						} else {
							int value = crunchifyMap.get(key).intValue();
							value++;
							crunchifyMap.put(key, value);
						}
					}
				}
			}
			
			// Set: A collection that contains no duplicate elements.
			// More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2),
			// and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
			Set&lt;Map.Entry&lt;String, Integer&gt;&gt; entrySet = crunchifyMap.entrySet();
			crunchifyPrint(&quot;Words&quot; + &quot;\t\t&quot; + &quot;# of Occurances&quot;);
			
			for (Map.Entry&lt;String, Integer&gt; entry : entrySet) {
				crunchifyPrint(entry.getKey() + &quot;\t\t&quot; + entry.getValue());
			}
			List&lt;String&gt; myTopOccurrence = crunchifyFindMaxOccurrence(crunchifyMap, 1);
			crunchifyPrint(&quot;\nMaximum Occurrence of Word in file: &quot;);
			
			for (String result : myTopOccurrence) {
				crunchifyPrint(&quot;==&gt; &quot; + result);
			}
			
			// IOException: Signals that an I/O exception of some sort has occurred.
			// This class is the general class of exceptions produced by failed or interrupted I/O operations.
		} catch (IOException error) {
			crunchifyPrint(&quot;Invalid File&quot;);
		} finally {
			bufferedReader.close();
		}
		
	}
	
	private static void crunchifyPrint(String s) {
		System.out.println(s);
	}
	
	/**
	 * @param map = All Words in map
	 * @param n   = How many top elements you want to print? If n=1 it will print the highest occurrence word. If n=2 it
	 *            will print top 2 highest occurrence words.
	 * @returns list of String
	 */
	public static List&lt;String&gt; crunchifyFindMaxOccurrence(Map&lt;String, Integer&gt; map, int n) {
		List&lt;CrunchifyComparable&gt; l = new ArrayList&lt;&gt;();
		for (Map.Entry&lt;String, Integer&gt; entry : map.entrySet())
			l.add(new CrunchifyComparable(entry.getKey(), entry.getValue()));
		
		// sort(): Sorts the specified list into ascending order, according to the natural ordering of its elements.
		// All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable
		// (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
		Collections.sort(l);
		List&lt;String&gt; list = new ArrayList&lt;&gt;();
		
		// subList(): Returns a view of the portion of this list between the specified fromIndex,
		// inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)
		// The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
		// The returned list supports all of the optional list operations supported by this list.
		for (CrunchifyComparable w : l.subList(0, n))
			list.add(w.wordFromFile + &quot;:&quot; + w.numberOfOccurrence);
		return list;
	}
}

class CrunchifyComparable implements Comparable&lt;CrunchifyComparable&gt; {
	public String wordFromFile;
	public int numberOfOccurrence;
	
	public CrunchifyComparable(String wordFromFile, int numberOfOccurrence) {
		super();
		this.wordFromFile = wordFromFile;
		this.numberOfOccurrence = numberOfOccurrence;
	}
	
	@Override
	public int compareTo(CrunchifyComparable arg0) {
		int crunchifyCompare = Integer.compare(arg0.numberOfOccurrence, this.numberOfOccurrence);
		return crunchifyCompare != 0 ? crunchifyCompare : wordFromFile.compareTo(arg0.wordFromFile);
	}
	
	@Override
	public int hashCode() {
		final int uniqueNumber = 19;
		int crunchifyResult = 9;
		crunchifyResult = uniqueNumber * crunchifyResult + numberOfOccurrence;
		
		// hasCode(): Returns a hash code for this string. The hash code for a String object is computed as
		//       s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
		//
		// using int arithmetic, where s[i] is the ith character of the string, n is the length of the string,
		// and ^ indicates exponentiation. (The hash value of the empty string is zero.)
		crunchifyResult = uniqueNumber * crunchifyResult + ((wordFromFile == null) ? 0 : wordFromFile.hashCode());
		return crunchifyResult;
	}
	
	// Override: Indicates that a method declaration is intended to override a method declaration in a supertype.
	// If a method is annotated with this annotation type compilers are required
	// to generate an error message unless at least one of the following conditions hold:
	// The method does override or implement a method declared in a supertype.
	// The method has a signature that is override-equivalent to that of any public method declared in Object.
	@Override
	public boolean equals(Object crunchifyObj) {
		if (this == crunchifyObj)
			return true;
		if (crunchifyObj == null)
			return false;
		if (getClass() != crunchifyObj.getClass())
			return false;
		CrunchifyComparable other = (CrunchifyComparable) crunchifyObj;
		if (numberOfOccurrence != other.numberOfOccurrence)
			return false;
		if (wordFromFile == null) {
			if (other.wordFromFile != null)
				return false;
		} else if (!wordFromFile.equals(other.wordFromFile))
			return false;
		return true;
	}
	
}
</pre>



<h3 class="wp-block-heading">Example-1&nbsp;file:</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">Crunchify is the largest free, premium, technical &amp; blogging resource site for beginners, who are passionate &amp; have the desire to excel in the online world. Attracting over 16 million monthly users, we are leading &amp; trusted tech + blogging resource for all. We also help clients transform their great ideas into reality!

Crunchify, Crunchify, Crunchify.com</pre>



<h3 class="wp-block-heading">Output:</h3>



<p>Here is a <a href="https://crunchify.com/how-to-create-1st-spring-boot-helloworld-application-in-intellij-idea-with-few-simple-steps/" target="_blank" rel="noreferrer noopener">IntelliJ IDEA</a> console result. Run above <a href="https://crunchify.com/log-file-tailer-tail-f-implementation-in-java-best-way-to-tail-any-file-programmatically/" target="_blank" rel="noreferrer noopener">program</a> as a <a href="https://crunchify.com/how-to-start-embedded-http-jersey-server-during-java-application-startup/" target="_blank" rel="noreferrer noopener">Java Application</a> and you are will see result as below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50339:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 
-classpath /Users/app/crunchify/github/CrunchifyTutorials/target/classes:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/zxing-2.1.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-logging-1.1.2.jar
:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-collections-3.2.1.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/javax.mail.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-io-2.4.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-lang-2.6.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-configuration-1.9.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/log4j-1.2.17.jar:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/commons-beanutils-1.8.3.jar
:/Users/app/Library/Application Support/JetBrains/IntelliJIdea2021.2/javascript/extLibs/http_code.jquery.com_jquery-3.6.0.js:/Users/app/.m2/repository/org/glassfish/javax.json/1.1.4/javax.json-1.1.4.jar:/Users/app/.m2/repository/com/github/wnameless/json-flattener/0.2.2/json-flattener-0.2.2.jar:/Users/app/.m2/repository/com/eclipsesource/minimal-json/minimal-json/0.9.4/minimal-json-0.9.4.jar:/Users/app/.m2/repository/com/github/wnameless/json/json-flattener/0.12.0/json-flattener-0.12.0.jar
:/Users/app/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.12.0/jackson-databind-2.12.0.jar:/Users/app/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.12.0/jackson-annotations-2.12.0.jar:/Users/app/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.12.0/jackson-core-2.12.0.jar
:/Users/app/.m2/repository/org/apache/commons/commons-text/1.9/commons-text-1.9.jar:/Users/app/.m2/repository/com/github/wnameless/json/json-base/2.0.0/json-base-2.0.0.jar:/Users/app/.m2/repository/commons-io/commons-io/2.10.0/commons-io-2.10.0.jar
:/Users/app/.m2/repository/com/google/code/gson/gson/2.8.7/gson-2.8.7.jar:/Users/app/.m2/repository/net/jodah/expiringmap/0.5.9/expiringmap-0.5.9.jar:/Users/app/.m2/repository/org/apache/httpcomponents/httpclient/4.5.13/httpclient-4.5.13.jar:/Users/app/.m2/repository/org/apache/httpcomponents/httpcore/4.4.13/httpcore-4.4.13.jar
:/Users/app/.m2/repository/commons-codec/commons-codec/1.11/commons-codec-1.11.jar:/Users/app/.m2/repository/org/json/json/20210307/json-20210307.jar:/Users/app/.m2/repository/net/spy/spymemcached/2.12.3/spymemcached-2.12.3.jar:/Users/app/.m2/repository/com/whalin/Memcached-Java-Client/3.0.2/Memcached-Java-Client-3.0.2.jar
:/Users/app/.m2/repository/commons-pool/commons-pool/1.5.6/commons-pool-1.5.6.jar:/Users/app/.m2/repository/com/googlecode/xmemcached/xmemcached/2.4.7/xmemcached-2.4.7.jar:/Users/app/.m2/repository/com/paypal/sdk/rest-api-sdk/1.14.0/rest-api-sdk-1.14.0.jar
:/Users/app/.m2/repository/org/apache/commons/commons-dbcp2/2.8.0/commons-dbcp2-2.8.0.jar:/Users/app/.m2/repository/org/apache/commons/commons-pool2/2.8.1/commons-pool2-2.8.1.jar:/Users/app/.m2/repository/commons-dbcp/commons-dbcp/20030825.184428/commons-dbcp-20030825.184428.jar:/Users/app/.m2/repository/javax/ws/rs/javax.ws.rs-api/2.1.1/javax.ws.rs-api-2.1.1.jar:/Users/app/.m2/repository/org/hamcrest/hamcrest-all/1.3/hamcrest-all-1.3.jar:/Users/app/.m2/repository/org/apache/logging/log4j/log4j-core/2.14.1/log4j-core-2.14.1.jar:/Users/app/.m2/repository/org/apache/logging/log4j/log4j-api/2.14.1/log4j-api-2.14.1.jar
:/Users/app/.m2/repository/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar:/Users/app/.m2/repository/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar:/Users/app/.m2/repository/com/google/guava/listenablefuture/9999.0-empty-to-avoid-conflict-with-guava/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar:/Users/app/.m2/repository/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar
:/Users/app/.m2/repository/org/checkerframework/checker-qual/3.8.0/checker-qual-3.8.0.jar:/Users/app/.m2/repository/com/google/errorprone/error_prone_annotations/2.5.1/error_prone_annotations-2.5.1.jar:/Users/app/.m2/repository/com/google/j2objc/j2objc-annotations/1.3/j2objc-annotations-1.3.jar:/Users/app/.m2/repository/com/googlecode/json-simple/json-simple/1.1.1/json-simple-1.1.1.jar:/Users/app/.m2/repository/junit/junit/4.10/junit-4.10.jar:/Users/app/.m2/repository/org/hamcrest/hamcrest-core/1.1/hamcrest-core-1.1.jar:/Users/app/.m2/repository/commons-net/commons-net/3.8.0/commons-net-3.8.0.jar:/Users/app/.m2/repository/org/ow2/asm/asm/9.1/asm-9.1.jar:/Users/app/.m2/repository/axis/axis/1.4/axis-1.4.jar:/Users/app/.m2/repository/org/apache/axis/axis-jaxrpc/1.4/axis-jaxrpc-1.4.jar:/Users/app/.m2/repository/axis/axis-wsdl4j/1.5.1/axis-wsdl4j-1.5.1.jar:/Users/app/.m2/repository/commons-beanutils/commons-beanutils/1.9.4/commons-beanutils-1.9.4.jar:/Users/app/.m2/repository/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar:/Users/app/.m2/repository/org/apache/commons/commons-collections4/4.4/commons-collections4-4.4.jar:/Users/app/.m2/repository/org/apache/commons/commons-configuration2/2.7/commons-configuration2-2.7.jar
:/Users/app/.m2/repository/commons-discovery/commons-discovery/0.5/commons-discovery-0.5.jar:/Users/app/.m2/repository/org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar:/Users/app/.m2/repository/commons-logging/commons-logging/1.2/commons-logging-1.2.jar:/Users/app/.m2/repository/commons-logging/commons-logging-api/1.1/commons-logging-api-1.1.jar:/Users/app/.m2/repository/javax/mail/javax.mail-api/1.6.2/javax.mail-api-1.6.2.jar:/Users/app/.m2/repository/javax/mail/mail/1.4.7/mail-1.4.7.jar:/Users/app/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar:/Users/app/.m2/repository/javax/xml/jaxrpc-api/1.1/jaxrpc-api-1.1.jar:/Users/app/.m2/repository/org/apache/axis/axis-saaj/1.4/axis-saaj- 1.4.jar:/Users/app/.m2/repository/wsdl4j/wsdl4j/1.6.3/wsdl4j-1.6.3.jar:/Users/app/.m2/repository/com/google/zxing/core/3.4.1/core-3.4.1.jar:/Users/app/.m2/repository/org/apache/commons/commons-compress/1.20/commons-compress-1.20.jar:/Users/app/.m2/repository/mysql/mysql-connector-java/8.0.25/mysql-connector-java-8.0.25.jar:/Users/app/.m2/repository/com/google/protobuf/protobuf-java/3.11.4/protobuf-java-3.11.4.jar
:/Users/app/.m2/repository/ch/qos/logback/logback-classic/1.3.0-alpha5/logback-classic-1.3.0-alpha5.jar:/Users/app/.m2/repository/ch/qos/logback/logback-core/1.3.0-alpha5/logback-core-1.3.0-alpha5.jar:/Users/app/.m2/repository/com/sun/mail/javax.mail/1.6.2/javax.mail-1.6.2.jar:/Users/app/.m2/repository/edu/washington/cs/types/checker/checker-framework/1.7.0/checker-framework-1.7.0.jar:/Users/app/.m2/repository/commons-validator/commons-validator/1.7/commons-validator-1.7.jar:/Users/app/.m2/repository/commons-digester/commons-digester/2.1/commons-digester-2.1.jar:/Users/app/.m2/repository/org/springframework/spring-context/5.3.8/spring-context-5.3.8.jar:/Users/app/.m2/repository/org/springframework/spring-aop/5.3.8/spring-aop-5.3.8.jar:/Users/app/.m2/repository/org/springframework/spring-beans/5.3.8/spring-beans-5.3.8.jar
:/Users/app/.m2/repository/org/springframework/spring-core/5.3.8/spring-core-5.3.8.jar:/Users/app/.m2/repository/org/springframework/spring-jcl/5.3.8/spring-jcl-5.3.8.jar:/Users/app/.m2/repository/org/springframework/spring-expression/5.3.8/spring-expression-5.3.8.jar:/Users/app/.m2/repository/org/springframework/spring-context-support/5.3.8/spring-context-support-5.3.8.jar:/Users/app/.m2/repository/org/slf4j/slf4j-api/1.7.31/slf4j-api-1.7.31.jar:/Users/app/.m2/repository/org/slf4j/jul-to-slf4j/1.7.31/jul-to-slf4j-1.7.31.jar:/Users/app/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.31/jcl-over-slf4j-1.7.31.jar:/Users/app/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.31/log4j-over-slf4j-1.7.31.jar crunchify.com.tutorials.CrunchifyFindMaxOccurrence


Words		# of Occurances
com		1
largest		1
clients		1
technical		1
passionate		1
leading		1
for		2
their		1
we		2
into		1
transform		1
premium		1
world		1
are		2
attracting		1
have		1
free		1
crunchify		4
over		1
tech		1
all		1
desire		1
blogging		2
resource		2
in		1
16		1
&amp;		3
is		1
also		1
ideas		1
+		1
great		1
users		1
the		3
excel		1
help		1
site		1
million		1
trusted		1
beginners		1
monthly		1
online		1
reality		1
to		1
who		1

Maximum Occurrence of Word in file: 
==&gt; crunchify:4

Process finished with exit code 0
</pre>



<h3 class="wp-block-heading">Example-2 File:</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">this and and and then and this</pre>



<h5 class="wp-block-heading">Output:</h5>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">Words		# of Occurances
and		4
this		2
then		1

Maixmum Occurance of Word in file: 
==&gt; and:4</pre>



<p>Are you looking for more <a href="https://crunchify.com/java-synchronized-collections-examples-java-util-collections/" target="_blank" rel="noreferrer noopener">java tutorials</a>? Look at this <a href="https://crunchify.com/category/java-tutorials/" target="_blank" rel="noopener noreferrer">collection</a>.</p>
<p>The post <a href="https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/">In Java How to Find Maximum Occurrence of Words from Text File?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Simple Scroll to Top Button in WordPress Footer without any JavaScript loading – Genesis Framework Tips</title>
		<link>https://crunchify.com/simple-scroll-to-top-button-in-wordpress-footer-without-any-javascript-loading-genesis-framework-tips/</link>
					<comments>https://crunchify.com/simple-scroll-to-top-button-in-wordpress-footer-without-any-javascript-loading-genesis-framework-tips/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Wed, 05 Mar 2025 20:55:00 +0000</pubDate>
				<category><![CDATA[JavaScript jQuery Tutorials]]></category>
		<category><![CDATA[functions.php]]></category>
		<category><![CDATA[style.css]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=8329</guid>

					<description><![CDATA[<p>Scroll to Top / Back to Top button at the bottom of page is sometime very essential&#160;mainly if you have long posts. Here on Crunchify,&#160;we do have most of Java tutorials&#160;and Blogging&#160;tips and those are very lengthy. If you are looking for Sticky Scroll To Top button which uses Javascript then follow this Tutorial: https://crunchify.com/how-to-add-smooth-scrolling-back-to-top-button-to-your-wordpress-blog/ [&#8230;]</p>
<p>The post <a href="https://crunchify.com/simple-scroll-to-top-button-in-wordpress-footer-without-any-javascript-loading-genesis-framework-tips/">Simple Scroll to Top Button in WordPress Footer without any JavaScript loading &#8211; Genesis Framework Tips</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2016/03/Simple-Scroll-to-Top-Button-without-Java-Script-Crunchify.png" rel="attachment wp-att-8330"><img loading="lazy" decoding="async" width="1302" height="506" src="https://crunchify.com/wp-content/uploads/2016/03/Simple-Scroll-to-Top-Button-without-Java-Script-Crunchify.png" alt="Simple-Scroll-to-Top-Button-without-Java-Script-Crunchify" class="wp-image-8330" srcset="https://crunchify.com/wp-content/uploads/2016/03/Simple-Scroll-to-Top-Button-without-Java-Script-Crunchify.png 1302w, https://crunchify.com/wp-content/uploads/2016/03/Simple-Scroll-to-Top-Button-without-Java-Script-Crunchify-768x298.png 768w" sizes="auto, (max-width: 1302px) 100vw, 1302px" /></a></figure>



<p><code>Scroll to Top</code> / <code>Back to Top</code> button at the bottom of page is sometime very essential&nbsp;mainly if you have <a href="https://crunchify.com/step-by-step-guide-on-how-to-enable-ssl-https-on-wordpress-blog-generate-csr-and-crt/" target="_blank" rel="noopener noreferrer">long posts</a>. Here on Crunchify,&nbsp;we do have most of <a href="https://crunchify.com/microsoft-translator-text-api-example/" target="_blank" rel="noreferrer noopener">Java tutorials</a>&nbsp;and <a href="https://crunchify.com/7-tips-for-business-growth-and-wordpress-post-todo-checklist/" target="_blank" rel="noreferrer noopener">Blogging&nbsp;tips</a> and those are very lengthy.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>If you are looking for <strong>Sticky</strong> Scroll To Top button which uses <strong>Javascript</strong> then follow this Tutorial: <a href="https://crunchify.com/how-to-add-smooth-scrolling-back-to-top-button-to-your-wordpress-blog/" target="_blank" rel="noreferrer noopener">https://crunchify.com/how-to-add-smooth-scrolling-back-to-top-button-to-your-wordpress-blog/</a> </p>
</blockquote>



<p>In this tutorial we will go over steps on how to add simple <code>Scroll to Top button</code> in <a href="https://crunchify.com/introducing-all-in-one-optimizer-customizer-wordpress-performance-plugin/" target="_blank" rel="noreferrer noopener">WordPress</a> footer without any <a href="https://crunchify.com/how-to-create-social-sharing-button-without-any-plugin-and-script-loading-wordpress-speed-optimization-goal/" target="_blank" rel="noreferrer noopener">JavaScript</a> loading.</p>



<h4 class="wp-block-heading">If you have below other questions then you are at right place:</h4>



<ul class="wp-block-list">
<li>How to add back to top button without jQuery</li>



<li>Non <a href="https://crunchify.com/how-to-change-easy-digital-download-checkout-form-label-and-text-works-with-any-frontend-labels/" target="_blank" rel="noreferrer noopener">floating</a> Scroll to top button</li>



<li>Scroll to top without any performance impact</li>



<li>Genesis Framework &#8211; how to add custom ID attribute?</li>
</ul>



<h3 class="wp-block-heading">Let&#8217;s get started:</h3>



<h3 class="wp-block-heading">Step-1</h3>



<p>On Crunchify&nbsp;we are using <a href="https://crunchify.com/refer/genesis" target="_blank" rel="noopener noreferrer">Genesis Framework</a>. By default my <a href="https://crunchify.com/genesis-framework-how-to-configure-genesis-enews-extended-newsletter-widget-correct-way-in-sidebar/" target="_blank" rel="noopener noreferrer">Eleven40 theme</a> doesn&#8217;t include any ID attribute into <a href="https://crunchify.com/how-to-modify-customize-genesis-framework-breadcrumb-for-your-wordpress-blog/" target="_blank" rel="noopener noreferrer">header</a> or body.</p>



<p>So we need to&nbsp;add <code>ID</code> called&nbsp;<code>content</code> manually using hook <code>genesis_attr_content</code>. I&#8217;m going to list all custom attribute for <a href="https://crunchify.com/refer/genesis" target="_blank" rel="noopener noreferrer">Genesis</a> framework in next post.</p>



<h3 class="wp-block-heading">Step-2</h3>



<p>Place below code into your child theme&#8217;s <a href="https://crunchify.com/how-to-disable-double-line-breaks-with-paragraph-elements-in-wordpress/" target="_blank" rel="noreferrer noopener">functions.php</a> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">add_filter( &#039;genesis_attr_content&#039;, &#039;custom_attributes_content&#039; );

function custom_attributes_content( $attributes ) {
    $attributes[&#039;id&#039;] = &#039;content&#039;;
    return $attributes;
}</pre>



<p>This will add custom <code>id="content"</code> attribute into <code>HTML</code> body. Take a look at below screenshot.</p>



<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2016/03/add-custom-attribute-idcontent-in-WordPress.png" rel="attachment wp-att-8331"><img loading="lazy" decoding="async" width="752" height="170" src="https://crunchify.com/wp-content/uploads/2016/03/add-custom-attribute-idcontent-in-WordPress.png" alt="add-custom-attribute-idcontent-in-WordPress" class="wp-image-8331"/></a></figure>



<h3 class="wp-block-heading">Step-3</h3>



<p>Now we need to place <code>arrow element (↑)</code> into footer. Add below code into your custom <a href="https://crunchify.com/how-to-add-an-extra-widget-section-before-footer-widget-area-genesis-wordpress-framework/" target="_blank" rel="noreferrer noopener">footer section</a> of your <code>functions.php</code> file</p>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-highlight="11" data-enlighter-title="">// Customize the entire footer
remove_action( &#039;genesis_footer&#039;, &#039;genesis_do_footer&#039; );
add_action( &#039;genesis_footer&#039;, &#039;custom_footer&#039; );
function custom_footer() {
	?&gt;

&lt;div class=&quot;creds-left&quot;&gt;
&lt;p&gt;&amp;copy; 2012-16 &lt;a href=&quot;https://crunchify.com&quot; target=&quot;_blank&quot;&gt;Crunchify.com&lt;/a&gt;. &amp;nbsp;&amp;#149;&amp;nbsp; All Rights Reserved. &lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;crunchify-top&quot;&gt;&lt;a href=&quot;#content&quot;&gt;↑&lt;/a&gt;&lt;/p&gt;

&lt;div style=&quot;clear:both&quot;&gt;&lt;/div&gt;
	&lt;?php
}</pre>



<p>Mainly take a look at highlighted <code>line 11</code>.</p>



<h3 class="wp-block-heading">Step-4</h3>



<p>Now we need to beautify arrow icon and place it into middle of footer section. Simply put below <a href="https://crunchify.com/social-media-css-sprite-example-for-your-wordpress-blog/" target="_blank" rel="noopener noreferrer">CSS code</a> into your Genesis framework Child&#8217;s <code><a href="https://crunchify.com/how-to-exclude-jsp-file-validation-in-eclipse/" target="_blank" rel="noopener noreferrer">style.css</a></code> file</p>



<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">.crunchify-top {
    clear: both;
    left: 50%;
    margin-bottom: 20px !important;
    margin-top: 20px !important;
}
.crunchify-top a {
    color: #fff;
    background-color: #333;
    border-radius: 50%;
    cursor: pointer;
    padding: 10px;
}
.crunchify-top a:hover {
    color: #fff;
    background-color: #999;
}</pre>



<p>Modify <a href="https://crunchify.com/how-to-add-beautiful-link-underline-animation-with-simple-css/" target="_blank" rel="noreferrer noopener">CSS color</a> as your theme&#8217;s need.</p>



<h3 class="wp-block-heading">Step-5</h3>



<p>Clean up <a href="https://crunchify.com/speed-up-your-wordpress-blog-by-tuning-wp-super-cache/" target="_blank" rel="noopener noreferrer">site cache</a> and if you are using <a href="https://crunchify.com/step-by-step-guide-to-setup-maxcdn-content-delivery-network-correctly-on-wordpress-with-wp-super-cache-plugin/" target="_blank" rel="noopener noreferrer">MaxCDN</a> or other CDN provider then clear your CDN cache too. Refresh your page and you&nbsp;should scroll to top button in the footer section exactly same way you see it&nbsp;on Crunchify.</p>



<h4 class="wp-block-heading">NOTE:</h4>



<ul class="wp-block-list">
<li>Again follow this tutorial if&nbsp;you want <a href="https://crunchify.com/how-to-add-smooth-scrolling-back-to-top-button-to-your-wordpress-blog/" target="_blank" rel="noopener noreferrer">Sticky Scroll to Top</a>&nbsp;button..</li>



<li>Above tips will work for <a href="https://crunchify.com/genesis-enews-extended-and-mailchimp-step-by-step-guide-to-setup-it-up-correctly-on-wordpress-site/">Genesis Framework</a> but not limited to other WordPress framework too. Hope this works. Keep visiting and happy blogging.</li>
</ul>
<p>The post <a href="https://crunchify.com/simple-scroll-to-top-button-in-wordpress-footer-without-any-javascript-loading-genesis-framework-tips/">Simple Scroll to Top Button in WordPress Footer without any JavaScript loading &#8211; Genesis Framework Tips</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/simple-scroll-to-top-button-in-wordpress-footer-without-any-javascript-loading-genesis-framework-tips/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Have you noticed Race Condition in Java Multi-threading Concurrency Example? How to deal with it?</title>
		<link>https://crunchify.com/have-you-noticed-race-condition-in-java-multithreading-concurrency-example-how-to-deal-with-it/</link>
					<comments>https://crunchify.com/have-you-noticed-race-condition-in-java-multithreading-concurrency-example-how-to-deal-with-it/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Fri, 29 Nov 2024 08:30:00 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=6490</guid>

					<description><![CDATA[<p>Sometime back I&#8217;ve written an article on Producer Consumer Example and how to handle read/write operation better way in Java. On the similar note, in this tutorial we will discuss something on Race Condition and Thread locking. If you have any of the below questions then you are at right place: Why Race Condition in [&#8230;]</p>
<p>The post <a href="https://crunchify.com/have-you-noticed-race-condition-in-java-multithreading-concurrency-example-how-to-deal-with-it/">Have you noticed Race Condition in Java Multi-threading Concurrency Example? How to deal with it?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2014/09/Have-you-noticed-Race-Condition-in-Java-Multi-threading-Concurrency-Example.png"><img loading="lazy" decoding="async" width="1410" height="588" src="https://crunchify.com/wp-content/uploads/2014/09/Have-you-noticed-Race-Condition-in-Java-Multi-threading-Concurrency-Example.png" alt="have-you-noticed-race-condition-in-java-multi-threading-concurrency-example" class="wp-image-10174" srcset="https://crunchify.com/wp-content/uploads/2014/09/Have-you-noticed-Race-Condition-in-Java-Multi-threading-Concurrency-Example.png 1410w, https://crunchify.com/wp-content/uploads/2014/09/Have-you-noticed-Race-Condition-in-Java-Multi-threading-Concurrency-Example-768x320.png 768w" sizes="auto, (max-width: 1410px) 100vw, 1410px" /></a></figure>



<p>Sometime back I&#8217;ve written an article on <a href="https://crunchify.com/java-producer-consumer-example-handle-concurrent-read-write/" target="_blank" rel="noopener noreferrer">Producer Consumer Example</a> and how to handle read/write <a href="https://crunchify.com/in-java-how-to-perform-file-search-operation-using-java-nio-file-interface-tutorial-on-file-and-directory-operations/" target="_blank" rel="noopener noreferrer">operation</a> better way in Java. On the similar note, in this tutorial we will discuss something on <code>Race Condition</code> and <code>Thread locking</code>.</p>



<p>If you have any of the below questions then you are at right place:</p>



<ul class="wp-block-list">
<li>Java race condition example</li>



<li><a href="https://crunchify.com/what-is-java-semaphore-and-mutex-java-concurrency-multithread-explained-with-example/" target="_blank" rel="noopener noreferrer">mutex</a> java example</li>



<li><a href="https://crunchify.com/what-is-lock-unlock-reentrantlock-trylock-and-how-its-different-from-synchronized-block-in-java/" target="_blank" rel="noopener noreferrer">multithreading</a> &#8211; What is a race condition?</li>



<li>Race Conditions and Critical Sections</li>



<li>What is race condition?</li>



<li>How to deal with Race Condition in <a href="https://crunchify.com/how-to-use-hamcrest-assertthat-matchers-to-create-junit-testcases-in-java-complete-tutorial/" target="_blank" rel="noopener noreferrer">Java</a> with Example</li>
</ul>



<h3 class="wp-block-heading">Why Race Condition in Java Occurs?</h3>



<p>Race condition in Java occurs when <code>two or more threads</code> try to modify/update shared data at the <code>same time</code>.</p>



<h3 class="wp-block-heading">Let&#8217;s take a look at below Program logic:</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>This is very simple banking example in which you will <code>deposit</code>&nbsp;and <code>withdraw</code> amounts <code>100 times</code>. You will deposit&nbsp;$100 total 100 times = $100 x 100 = $10,000 and you will withdraw $50 total 100 times = $50 x 100 = $5,000. At the end of program completion you should have $5000 in your bank.</p>
</blockquote>



<h4 class="wp-block-heading">Here are the steps:</h4>



<ol class="wp-block-list">
<li>Create class CrunchifyRaceCondition.java</li>



<li>Create class CrunchifyTransaction.java</li>



<li>Create class CrunchifyBankAccount.java</li>



<li>We will <a href="https://crunchify.com/exception-in-thread-main-java-lang-unsupportedclassversionerror-comcrunchifymain-unsupported-major-minor-version-51-0/" target="_blank" rel="noopener noreferrer">run class</a>&nbsp;CrunchifyRaceCondition and it will start deposit&nbsp;and withdraw loop 100 times.</li>



<li>We will run it <code>with <a href="https://crunchify.com/java-concurrentnavigablemap-and-concurrentskiplistmap-example-with-all-details/" target="_blank" rel="noopener noreferrer">Synchronized</a> block</code>&nbsp;to check result</li>



<li>We will run it <code>without Synchronized block</code> to check result</li>
</ol>



<h3 class="wp-block-heading">CrunchifyRaceCondition.java</h3>



<pre class="EnlighterJSRAW">package com.crunchify.tutorial;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyRaceCondition {

	public static void main(String&#091;] args) {
		CrunchifyBankAccount crunchifyAccount = new CrunchifyBankAccount(&quot;CrunchifyAccountNumber&quot;);

		// Total Expected Deposit: 10000 (100 x 100)
		for (int i = 0; i &lt; 100; i++) {
			CrunchifyTransaction t = new CrunchifyTransaction(crunchifyAccount, CrunchifyTransaction.TransactionType.DEPOSIT_MONEY, 100);
			t.start();
		}

		// Total Expected Withdrawal: 5000 (100 x 50)
		for (int i = 0; i &lt; 100; i++) {
			CrunchifyTransaction t = new CrunchifyTransaction(crunchifyAccount, CrunchifyTransaction.TransactionType.WITHDRAW_MONEY, 50);
			t.start();

		}

		// Let&#039;s just wait for a second to make sure all thread execution completes.
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println(e);
		}

		// Expected account balance is 5000
		System.out.println(&quot;Final Account Balance: &quot; + crunchifyAccount.getAccountBalance());
	}
}</pre>



<h3 class="wp-block-heading">CrunchifyTransaction.java</h3>



<pre class="EnlighterJSRAW">package com.crunchify.tutorial;

/**
 * @author Crunchify.com
 */

class CrunchifyTransaction extends Thread {

	public static enum TransactionType {
		DEPOSIT_MONEY(1), WITHDRAW_MONEY(2);

		private TransactionType(int value) {
		}
	};

	private TransactionType transactionType;
	private CrunchifyBankAccount crunchifyAccount;
	private double crunchifyAmount;

	/*
	 * If transactionType == 1, depositAmount() else if transactionType == 2 withdrawAmount()
	 */
	public CrunchifyTransaction(CrunchifyBankAccount crunchifyAccount, TransactionType transactionType, double crunchifyAmount) {
		this.transactionType = transactionType;
		this.crunchifyAccount = crunchifyAccount;
		this.crunchifyAmount = crunchifyAmount;
	}

	public void run() {
		switch (this.transactionType) {
		case DEPOSIT_MONEY:
			depositAmount();
			printBalance();
			break;
		case WITHDRAW_MONEY:
			withdrawAmount();
			printBalance();
			break;
		default:
			System.out.println(&quot;NOT A VALID TRANSACTION&quot;);
		}
	}

	public void depositAmount() {
		this.crunchifyAccount.depositAmount(this.crunchifyAmount);
	}

	public void withdrawAmount() {
		this.crunchifyAccount.withdrawAmount(crunchifyAmount);
	}

	public void printBalance() {
		System.out.println(Thread.currentThread().getName() + &quot; : TransactionType: &quot; + this.transactionType + &quot;, Amount: &quot; + this.crunchifyAmount);
		System.out.println(&quot;New Account Balance: &quot; + this.crunchifyAccount.getAccountBalance());
	}
}</pre>



<h3 class="wp-block-heading">CrunchifyBankAccount.java</h3>



<pre class="EnlighterJSRAW">package com.crunchify.tutorial;

/**
 * @author Crunchify.com
 */

class CrunchifyBankAccount {
	private String crunchifyAccountNumber;
	private double crunchifyAccountBalance;

	public String getAccountNumber() {
		return crunchifyAccountNumber;
	}

	public double getAccountBalance() {
		return crunchifyAccountBalance;
	}

	public CrunchifyBankAccount(String crunchifyAccountNumber) {
		this.crunchifyAccountNumber = crunchifyAccountNumber;
	}

	// Make a note of this line -- synchronized keyword added
	public synchronized boolean depositAmount(double amount) {
		if (amount &lt; 0) {
			return false;
		} else {
			crunchifyAccountBalance = crunchifyAccountBalance + amount;
			return true;
		}
	}

	// Make a note of this line -- synchronized keyword added
	public synchronized boolean withdrawAmount(double amount) {
		if (amount &gt; crunchifyAccountBalance) {
			return false;
		} else {
			crunchifyAccountBalance = crunchifyAccountBalance - amount;
			return true;
		}
	}
}</pre>



<p>Please check line 24 and 34 above. Keep that <code>Synchronized</code> keyword and run your <a href="https://crunchify.com/how-to-create-zip-or-tar-programatically-in-java-using-apache-commons-archivers-and-compressors/" target="_blank" rel="noopener noreferrer">program</a>. You should see correct result as you see it in below image.</p>



<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2014/09/Java-Synchronized-Block-Keyword-Crunchify.png"><img loading="lazy" decoding="async" width="1200" height="352" src="https://crunchify.com/wp-content/uploads/2014/09/Java-Synchronized-Block-Keyword-Crunchify.png" alt="Java Synchronized Block Keyword - Crunchify" class="wp-image-6713" srcset="https://crunchify.com/wp-content/uploads/2014/09/Java-Synchronized-Block-Keyword-Crunchify.png 1200w, https://crunchify.com/wp-content/uploads/2014/09/Java-Synchronized-Block-Keyword-Crunchify-768x225.png 768w" sizes="auto, (max-width: 1200px) 100vw, 1200px" /></a></figure>



<h3 class="wp-block-heading">Now remove synchronized keyword from line 24 and 34 and run the same program.</h3>



<p>You may need to run this program <a href="https://crunchify.com/how-to-merge-concat-multiple-jsonobjects-in-java-best-way-to-combine-two-jsonobjects/" target="_blank" rel="noopener noreferrer">multiple</a> times to see an issue. In java there is no guarantee you will see Race condition all the times.</p>



<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2014/09/Java-without-Synchronized-Block-Keyword-Crunchify.png"><img loading="lazy" decoding="async" width="1202" height="342" src="https://crunchify.com/wp-content/uploads/2014/09/Java-without-Synchronized-Block-Keyword-Crunchify.png" alt="Java without Synchronized Block Keyword - Crunchify" class="wp-image-6712" srcset="https://crunchify.com/wp-content/uploads/2014/09/Java-without-Synchronized-Block-Keyword-Crunchify.png 1202w, https://crunchify.com/wp-content/uploads/2014/09/Java-without-Synchronized-Block-Keyword-Crunchify-768x219.png 768w, https://crunchify.com/wp-content/uploads/2014/09/Java-without-Synchronized-Block-Keyword-Crunchify-1200x342.png 1200w" sizes="auto, (max-width: 1202px) 100vw, 1202px" /></a></figure>



<p>If you have <a href="https://crunchify.com/better-logging-for-your-enterprise-java-application-crunchifybetterlog4jlogging-java/" target="_blank" rel="noopener noreferrer">enterprise level application</a> and you are talking of millions of transaction per seconds then race condition may cause disaster for your company.</p>



<h3 class="wp-block-heading">Now question is how to avoid Race Condition in your Java Application?</h3>



<ol class="wp-block-list">
<li>If the race condition is in updates to some shared <a href="https://crunchify.com/how-to-create-a-simple-in-memory-cache-in-java-lightweight-cache/" target="_blank" rel="noopener noreferrer">in-memory</a> data structures, you need to synchronize access and updates to the <a href="https://crunchify.com/how-to-implement-selection-sort-algorithm-in-java-detailed-explanation/" target="_blank" rel="noopener noreferrer">data structure</a> appropriate way.</li>



<li>If the race condition is in updates to the your database, you need to restructure your SQL to use transactions at the appropriate level of granularity.</li>



<li>It&#8217;s not a bad idea to do Load testing before going live in production. More load may cause rare Race Condition. Better to fix it before rather fixing it later.</li>



<li>Make sure you have no global variable that you write to.</li>



<li>In Java, <a href="https://crunchify.com/create-simple-pojo-and-multiple-java-reflection-examples/" target="_blank" rel="noopener noreferrer">every object</a> has one and only one monitor and mutex associated with it. The single monitor has several doors into it, however, each indicated by the&nbsp;<a href="https://crunchify.com/java-synchronized-collections-examples-java-util-collections/" target="_blank" rel="noopener noreferrer"><code>synchronized</code></a> keyword. When a thread passes over the <code>synchronized</code> keyword, it effectively locks all the doors.</li>



<li>Of course, if a <a href="https://crunchify.com/how-to-generate-java-thread-dump-programmatically/" target="_blank" rel="noopener noreferrer">thread</a> doesn&#8217;t pass across the&nbsp;<code>synchronized</code> keyword, it hasn&#8217;t locked the door, and some other thread is free barge in at any time.</li>
</ol>
<p>The post <a href="https://crunchify.com/have-you-noticed-race-condition-in-java-multithreading-concurrency-example-how-to-deal-with-it/">Have you noticed Race Condition in Java Multi-threading Concurrency Example? How to deal with it?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/have-you-noticed-race-condition-in-java-multithreading-concurrency-example-how-to-deal-with-it/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>In Java How to convert Byte[] Array To String and String to Byte[]?</title>
		<link>https://crunchify.com/java-how-to-convert-byte-array-to-string/</link>
					<comments>https://crunchify.com/java-how-to-convert-byte-array-to-string/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Fri, 15 Nov 2024 21:45:00 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=3382</guid>

					<description><![CDATA[<p>How to convert Byte[] Array to String in Java? How to convert UTF-8 byte[] to string? Convert Java Byte Array to String to Byte Array. String stores textual data and for storing binary data you would need byte[]. In ideal situation you would avoid using the same in your production ready build. Here is a [&#8230;]</p>
<p>The post <a href="https://crunchify.com/java-how-to-convert-byte-array-to-string/">In Java How to convert Byte[] Array To String and String to Byte[]?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte.png"><img loading="lazy" decoding="async" width="2071" height="1119" src="https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte.png" alt="In Java How to convert Byte[] Array To String and String to Byte[]?" class="wp-image-13360" srcset="https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte.png 2071w, https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte-768x415.png 768w, https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte-1536x830.png 1536w, https://crunchify.com/wp-content/uploads/2020/12/In-Java-How-to-convert-Byte-Array-To-String-and-String-to-Byte-2048x1107.png 2048w" sizes="auto, (max-width: 2071px) 100vw, 2071px" /></a></figure>



<p>How to convert Byte[] Array to <a href="https://crunchify.com/how-to-reverse-a-string-in-java/" target="_blank" rel="noreferrer noopener">String in Java</a>? How to convert <a href="https://crunchify.com/in-java-how-to-join-arrays-3-ways-apache-commons-arrayutils-java-8-streams-and-simple-apis/" target="_blank" rel="noreferrer noopener">UTF-8</a> byte[] to string? Convert Java Byte Array to String to <a href="https://crunchify.com/in-java-best-way-to-convert-file-into-a-bytes-array-of-bytes/" target="_blank" rel="noreferrer noopener">Byte Array</a>.</p>



<p>String stores <code>textual data</code> and for storing <code>binary data</code> you would need byte[]. In ideal situation you would avoid using the same in your <a href="https://crunchify.com/memcached-java-client-tutorial-using-com-whalin-memcached-java-client-and-com-googlecode-xmemcached-libraries/" target="_blank" rel="noreferrer noopener">production ready build</a>. Here is a code,  just incase if you need to do conversion in your application from String to byte[] and vice versa.</p>



<h3 class="wp-block-heading">There are multiple ways you could covert byte[] to String and String to byte[].</h3>



<p>We will manipulate String and byte[] <code>5 different ways</code>.</p>



<ol class="wp-block-list"><li>Convert String to byte[] Array using getBytes()</li><li>Convert String to byte[] Array using UTF_8 encoding</li><li><a href="https://crunchify.com/escape-character-utility-for-url-and-json-data-free-to-use-in-your-project/" target="_blank" rel="noreferrer noopener">Encode and Decode</a> to String using <a href="https://crunchify.com/soap-vs-rest-simple-object-access-protocol-vs-representational-state-transfer/" target="_blank" rel="noreferrer noopener">Base64 encoding</a></li><li>Convert Byte[] to String using new String()</li><li>Convert Byte[] to String using UTF_8 encoding</li></ol>



<p><code>toString()</code> function on String <a href="https://crunchify.com/what-is-json-javascript-object-notation/" target="_blank" rel="noreferrer noopener">object</a> wont return actual string but only <a href="https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/" target="_blank" rel="noreferrer noopener">HashValue</a>. Look for all comments mentioned in below Java program.</p>



<h3 class="wp-block-heading">Java Code:</h3>



<pre class="EnlighterJSRAW">package crunchify.com.tutorials;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author Crunchify.com
 * In Java How to convert Byte&#091;] Array To String and String to Byte&#091;]?
 * Version: 1.2
 */

public class CrunchifyByteArrayToString {
    public static void main(String&#091;] args) throws UnsupportedEncodingException {

        // Method-1: Convert String to byte&#091;] Array using getBytes()
        String crunchifyString = &quot;Crunchify Example on Byte&#091;] to String...&quot;;
        // getBytes() encodes this String into a sequence of bytes using the platform&#039;s
        // default charset, storing the result into a new byte array.
        byte&#091;] crunchifyByte = crunchifyString.getBytes();

        System.out.println(&quot;crunchifyString : &quot; + crunchifyString);
        // toString() Returns a string representation of the contents of the specified array.
        // The string representation consists of a list of the array&#039;s elements, enclosed in square brackets (&quot;&#091;]&quot;). Adjacent elements are separated by the characters &quot;, &quot; (a comma followed by a space).
        // Elements are converted to strings as by String.valueOf(byte). Returns &quot;null&quot; if a is null.
        System.out.println(&quot;crunchifyByte : &quot; + Arrays.toString(crunchifyByte));

        // Method-2: Convert String to byte&#091;] Array using UTF_8 encoding
        String crunchifyString2 = &quot;This is test for converting String to byte...!&quot;;
        byte&#091;] crunchifyByte2 = crunchifyString2.getBytes(StandardCharsets.UTF_8);
        System.out.println(&quot;\ncrunchifyString2 : &quot; + crunchifyString2);
        System.out.println(&quot;crunchifyByte2 : &quot; + Arrays.toString(crunchifyByte2));

        // Method-3: Encode and Decode to String using Base64 encoding
        // encodeToString() Encodes the specified byte array into a String using the Base64 encoding scheme.
        // This method first encodes all input bytes into a base64 encoded byte array and then constructs
        // a new String by using the encoded byte array and the ISO-8859-1 charset.
        String crunchifyEncodedValue = Base64.getEncoder().encodeToString(crunchifyByte2);
        System.out.println(&quot;crunchifyByte2 encoded value : &quot; + crunchifyEncodedValue);

        // decode() Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme.
        // An invocation of this method has exactly the same effect as invoking decode(src.getBytes(StandardCharsets.ISO_8859_1))
        byte&#091;] crunchifyByte3 = Base64.getDecoder().decode(crunchifyEncodedValue);
        System.out.println(&quot;crunchifyByte2 decoded value : &quot; + Arrays.toString(crunchifyByte3));

        // Method-4: Convert Byte&#091;] to String using new String()
        String crunchifyDecodedData = new String(crunchifyByte3);
        System.out.println(&quot;\nDecrypted String : &quot; + crunchifyDecodedData);

        // Method-5: Convert Byte&#091;] to String using UTF_8 encoding
        String decodedDataUsingUTF8;
        // UTF_8 is Eight-bit UCS Transformation Format.
        decodedDataUsingUTF8 = new String(crunchifyByte3, StandardCharsets.UTF_8);
        System.out.println(&quot;Text Decrypted using UTF-8 : &quot; + decodedDataUsingUTF8);
    }
}</pre>



<h3 class="wp-block-heading">Eclipse console Output:</h3>



<p>Just run above program as <a href="https://crunchify.com/how-to-start-embedded-http-jersey-server-during-java-application-startup/" target="_blank" rel="noreferrer noopener">Java Application</a> and you should see similar result.</p>



<pre class="EnlighterJSRAW">crunchifyString : Crunchify Example on Byte&#091;] to String...
crunchifyByte : &#091;67, 114, 117, 110, 99, 104, 105, 102, 121, 32, 69, 120, 97, 109, 112, 108, 101, 32, 111, 110, 32, 66, 121, 116, 101, 91, 93, 32, 116, 111, 32, 83, 116, 114, 105, 110, 103, 46, 46, 46]

crunchifyString2 : This is test for converting String to byte...!
crunchifyByte2 : &#091;84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 115, 116, 32, 102, 111, 114, 32, 99, 111, 110, 118, 101, 114, 116, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 32, 116, 111, 32, 98, 121, 116, 101, 46, 46, 46, 33]
crunchifyByte2 encoded value : VGhpcyBpcyB0ZXN0IGZvciBjb252ZXJ0aW5nIFN0cmluZyB0byBieXRlLi4uIQ==
crunchifyByte2 decoded value : &#091;84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 115, 116, 32, 102, 111, 114, 32, 99, 111, 110, 118, 101, 114, 116, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 32, 116, 111, 32, 98, 121, 116, 101, 46, 46, 46, 33]

Decrypted String : This is test for converting String to byte...!
Text Decrypted using UTF-8 : This is test for converting String to byte...!

Process finished with exit code 0</pre>



<p>Let me know if you see <a href="https://crunchify.com/ansible-how-to-grep-ps-few-and-kill-process-running-on-remote-host/" target="_blank" rel="noreferrer noopener">any issue</a> running above program.</p>
<p>The post <a href="https://crunchify.com/java-how-to-convert-byte-array-to-string/">In Java How to convert Byte[] Array To String and String to Byte[]?</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/java-how-to-convert-byte-array-to-string/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java</title>
		<link>https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/</link>
					<comments>https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Fri, 15 Nov 2024 06:29:06 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=2719</guid>

					<description><![CDATA[<p>How to iterate through Java List? This tutorial demonstrates the use of ArrayList, Iterator and a List. There are 7 ways you can iterate through List. Simple For loop Enhanced For loop Iterator ListIterator While loop Iterable.forEach() util Stream.forEach() util Java Example: You need JDK 13 to run below program as point-5 above uses stream() [&#8230;]</p>
<p>The post <a href="https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/">How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="https://crunchify.com/wp-content/uploads/2012/11/How-to-iterate-through-Java-List-Seven-7-different-ways-to-Iterate-Through-Loop-in-Java.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-12687" src="https://crunchify.com/wp-content/uploads/2012/11/How-to-iterate-through-Java-List-Seven-7-different-ways-to-Iterate-Through-Loop-in-Java.png" alt="How to iterate through Java List? Seven (7) different ways to Iterate Through Loop in Java" width="1854" height="1334" srcset="https://crunchify.com/wp-content/uploads/2012/11/How-to-iterate-through-Java-List-Seven-7-different-ways-to-Iterate-Through-Loop-in-Java.png 1854w, https://crunchify.com/wp-content/uploads/2012/11/How-to-iterate-through-Java-List-Seven-7-different-ways-to-Iterate-Through-Loop-in-Java-768x553.png 768w, https://crunchify.com/wp-content/uploads/2012/11/How-to-iterate-through-Java-List-Seven-7-different-ways-to-Iterate-Through-Loop-in-Java-1536x1105.png 1536w" sizes="auto, (max-width: 1854px) 100vw, 1854px" /></a></p>
<p>How to iterate through <a href="https://crunchify.com/category/java-tutorials/" target="_blank" rel="noopener noreferrer">Java</a> List? This tutorial demonstrates the use of <a href="https://crunchify.com/how-to-convert-hashmap-to-arraylist-in-java/" target="_blank" rel="noopener noreferrer">ArrayList</a>, Iterator and a List.</p>
<h3>There are 7 ways you can iterate through List.</h3>
<ol>
<li>Simple For loop</li>
<li>Enhanced For loop</li>
<li>Iterator</li>
<li>ListIterator</li>
<li>While loop</li>
<li>Iterable.forEach() util</li>
<li>Stream.forEach() util</li>
</ol>
<h3>Java Example:</h3>
<p>You need JDK 13 to run below program as <code>point-5</code> above uses <code>stream()</code> util.</p>
<p>void <code>java.util.stream.Stream.forEach</code>(Consumer&lt;? super String&gt; action) p<span class="s1">erforms an action for each element of this stream.</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-title="CrunchifyIterateThroughList.java">package crunchify.com.tutorials;

import java.util.*;

/**
 * @author Crunchify.com
 * How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java.
 * 1. Simple For loop
 * 2. Enhanced For loop
 * 3. Iterator
 * 4. ListIterator
 * 5. While loop
 * 6. Iterable.forEach() util
 * 7. Stream.forEach() util
 */

public class CrunchifyIterateThroughList {

    public static void main(String[] argv) {

        // create list
        List&lt;String&gt; crunchifyList = new ArrayList&lt;String&gt;();

        // add 4 different values to list
        crunchifyList.add(&quot;Facebook&quot;);
        crunchifyList.add(&quot;Paypal&quot;);
        crunchifyList.add(&quot;Google&quot;);
        crunchifyList.add(&quot;Yahoo&quot;);

        // Other way to define list is - we will not use this list :)
        List&lt;String&gt; crunchifyListNew = Arrays.asList(&quot;Facebook&quot;, &quot;Paypal&quot;, &quot;Google&quot;, &quot;Yahoo&quot;);

        // Simple For loop
        System.out.println(&quot;==============&gt; 1. Simple For loop Example.&quot;);
        for (int i = 0; i &lt; crunchifyList.size(); i++) {
            System.out.println(crunchifyList.get(i));
        }

        // New Enhanced For loop
        System.out.println(&quot;\n==============&gt; 2. New Enhanced For loop Example..&quot;);
        for (String temp : crunchifyList) {
            System.out.println(temp);
        }

        // Iterator - Returns an iterator over the elements in this list in proper sequence.
        System.out.println(&quot;\n==============&gt; 3. Iterator Example...&quot;);
        Iterator&lt;String&gt; crunchifyIterator = crunchifyList.iterator();
        while (crunchifyIterator.hasNext()) {
            System.out.println(crunchifyIterator.next());
        }

        // ListIterator - traverse a list of elements in either forward or backward order
        // An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration,
        // and obtain the iterator&#039;s current position in the list.
        System.out.println(&quot;\n==============&gt; 4. ListIterator Example...&quot;);
        ListIterator&lt;String&gt; crunchifyListIterator = crunchifyList.listIterator();
        while (crunchifyListIterator.hasNext()) {
            System.out.println(crunchifyListIterator.next());
        }

        // while loop
        System.out.println(&quot;\n==============&gt; 5. While Loop Example....&quot;);
        int i = 0;
        while (i &lt; crunchifyList.size()) {
            System.out.println(crunchifyList.get(i));
            i++;
        }

        // Iterable.forEach() util: Returns a sequential Stream with this collection as its source
        System.out.println(&quot;\n==============&gt; 6. Iterable.forEach() Example....&quot;);
        crunchifyList.forEach((temp) -&gt; {
            System.out.println(temp);
        });

        // collection Stream.forEach() util: Returns a sequential Stream with this collection as its source
        System.out.println(&quot;\n==============&gt; 7. Stream.forEach() Example....&quot;);
        crunchifyList.stream().forEach((crunchifyTemp) -&gt; System.out.println(crunchifyTemp));
    }
}</pre>
<h3>Output:</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="">==============&gt; 1. Simple For loop Example.
Facebook
Paypal
Google
Yahoo

==============&gt; 2. New Enhanced For loop Example..
Facebook
Paypal
Google
Yahoo

==============&gt; 3. Iterator Example...
Facebook
Paypal
Google
Yahoo

==============&gt; 4. ListIterator Example...
Facebook
Paypal
Google
Yahoo

==============&gt; 5. While Loop Example....
Facebook
Paypal
Google
Yahoo

==============&gt; 6. Iterable.forEach() Example....
Facebook
Paypal
Google
Yahoo

==============&gt; 7. Stream.forEach() Example....
Facebook
Paypal
Google
Yahoo

Process finished with exit code 0
</pre>
<p>The post <a href="https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/">How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/feed/</wfw:commentRss>
			<slash:comments>37</slash:comments>
		
		
			</item>
		<item>
		<title>Java: Simple QR Code Generator Example – Create QR codes for free</title>
		<link>https://crunchify.com/java-simple-qr-code-generator-example/</link>
					<comments>https://crunchify.com/java-simple-qr-code-generator-example/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Fri, 15 Nov 2024 00:18:00 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<category><![CDATA[Google Tech]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=3494</guid>

					<description><![CDATA[<p>Scan this: You will be redirected to https://crunchify.com QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed for the automotive industry in Japan. Bar codes are optical machine-readable labels attached to items that record information related to the item. Initially patented, its patent [&#8230;]</p>
<p>The post <a href="https://crunchify.com/java-simple-qr-code-generator-example/">Java: Simple QR Code Generator Example &#8211; Create QR codes for free</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://crunchify.com/wp-content/uploads/2020/12/Crunchify.com-QRCode-gray-color.png"><img loading="lazy" decoding="async" width="512" height="512" src="https://crunchify.com/wp-content/uploads/2020/12/Crunchify.com-QRCode-gray-color.png" alt="Crunchify.com-QRCode - gray color" class="wp-image-13392" srcset="https://crunchify.com/wp-content/uploads/2020/12/Crunchify.com-QRCode-gray-color.png 512w, https://crunchify.com/wp-content/uploads/2020/12/Crunchify.com-QRCode-gray-color-120x120.png 120w" sizes="auto, (max-width: 512px) 100vw, 512px" /></a></figure></div>



<p>Scan this: You will be redirected to <code>https://crunchify.com</code></p>



<p><code>QR code</code> (abbreviated from <code>Quick Response Code</code>) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed for the automotive industry in Japan. Bar codes are optical machine-readable labels attached to items that record information related to the item. Initially patented, its patent holder has chosen not to exercise those rights. Recently, the QR Code system has become popular outside the automotive industry due to its fast readability and greater <a href="https://crunchify.com/how-to-change-default-media-upload-location-in-wordpress/" target="_blank" rel="noopener noreferrer">storage</a> capacity compared to standard UPC barcodes.</p>



<p>The code consists of black modules (square dots) arranged in a square grid on a white background. <code>ZXING</code>&nbsp;is a&nbsp;Multi-format 1D/2D barcode <a href="https://crunchify.com/java-jsongenerator-json-processing-api-and-how-to-enable-pretty-print-json-output-gson-jackson/" target="_blank" rel="noopener noreferrer">image processing</a> library with clients for <a href="https://crunchify.com/how-to-create-simple-calculator-android-app-using-android-studio/" target="_blank" rel="noreferrer noopener">Android</a>, Java. It is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages.</p>



<h3 class="wp-block-heading">Checkout live example:</h3>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Crunchify QR Code Generator Example" width="500" height="281" src="https://www.youtube.com/embed/Z_KGe8o7kBE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Our focus is on using the built-in camera on <a href="https://crunchify.com/wordpress-and-amp-accelerated-mobile-pages-all-in-one-customization-for-analytics-adsense-social-media-guide-for-beginner/" target="_blank" rel="noreferrer noopener">mobile</a> phones to scan and decode barcodes on the device, without communicating with a server. However the project can be used to encode and decode barcodes on desktops and <a href="https://crunchify.com/how-to-create-1st-spring-boot-helloworld-application-in-intellij-idea-with-few-simple-steps/" target="_blank" rel="noreferrer noopener">servers</a> as well. </p>



<p>Here is a simple <a href="https://crunchify.com/memcached-java-client-tutorial-using-com-whalin-memcached-java-client-and-com-googlecode-xmemcached-libraries/" target="_blank" rel="noreferrer noopener">Java Code</a> which generates QR code for you.</p>



<pre class="EnlighterJSRAW">package crunchify.com.tutorials;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;

/**
 * @author Crunchify.com
 * Simple QR Code Generator Example - Create QR codes for free.
 */

public class CrunchifyQRCodeGenerator {

    public static void main(String&#091;] args) {
        String myCodeText = &quot;https://crunchify.com&quot;;
        String filePath = &quot;/Users/app/Document/Crunchify.com-QRCode.png&quot;;
        int size = 512;
        String crunchifyFileType = &quot;png&quot;;
        File crunchifyFile = new File(filePath);
        try {

            Map&lt;EncodeHintType, Object&gt; crunchifyHintType = new EnumMap&lt;EncodeHintType, Object&gt;(EncodeHintType.class);
            crunchifyHintType.put(EncodeHintType.CHARACTER_SET, &quot;UTF-8&quot;);

            // Now with version 3.4.1 you could change margin (white border size)
            crunchifyHintType.put(EncodeHintType.MARGIN, 1); /* default = 4 */
            Object put = crunchifyHintType.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            QRCodeWriter mYQRCodeWriter = new QRCodeWriter(); // throws com.google.zxing.WriterException
            BitMatrix crunchifyBitMatrix = mYQRCodeWriter.encode(myCodeText, BarcodeFormat.QR_CODE, size,
                    size, crunchifyHintType);
            int CrunchifyWidth = crunchifyBitMatrix.getWidth();

            // The BufferedImage subclass describes an Image with an accessible buffer of crunchifyImage data.
            BufferedImage crunchifyImage = new BufferedImage(CrunchifyWidth, CrunchifyWidth,
                    BufferedImage.TYPE_INT_RGB);

            // Creates a Graphics2D, which can be used to draw into this BufferedImage.
            crunchifyImage.createGraphics();

            // This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout.
            // This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java(tm) platform.
            Graphics2D crunchifyGraphics = (Graphics2D) crunchifyImage.getGraphics();

            // setColor() sets this graphics context&#039;s current color to the specified color.
            // All subsequent graphics operations using this graphics context use this specified color.
            crunchifyGraphics.setColor(Color.white);

            // fillRect() fills the specified rectangle. The left and right edges of the rectangle are at x and x + width - 1.
            crunchifyGraphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);

            // TODO: Please change this color as per your need
            crunchifyGraphics.setColor(Color.BLUE);

            for (int i = 0; i &lt; CrunchifyWidth; i++) {
                for (int j = 0; j &lt; CrunchifyWidth; j++) {
                    if (crunchifyBitMatrix.get(i, j)) {
                        crunchifyGraphics.fillRect(i, j, 1, 1);
                    }
                }
            }

            // A class containing static convenience methods for locating
            // ImageReaders and ImageWriters, and performing simple encoding and decoding.
            ImageIO.write(crunchifyImage, crunchifyFileType, crunchifyFile);

            System.out.println(&quot;\nCongratulation.. You have successfully created QR Code.. \n&quot; +
                    &quot;Check your code here: &quot; + filePath);
        } catch (WriterException e) {
            System.out.println(&quot;\nSorry.. Something went wrong...\n&quot;);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}</pre>



<h3 class="wp-block-heading">Output: (Scan it by yourself)</h3>



<figure class="wp-block-image is-resized"><a href="https://crunchify.com/wp-content/uploads/2013/01/Crunchify-QR-Code.jpg"><img loading="lazy" decoding="async" src="https://crunchify.com/wp-content/uploads/2013/01/Crunchify-QR-Code.jpg" alt="Crunchify QR Code" class="wp-image-5104" width="640" height="1136"/></a></figure>



<h3 class="wp-block-heading">Which library do I have to download?</h3>



<p>If you have <a href="https://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/" target="_blank" rel="noopener noreferrer">Maven project</a> then include this dependency to your pom.xml file.</p>



<pre class="EnlighterJSRAW">&lt;dependency&gt;
	&lt;groupId&gt;com.google.zxing&lt;/groupId&gt;
	&lt;artifactId&gt;core&lt;/artifactId&gt;
	&lt;version&gt;3.4.1&lt;/version&gt;
&lt;/dependency&gt;</pre>



<figure class="wp-block-image size-large"><a href="https://crunchify.com/wp-content/uploads/2020/12/Crunchify-QR-Code-Generator-Tutorial.png"><img loading="lazy" decoding="async" width="2038" height="1215" src="https://crunchify.com/wp-content/uploads/2020/12/Crunchify-QR-Code-Generator-Tutorial.png" alt="Crunchify QR Code Generator Tutorial" class="wp-image-13395" srcset="https://crunchify.com/wp-content/uploads/2020/12/Crunchify-QR-Code-Generator-Tutorial.png 2038w, https://crunchify.com/wp-content/uploads/2020/12/Crunchify-QR-Code-Generator-Tutorial-768x458.png 768w, https://crunchify.com/wp-content/uploads/2020/12/Crunchify-QR-Code-Generator-Tutorial-1536x916.png 1536w" sizes="auto, (max-width: 2038px) 100vw, 2038px" /></a></figure>



<h4 class="wp-block-heading">OR Download&nbsp;.jar file manually</h4>



<h4 class="wp-block-heading">Step-1:</h4>



<p>Download&nbsp;<a href="http://mvnrepository.com/artifact/com.google.zxing/core/3.2.1" target="_blank" rel="noopener noreferrer">link</a>.</p>



<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2013/01/Download-ZXing-and-Manually-add-it-to-your-project-Simple-QR-code-generator-Example.png" rel="attachment wp-att-8436"><img loading="lazy" decoding="async" width="1048" height="482" src="https://crunchify.com/wp-content/uploads/2013/01/Download-ZXing-and-Manually-add-it-to-your-project-Simple-QR-code-generator-Example.png" alt="Download ZXing and Manually add it to your project - Simple QR code generator Example" class="wp-image-8436" srcset="https://crunchify.com/wp-content/uploads/2013/01/Download-ZXing-and-Manually-add-it-to-your-project-Simple-QR-code-generator-Example.png 1048w, https://crunchify.com/wp-content/uploads/2013/01/Download-ZXing-and-Manually-add-it-to-your-project-Simple-QR-code-generator-Example-768x353.png 768w" sizes="auto, (max-width: 1048px) 100vw, 1048px" /></a></figure>



<h4 class="wp-block-heading">Step-2</h4>



<p>Once you download it you have to include it into your project&#8217;s classpath. How to add .jar file to Project Build Path in Eclipse.</p>



<figure class="wp-block-image"><a href="https://crunchify.com/wp-content/uploads/2013/01/How-to-add-.jar-file-to-Project-Build-Path-in-Eclipse-Crunchify-Tips.png" rel="attachment wp-att-8439"><img loading="lazy" decoding="async" width="1432" height="642" src="https://crunchify.com/wp-content/uploads/2013/01/How-to-add-.jar-file-to-Project-Build-Path-in-Eclipse-Crunchify-Tips.png" alt="How to add .jar file to Project Build Path in Eclipse - Crunchify Tips" class="wp-image-8439" srcset="https://crunchify.com/wp-content/uploads/2013/01/How-to-add-.jar-file-to-Project-Build-Path-in-Eclipse-Crunchify-Tips.png 1432w, https://crunchify.com/wp-content/uploads/2013/01/How-to-add-.jar-file-to-Project-Build-Path-in-Eclipse-Crunchify-Tips-768x344.png 768w" sizes="auto, (max-width: 1432px) 100vw, 1432px" /></a></figure>



<p>Let me know if you face any issue generating QR code.</p>
<p>The post <a href="https://crunchify.com/java-simple-qr-code-generator-example/">Java: Simple QR Code Generator Example &#8211; Create QR codes for free</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/java-simple-qr-code-generator-example/feed/</wfw:commentRss>
			<slash:comments>70</slash:comments>
		
		
			</item>
		<item>
		<title>Java: How to Get Random Key-Value Element From HashMap</title>
		<link>https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/</link>
					<comments>https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/#comments</comments>
		
		<dc:creator><![CDATA[App]]></dc:creator>
		<pubDate>Thu, 14 Nov 2024 08:23:10 +0000</pubDate>
				<category><![CDATA[Java J2EE Tutorials]]></category>
		<category><![CDATA[Hashmap]]></category>
		<guid isPermaLink="false">https://crunchify.com/?p=5609</guid>

					<description><![CDATA[<p>Is there a way to get the value of a HashMap randomly in Java? How to Shuffle a List in Java?</p>
<p>The post <a href="https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/">Java: How to Get Random Key-Value Element From HashMap</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="https://crunchify.com/wp-content/uploads/2013/08/How-to-Get-Random-Key-Value-Element-From-HashMap.png"><img loading="lazy" decoding="async" class="alignnone wp-image-6990 size-full" src="https://crunchify.com/wp-content/uploads/2013/08/How-to-Get-Random-Key-Value-Element-From-HashMap.png" alt="How to Get Random Key-Value Element From HashMap" width="1560" height="554" srcset="https://crunchify.com/wp-content/uploads/2013/08/How-to-Get-Random-Key-Value-Element-From-HashMap.png 1560w, https://crunchify.com/wp-content/uploads/2013/08/How-to-Get-Random-Key-Value-Element-From-HashMap-768x273.png 768w, https://crunchify.com/wp-content/uploads/2013/08/How-to-Get-Random-Key-Value-Element-From-HashMap-1536x545.png 1536w" sizes="auto, (max-width: 1560px) 100vw, 1560px" /></a></p>
<p>Is there a way to get the value of a HashMap <a href="https://crunchify.com/how-to-generate-random-number-in-java-with-some-variations/" target="_blank" rel="noopener noreferrer">randomly</a> in <a href="https://crunchify.com/how-to-create-your-own-non-blocking-queue-in-java-same-as-evictingqueue/" target="_blank" rel="noopener noreferrer">Java</a>? Of Course, below is a simple Java Code which represents the same.</p>
<p>Also, at the end of program there is a bonus code to Shuffle complete <a href="https://crunchify.com/how-to-use-expiringmap-maven-java-utility-to-remove-expired-objects-from-map-automatically-complete-java-tutorial/" target="_blank" rel="noopener noreferrer">HashMap</a>. Reshuffling a large <a href="https://crunchify.com/what-is-java-collections-framework-benefits-of-collections-framework/" target="_blank" rel="noopener noreferrer">collection</a> is always going to be expensive. You are going to need at least one reference per entry. e.g. for 1 million entries you will need approx 4 MB.</p>
<p>Note; the shuffle operation is <code>O(N)</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-highlight="29,37" data-enlighter-title="CrunchifyGetRandomKeyValueFromHashMap.java">package com.crunchify.tutorials;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyGetRandomKeyValueFromHashMap {
	public static void main(String[] args) {
		//
		// Create a hashtable and put some key-value pair.
		//
		HashMap&lt;String, String&gt; companies = new HashMap&lt;String, String&gt;();
		companies.put(&quot;eBay&quot;, &quot;South San Jose&quot;);
		companies.put(&quot;Paypal&quot;, &quot;North San Jose&quot;);
		companies.put(&quot;Google&quot;, &quot;Mountain View&quot;);
		companies.put(&quot;Yahoo&quot;, &quot;Santa Clara&quot;);
		companies.put(&quot;Twitter&quot;, &quot;San Francisco&quot;);

		// Get a random entry from the HashMap.
		Object[] crunchifyKeys = companies.keySet().toArray();
		Object key = crunchifyKeys[new Random().nextInt(crunchifyKeys.length)];
		System.out.println(&quot;************ Random Value ************ \n&quot; + key + &quot; :: &quot; + companies.get(key));

		List&lt;Map.Entry&lt;String, String&gt;&gt; list = new ArrayList&lt;Map.Entry&lt;String, String&gt;&gt;(companies.entrySet());

		// Bonus Crunchify Tips: How to Shuffle a List??
		// Each time you get a different order...
		System.out.println(&quot;\n************ Now Let&#039;s start shuffling list ************&quot;);
		Collections.shuffle(list);
		for (Map.Entry&lt;String, String&gt; entry : list) {
			System.out.println(entry.getKey() + &quot; :: &quot; + entry.getValue());
		}
	}
}</pre>
<p>Other must read:</p>
<ul>
<li><a href="https://crunchify.com/how-to-convert-hashmap-to-arraylist-in-java/" target="_blank" rel="noopener noreferrer">How to convert HashMap to ArrayList in Java?</a></li>
<li><a title="Java: How to Find Maximum Occurrence of Words from Text File?" href="https://crunchify.com/java-how-to-find-maximum-occurrence-of-words-from-text-file/" rel="bookmark">Java: How to Find Maximum Occurrence of Words from Text File?</a></li>
</ul>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="default" data-enlighter-title="Output">************ Random Value ************ 
Twitter :: San Francisco

************ Now Let&#039;s start shuffling list ************
Paypal :: North San Jose
eBay :: South San Jose
Google :: Mountain View
Twitter :: San Francisco
Yahoo :: Santa Clara</pre>
<p>The post <a href="https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/">Java: How to Get Random Key-Value Element From HashMap</a> appeared first on <a href="https://crunchify.com">Crunchify</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://crunchify.com/java-how-to-get-random-key-value-element-from-hashmap/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>