Java Mistake 1 - Using float and double for monetary or financial calculation

Java is considered very safe programming language compared to C and C++ as it doesn't have free() and malloc() to directly do memory allocation and deallocation, You don't need to worry of array overrun in Java as they are bounded and there is pointer arithmetic in Java. Still there are some sharp edges in Java programming language which you need to be aware of while writing enterprise application. Many of us make subtle mistake in Java which looks correct in first place but turn out to be buggy when looked carefully. In this series of java articles I will be sharing some of common Java mistake programmers make while programming application in Java. As I have said earlier every day we learn new things but we forget something equally important. This again highlight importance of code review and following best practices in Java. In this part we will discuss why double and float should not be used in monetary or financial calculation where exact result of calculation is expected.

How to convert Char to String in Java with Example

There are multiple ways to convert char to String in Java. In fact String is made of Character array in Java, which can be retrieved by calling String.toCharArray() method. Char is 16 bit or 2 byte unsigned data type in java mainly used to store characters. You can convert a single character into String for any purpose in Java by more than one ways. I thought about this article while writing how to convert Integer to String in Java but t it took little longer to get this post completed. In this Java tutorial we will see different ways to convert character into String in java with code Example.

How to check or detect duplicate elements in Array in Java

Detecting duplicate elements in Java array is another programming interview question I like. There could be a lot of ways you can check if your array contains duplicate elements or not and sometimes you discover a unique way of checking duplicates by asking this question on Java interview. Beauty of this question is that it has endless number of follow-up question so if interviewee gets through this question you can ask to him about time complexity and space or to improve his algorithm to make it fast .you can even ask to find those duplicate elements in Array which even can go from one duplicate to many repeating elements in Array. As I said you can really test programming skill around an array of a Java programmer.

How to solve java.util.NoSuchElementException in Java

How to fix java.util.NoSuchElementException in Java

java.util.NoSuchElementException is a RuntimeException which can be thrown by different classes in Java like Iterator, Enumerator, Scanner or StringTokenizer. All of those classes has method to fetch next element or next tokens if underlying data-structure doesn't have any element Java throws "java.util.NoSuchElementException". Most common example of this iterating over hashmap without checking if there is any element or not and that's why it's advised to use hashNext() before calling next() on Iterator. In this Java tutorial we will what causes NoSuchElementException in Java and how to avoid it completely.

How to set JAVA_HOME environment in Linux, Unix and Windows

JAVA_HOME is a system environment variable which represent JDK installation directory. When you install JDK in your machine (windows, Linux or unix) it creates a home directory and puts all its binary (bin), library(lib) and other
tools. In order to compile java program "javac" tool should be in your PATH and in order to get that in PATH
we use JAVA_HOME environment variable. Many tools like ANT and web servers like tomcat use JAVA_HOME to find java binaries. In this article we will see how to set JAVA_HOME environment variable in different operating system including Windows (windows 7, vista, xp) and Linux (Unix).

What is Race Condition in multithreading – 2 Examples in Java

Race condition in Java is a type of concurrency bug or issue which is introduced in your program because  parallel execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition and how to avoid that. Anyway Race conditions are just one of hazards or risk presented by  use of multi-threading in Java just like deadlock in Java. Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical example of Race condition is incrementing a counter since increment is not an atomic operation and can be further divided into three steps like read, update and write. if two threads tries to increment count at same time and if they read same value because of interleaving of read operation of one thread to update operation of another thread, one count will be lost when one thread overwrite increment done by other thread. atomic operations are not subject to race conditions because those operation cannot be interleaved. This is also a popular multi-threading interview questions during core java interviews. In this article we will see how to find race condition in Java and  two sample code patterns which often causes race conditions in Java.

JSTL Set tag examples or <c:set> in JSP – Java J2EE Tutorial

JSTL set tag or <c:set> also called as JSTL Core tag library is a good replacement of <jsp:setProperty> jsp action which lacks lot of functionality and only allow you to set bean property. you can not set Map's key value or create a scoped variable by using <jsp:setProperty>. jstl <set> tag allows you to do all the stuff related to setting or creating variables or attributes. by using JSTL <c:set> tag you can :

Difference between throw and throws in Exception handling - Java Example

Difference between throw and throws keyword on Exception handling in Java is a popular core java interview question. Exception handling being an important part of Java programming language, complete knowledge of all keywords related to exception handling e.g. try, catch, finally, throw and throws is important. Main difference between throw and throws is in there usage and functionality. where throws is used in method signature to declare Exception possibly thrown by any method, throw is actually used to throw Exception in Java code, here is an example of both throw and throws keyword which makes it easy to understand difference between them.

Difference between LinkedList vs ArrayList in Java

LinkedList and ArrayList both implement List Interface but how they work internally is where the differences lies. Main difference between ArrayList and LinkedList is that ArrayList is implemented using re sizable array while LinkedList is implemented using doubly LinkedList. ArrayList is more popular among Java programmer than LinkedList as there are few scenarios on which LinkedList is a suitable collection than ArrayList. In this article we will see some differences between LinkedList and ArrayList and try to find out when and where to use LinkedList over ArrayList.

How to encode decode String in Java base64 Encoding

Encoding and Decoding of String in Java using base64 are extremely easy if you are using Apache commons code open source library. it provides convenient static utility method Base64.encodeBase64(byte[]) and Base64.decodeBase64(byte []) for converting binary data into base64 encoded binary Stream and then decoding back from encoded data in base64 encoding mechanism. Many times we need to encode sensitive data be it binary String  format transferring over a socket or transferring or storing data in XML files. Though there are other open source libraries available which provide support to encode any String into base64 e.g. MimeUtil from javax.mail package but Apache commons codec package is really handy and doesn't add a lot of extra stuff. its API is also very neat and clean. In this article, we will see how to encode and decode String into base64 encoding.

Producer Consumer Design Pattern with Blocking Queue Example in Java

Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between
Producer and Consumer by separating Identification of work with Execution of Work. In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code producer and consumer separately. It also addresses the issue of different timing require to produce item or consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed. In this article we will see What is producer consumer problem which is very popular multi-threading interview question, How to solve producer consumer problem using Blocking Queue and Benefits of using Producer Consumer design pattern.

Why non-static variable cannot be referenced from a static context?

"non-static variable cannot be referenced from a static context" is biggest nemesis of some one who has just
started programming and that too in Java. Since main method in java is most popular method among all beginners and
they try to put program code there they face "non-static variable cannot be referenced from a static context" compiler error when they  try to access a non static member variable inside main in Java which is static. if you want to know
why main is declared static in Java see the link.

fail-safe vs fail-fast Iterator in Java

Difference between fail-safe and fail-fast Iterator is becoming favorite core java interview questions day by day, reason
it touches concurrency a bit and interviewee can go deep on it to ask how fail-safe or fail-fast behavior is implemented.
In this article article we will see what is fail-safe and fail fast iterators in java and differences between fail-fast and fail-safe iterators . Concept of fail-safe iterator are relatively new in Java and first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap and CopyOnWriteArrayList.

How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory

java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory  or "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory" exception comes when you don't apache commons-logging-1.1.1.jar in your Classpath. I have faced this exception many times while using open source framework like Struts, Spring and Displaytag which uses commons-logging framework for logging. commons-logging is not an actual java logging framework but provides a wrapper so that you can use log4j, java logging or any other Java logging framework. commons-logging is also smart enough to detect which logging framework are you using e.g if you are using log4j it can detect it by looking log4j.jar in your classpath. but if you don't have commons-logging.jar in your classpath you may get java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at runtime even if your application gets deployed successfully.

What is blocking methods in Java and how do deal with it?

Blocking methods in Java are those methods which block the executing thread until their operation finished. A famous
example of blocking method is InputStream read() method which blocks until all data from InputStream has been read
completely. A correct understanding of blocking methods are required if you are serious towards Java programming especially in early days because if not used carefully blocking method can freeze GUIs, hung your program and become non-responsive for a longer duration of time. In this post, we will see What is Blocking methods in Java, Examples of Blocking methods and Some best practices around blocking methods and how to use blocking methods in Java.

Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java

Why to wait, notify and notifyAll is declared in Object Class instead of Thread is famous core java interview question which is asked during all levels of Java interview ranging from 2 years, 4years to quite senior level position on java development. Beauty of this question is that it reflect what does interviewee knows about wait notify mechanism, how does it sees whole wait and notify feature and whether his understanding is not shallow on this topic. Like Why Multiple inheritance is not supported in Java or why String is final in java there could be multiple answers of why wait and notify is defined in Object class and every one could justify there reason.  

3 Example to Compare two Dates in Java

comparing dates in Java is common need for Java programmer, now and then we need to compare two dates to check whether two dates are equals, less than or greater than each other, some time we also needs to check if one dates comes in between two dates. Java provides multiple ways to compare two Dates in Java which is capable of performing Date comparison and letting you know whether two dates are same, one date come before or after another date in Java. In last couple of article we have seen how to convert String to Date in Java and Converting  Date to String in Java and here we will see three different example of comparing two dates in Java.

Difference between instance class and local variables in Java

There are a lot of differences between instance variable, class variable and local variable in Java and knowing them will help you to write correct and bug-free Java programs. Java is a full-featured programming language and provides different kind of variables like static variable also called Class variable since it belongs to whole Class, non-static also called instance variable and local variables which vary in scope and value. Thank god Java doesn't have any register variable or auto scope like C otherwise it would have so much detail to remember. static variables are a common source of error in may multi-threaded java program and does require a bit of carefulness while using it. On the other hand instance, variable and the local variable has less sharing visibility than static variable.