How to Check if Given Number is Prime in Java - With Example

One of the most common programming exercise for beginners is, write a program to check if given number is prime or not? There are many methods to check if a number is prime or not, but most common of them is trial division, which is what we will see in this tutorial. In my opinion, these kind of program is their first steps towards algorithmic understanding. You first come with a solution, which is driven by the fact that prime numbers are natural numbers, which are not divisible by any positive number other than 1 and themselves. You write a for loop to check every number, starting from 1 to given number, to see if given number is divisible by any positive number or not. This leads you to the solution. Then you find some more fact that there is no need to check till N-1, where N is the number we are checking for primeness, and checking till square root of N is enough. This reduces a lot of time, especially while checking a large number is prime or not.

How HashSet Internally Works in Java

Not many programmer know that HashSet is internally implemented using HashMap in Java, so if you know How HashMap works internally in Java, more likely you can figure out how HashSet works in Java. But, now a curious Java developer can question that, how come HashSet uses HashMap, because you need a key value pair to use with Map, while in HashSet we only store one object. Good question, isn't it? If you remember some functionality of earlier class, then you know that HashMap allows duplicate values and this property is exploited while implementing HashSet in Java. Since HashSet implements Set interface it needs to guarantee uniqueness and this is achieved by storing elements as keys with same value always. Things gets clear by checking from JDK source code. All you need to look at is, how elements are stored in HashSet and how they are retrieved from HashSet. Since HashSet doesn't provide any direct method for retrieving object e.g. get(Key key) from HashMap or get(int index) from List, only way to get object from HashSet is via Iterator. See here for code example of iterating over HashSet in Java. When you create an object of HashSet in Java, it internally create instance of backup Map with default initial capacity 16 and default load factor 0.75 as shown below :

Java Regular Expression to Check If String contains at least One Digit

This week's task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing "abcd" to pattern should false, while passing "abcd1" to return true, because it contains at least one digit. Similarly passing "1234" should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with an inbuilt support of regular expression e.g.split method, replaceAll() and  matches method, which can be used for this purpose, but they have a drawback.  They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don't need to spend time on creating and compiling pattern, which is expensive compared to testing a String against the pattern.

How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory

Java allows an application to access non-heap memory by using direct byte buffer. Many high-performance applications uses direct byte buffer, along with memory mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of Garbage collection scope.  Which means garbage collector can not reclaim this memory. It is often used to store large data e.g. order or static data cache. Since generally your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running following code

Why String Class is made Immutable or Final in Java - 5 Reasons

There is hardly any Java Interview, where no questions are asked from String, and Why String is Immutable in Java is I think most popular one. This question is also asked as Why String class is made final in Java or simply, Why String is final. In order to answer these questions, Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals. The String class is a God class in Java, It has got special features which is not available to other classes e.g. String literals are stored in pools, You can concatenate strings using + operator. Given its importance in Java programming, Java designer has made it final, which means you can not extend java.lang.String class, this also helps to make String object Immutable.

10 points about Thread in Java

Thread in Java is one of those topics which always confuse beginners but given its important and strength it provides to Java language, it's very important for every Java developer to learn and understand the fundamental concept of multi-threading and basic points about Thread in Java. I had started thread programming in Java by animating a couple of  words in Applets, that was an amazing experience to code animation, but after spending almost 10 years on developing core Java application and I am still discovering things on threading and concurrency. My first program which involves Thread had three words dropping from each corner of the screen and I was excited to see that animation driven by Java thread.

java.lang.UnsatisfiedLinkError: Library not found tibrvnative or android

When I was working in JNI and using native code, actually an in-house library,  I realized that java.lang.UnsatisfiedLinkError: Library not found comes mainly due to two reasons

1) First reason, which happens in 90% scenarios is that the library which you are using directly or indirectly (some external JAR is using native library or native dll e.g. if your Java application is using TIBCO libraries for messaging or fault tolerance then tibrv.jar uses tibrvnative.dll library and throws java.lang.UnsatisfiedLinkError: Library not found tibrvnative if that library (the dll) is not in the path. In order to fix this problem, you need to update your PATH environment variable to include native libraries binary. see last section for more details.

6 Difference between LinkedHashSet vs TreeSet vs HashSet in Java

LinkedHashSet, TreeSet, and HashSet are three of most popular implementation of Set interface in Java Collection Framework. Since they implement Set interface, they follow its contracts for not allowing duplicates. All these implementation except, TreeSet uses equals() method to check for duplicates, on the other hand TreeSet use compareTo() or compare() method for comparing objects and can break Set interface contract of unique element, if equals method is not consistent with compareTo() or compare() method. In this Java Collection tutorial, we will see the difference between LinkedHashSet vs TreeSet vs HashSet on different points e.g. speed, performance, ordering, synchronization etc. Based upon these differences we can also decide when to use LinkedHashSet vs TreeSet vs HashSet in Java.