Tuesday, February 28, 2017

Difference between Executor, ExecutorService and Executers class in Java

All three classes Executor, ExecutorService, and Executers are part of Java's Executor framework which provides thread pool facilities to Java applications. Since creation and management of Threads are expensive and operating system also imposes restrictions on how many Threads an application can spawn, it's a good idea is to use a pool of thread to execute tasks in parallel, instead of creating a new thread every time a request come in. This not only improves the response time of application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread". A thread pool which is created when an application is a startup solves both of these problems. It has ready threads to serve clients when needed and it also has a bound on how many threads to create under load.

Why Catching Throwable or Error is bad?

We often hear advice that catching Throwable or Error is bad practice and Java developer should avoid catching these, but have you thought Why? If language allows you to catch anything which is instance of java.lang.Throwable, then what is the problem of catching them or their subclass java.lang.Error? If they are bad, shouldn't Java itself has prohibited them from catching?  Well this all looks good on theory, but not in real world programming. As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error. There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.

Monday, February 27, 2017

How to use ConcurrentHashMap in Java - Example Tutorial and Working

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package. Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have a better choice; because not only it can be safely used in the concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. CHM allows concurred read operations and the same time maintains integrity by synchronizing write operations. We have seen basics of ConcurrentHashMap on Top 5 Java Concurrent Collections from JDK 5 and 6 and in this Java tutorial, we will learn:

Ø       How ConcurrentHashMap works in Java or how it is implemented in Java.
Ø       When to use ConcurrentHashMap in Java
Ø       ConcurrentHashMap examples in Java
Ø       And some important properties of CHM.

How to Count Number of Words in String - Java Coding Exercise

String is very popular among Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based from Java fundamentals like why String is Immutable in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled candidates. In this article, we will see a similar questions, how to count number of words in Java String. Before jumping to solution, just read below to make sure what a word means here. It's sequence of one or more non-space characters. We will see two examples to find number of words in Java String, first one is based upon pure logic, where it goes through all characters from String and then count each word. Second is more interesting than first one, here we have used regular expression to find all words. We split String by white space, passing \\s+ means greedy search i.e. it includes one or more white spaces.  BTW, this is one of the question I forgot to share when I wrote about Top 20 String coding questions, will include it on that list for sure.

Sunday, February 26, 2017

How to connect to Microsoft SQL Server database using Eclipse

Though I prefer SQL Server Management Studio to access and work with Microsoft SQL Server database, Sometimes, it's better to connect MSSQL database directly from Eclipse. This will save a lot of time which is wasted on switching between two applications, Eclipse and SSMS. It will also keep your PC fast enough because less application means less overhead. Eclipse IDE allows you to connect to almost all the database you have heard e.g. Oracle, MySQL, PostgreSQL, DB2 etc. All the steps are pretty much same, so once you know how to connect SQL Server database from Eclipse, you can connect Oracle or MySQL by yourself. Since Eclipse connects to the database using JDBC, you need to deploy JDBC drivers in your classpath. This is done part of New Database Connection Profile, one of the steps, which we will see later. In this article, I'll show you step by step guide to connect to Microsoft SQL Server database using Eclipse.

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.

10 Example of Lambda Expressions and Streams in Java 8

Java 8 release is just a couple of weeks away, scheduled at 18th March 2014, and there is lot of buzz and excitement about this path breaking release in Java community. One of feature, which is synonymous to this release is lambda expressions, which will provide ability to pass behaviours to methods. Prior to Java 8, if you want to pass behaviour to a method, then your only option was Anonymous class, which will take 6 lines of code and most important line, which defines the behaviour is lost in between. Lambda expression replaces anonymous classes and removes all boiler plate, enabling you to write code in functional style, which is some time more readable and expression.

How to get Key From Value in Hashtable, HashMap or Map in Java

It's not easy to get key from value in Hashtable or HashMap, as compared to getting value from key because HashMap or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. in fact, Map allows same value to be mapped to multiple keys inside HashMap, Hashtable or any other Map implementation. What you have in your kitty is Hashtable.containsValue(String value) or Hashtable.containsKey(String key) to check whether key or value exists in Hashtable or not, but sometimes we want to retrieve a value from Map corresponding to any key and there is no API method to do in Map. We can still do this, but it highly depends data in your Map because Hashtable and HashMap both allows duplicate values mapped to the different key. In this Java tutorial, we will see an example of how to get key from value in Hashtable in Java.

Saturday, February 25, 2017

How to Setup Java Remote Debugging in Eclipse - Step by Step Guide

How to remote debug Java program in Eclipse
Remote debugging is not a new concept and many of you are aware of this just for who don’t know what is remote debugging? It’s a way of debugging any process could be Java or C++ running on some other location on your development machine.  Since debugging Java application is an essential part of Java development and ability to debug your application not only saves time but also increase productivity. Local debugging is the best way to debug Java program in my opinion and should always be preferred over remote debugging as discussed in my post How to debug Java program in Eclipse, but if local debugging is not possible and there is no way to debug your process then remote debugging Java application is the solution.  

All Major IDE like NetBeans, Eclipse, IntelliJ allows you to remote debug Java program but I mostly use Eclipse for remote debugging Java application because it's free and standard IDE in Investment banks for Java projects. By the this is second article on Eclipse IDE in Javarevisited after sharing Top 30 Eclipse keyboard shortcuts to improve productivity in the previous post.

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.

String Deduplication of G1 Garbage collector to Save Memory from Duplicate String in Java 8

You might not be aware that Java 8 update 20 has introduced a new feature called "String deduplication" which can be used to save memory from duplicate String object in Java application, which can improve the performance of your Java application and prevent java.lang.OutOfMemoryError if your application makes heavy use of String. If you have profiled a Java application to check which object is taking the bulk of memory, you will often find char[] object at the top of the list, which is nothing but internal character array used by String object. Some of the tools and profilers might show this as java.lang.String[] as well e.g. Java Flight Recorder, but they are essentially pointing to the same problem i.e. a major portion of memory is occupied with String objects.

Data Access Object (DAO) design pattern in Java - Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields rest of application from any change in the persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example, if you are authenticating the user using a relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make a change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of an application. By using DAO design pattern your View Layer is completely independent of DAO layer and only Service layer has the dependency on it which is also abstracted by using DAO interface.

Friday, February 24, 2017

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 Read File in One Line in JDK 7 or Java 8

Reading a file in Java is not simple, it requires lots of boiler plate code, as we have seen in our earlier example of reading text files. Various things had to wrapped e.g. a FileInputStream inside a BufferedReader, loops with weird terminating conditions had to be specified and so forth. From JDK 7 onward,  you can do a lot better. It provides lots of useful classes e.g. Files and Paths to deal with file and their actual path. In this article, we will see how we can read a file in just one line. Of course, your production code won't be like that, especially if you are reading a few gigabytes into memory and want to pay attention to the character set, if you don't specify, by platform's default character encoding will be used.  In short, you will need a little more code, but for quick and dirty file reading this should do the trick. By the way, It wouldn't be a one-liner if it had exception handling. In a production application you would need to deal with the fact that the file isn't there e.g. displaying an error for the user, posting metrics, logging the error etc, but it certainly be lot less boiler code than it used to be.

How to Format and Display Number to Currency in Java - Example Tutorial

Displaying financial amount in respective currency is common requirement in Java based E-commerce applications. For example if you are selling products on-line globally, you will show price of product in their local currency rather than USD or some other currency. Storing price in every currency is not a good option because of maintenance, and more realistically fluctuation in exchange rates. That's why many of these application prefer stores price of books, electronic goods or whatever product they are selling in USD, and responsibility of converting that price to local currency and displaying is left to client side code. If your client is Java based client e.g. Swing GUI , Java FX client, or a JSP web page, you can use java.text.NumberFormat class to format currency in Java.

Thursday, February 23, 2017

Overriding equals() and hashCode() method in Java and Hibernate

Override equals and hashCode in Java
Equals and hashCode in Java are two fundamental methods which are declared in Object class and part or core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object. equals and hashCode have used extensively in Java core library like they are used while inserting and retrieving Object in HashMap, see how to get method of HashMap works in Java for the full story, equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects. Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable is pointing to same memory location i.e. essentially they are the same object. Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic and many classes in Java standard library does override it e.g. String overrides equals,  whose implementation of equals() method return true if the content of two String objects is exactly same. Integer wrapper class overrides equal to perform numerical comparison etc.

5 Differences between COALESCE and ISNULL in SQL Server

What is the difference between COALESCE and ISNULL is one of the frequently asked Microsoft SQL Server interview question. Recently, one of my reader asked the same question to me, he got confused between these two because both are used to replace NULL values to default values in SQL Server. I'll try to answer this question here with little bit of insight about when to use ISNULL and COALESCE in SQL Server. Even though both ISNULL and COALESCE is used to provide default values for NULLs there are some key differences between them e.g. ISNULL() is a T-SQL or Microsoft SQL Server specific function or operator, and datatype and length of result depends upon parameter, but COALESCE is a SQL ANSI standard, it can accept more than one parameter and unlike ISNULL, the result doesn't directly depends upon parameter, it is always the type and length of the value returned.

Top 20 jQuery Interview Questions and Answers

Without a doubt, jQuery has given a much needed boost to JavaScript, a language so useful but equally underrated at times. Before jQuery comes into picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functionality. Those code were at times both difficult to read and maintain. Having written JavaScript before using this excellent library, I realized true power of jQuery, just after using it for a month. Given it's huge popularity, jQuery interview questions are increasingly asked in any web developer interview, not just beginners but also experienced developers, including HTML and JavaScript. Since jQuery is relatively new, most interview questions are asked from core jQuery library including selectors, DOM manipulation and jQuery basics.

2 Ways to Combine Arrays in Java – Integer, String Array Copy Example

There are multiple ways to combine or join two arrays in Java, both for primitive like int array and Object e.g. String array. You can even write your own combine() method which can use System.arrayCopy() to copy both those array into the third array. But being a Java developer, I first looked in JDK to find any method which concatenates two arrays in Java. I looked at java.util.Arrays class, which I have used earlier to compare two arrays and print arrays in Java, but didn't find a direct way to combine two arrays. Then I looked into Apache Commons, ArrayUtils class, and bingo, it has several overloaded method to combine int, long, float, double or any Object array. Later I also found that Guava ,earlier known as Google collections also has a class ObjectArrays in com.google.common.collect the package, which can concatenate two arrays in Java. It's always good to add Apache commons and Guava, as supporting library in Java project, they have lots of supporting classes, utility and method, which complements rich Java API. In this Java programming tutorial, we will see an example of these 2 ways to combine, join or concatenate two arrays in Java and will write a method in core Java to concatenate two int arrays in Java.

Wednesday, February 22, 2017

5 Difference between Constructor and Static Factory method in Java- Pros and Cons

The common way to create objects in Java is by using public constructors. A class provides public constructor e.g. java.lang.String so anyone can create an instance of String class to use in their application, but, there is another technique which can be used to create objects in Java and every experienced Java programmer should know about it. A class can provide a public static factory method which can return an instance of the class e.g. HashMap.newInstance(). The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.

How to execute native shell commands from Java Program

How to execute native shell commands from JAVA
Though it’s not recommended but some time it’s become necessary to execute native operating system or shell command from JAVA, especially if you are doing some kind of reporting or monitoring stuff and required information can easily be found using native command. This is not advised though because then you will lose platform independence which is why we mostly used JAVA.

Anyway if you no choice and you want to execute native commands from JAVA then its good to know that how we can do it, many of you probably know this but for those who don't know and have never done it we will see through an example.

Tuesday, February 21, 2017

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 :

Fixing java.net.BindException: Cannot assign requested address: JVM_Bind in Tomcat, Jetty

Some of the most dreaded error in Java based client server based application is networking related error, e.g. java.net.BindException: Cannot assign requested address: JVM_Bind. I have faced this issue, while working with web servers like Tomcat, Jetty, and Weblogic before, but yesterday it came again, when one of my colleague faced this issue in Windows. As soon as Java programmers sees java.net.BindException, they come to conclusion that it's issue with two process listening on same port, and often mistook it for Java.net.BindException: Address already in use: JVM_Bind:8080, which is slightly different than this.

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.

How to Swap Two Numbers Without Temp or Third Variable in Java - Interview Question

How to swap two numbers without using temp or third variable is common interview question not just on Java interviews but also on C and C++ interviews. It is also a good programming questions for freshers. This question was asked to me long back and didn't had any idea about how to approach this question without using temp or third variable, may be lack of knowledge on bitwise operators in Java or may be it didn't click at that time. Given some time and trial error, I eventually come out with a solution with just arithmetic operator but interviewer was keep asking about other approaches of swapping two variables without using temp or third variable. Personally, I liked this question and included in list of my programming interview question because of its simplicity and some logical work, it force you to do. When learned bit-wise operation in Java I eventually find another way of swapping two variables without third variable, which I am going to share with you guys.

Monday, February 20, 2017

10 points about volatile modifier or field in Java

The volatile modifier has always been an interesting and tricky topic to many Java programmers. I still feel that it's one of the most underutilized modifiers in Java, which can do a lot of good if understood and applied correctly, after all, it provides a lock-free way to achieve synchronization in Java. If a field is shared between multiple threads and one of them change its value i.e. one thread reads from the field which is written by other threads, then, by using a volatile modifier, you can synchronize access to this field. The volatile modifier in Java provides visibility and ordering guarantee without any locking. You might know that compiler and JVM can re-order your code due to various reasons e.g. performance improvement which can be a problem in concurrent Java application.

Sunday, February 19, 2017

Insertion Sort Algorithm in Java with Example and Explanation

The Insertion sort is another simple sorting algorithm, which can be used to sort any linear data structure like an array or linked list. On simplicity, this is next to bubble sort, and it’s also pretty close to how humans manually sort something (for example, a hand of playing cards). As the name suggest, Insertion sort is based upon insertion of an element in a sorted list. To start, we assume that first element is already sorted. Then we pick the next element and put it in second place, we compare this number with the first element and if they are not in sorted order, we swap them. This gives a new sorted list of 2 elements. Now we pick the third element and put it in the 3rd place and compare it with the 2nd placed number, if they are not in sorted order, we swap them again, if all three elements are still not in sorted order then we again swap the 1st and 2nd element, now we have a sorted list of three numbers.

How to Install JDK on Windows - Java Programming Tutorial

Installing JDK is first step in learning Java Programming. If you are using Windows 8 or Windows 7 Operating System, than installing JDK is quite easy as you just need to follow instruction given by Java SE Installation wizard. Only thing which requires some attention is, choosing correct JDK installer based upon, whether you are running with 32-bit or 64-bit Windows 8 or Windows 7 OS. JDK 7 is latest Java version but JDK 6 is still most popular in software and programming world. You can choose to install JDK 7 or JDK 6 based upon your course material. In this Java tutorial, we will learn how to install JDK 7 in Windows 8 operating system by following step by step guide. Another thing, which is part of JDK installation is setting PATH for Java in Windows 8, this will enable to run javac and java command from any directory in Windows 8. See that link for step by step guide on setting PATH in Windows 8. Though, I will use Windows 8 operating system to install JDK 7, You can still install JDK 6 or 7 in Windows 7 by following those steps. In order to choose correct JDK installer, we first need to check if Windows is running with 32-bit or 64-bit Windows 8. For that you can go to Control Panel-->System and Security and check System Type, if it shows 32-bit operating system means you need Windows x86 Java Installer, if it shows 64-bit operating system than you need Windows x64 Java Installer. Let's see steps involved to install JDK 6 or JDK 7 in Windows 8 operating system.

Saturday, February 18, 2017

FIX Protocol tutorials: Difference between Session Level Reject and Business message Reject

FIX Protocol tutorials: Difference between Session Level Reject and Business message Reject
In FIX protocol there are multiple ways of rejecting message some of them are using an Execution Report (MsgType=8) and ExecType=8 to reject a FIX message if it can not be acceptable by exchange e.g. Sending order for an exchange and link between broker and exchange is down. Another way of rejecting message is OrderCancelReject (FIX MsgType=9) which is used to reject amend (OrderCancelReplace message FIX MsgType 35=G) and cancel (OrderCancelRequest FIX MsgType=F) messages if its not possible to modify or cancel original message e.g. Sending Cancel request to an already filled order will be rejected by OrderCancelReject message in FIX protocol.

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.

Difference between Comparison (QuickSort) and Non-Comparison (Counting Sort) based Sorting Algorithms?

For many of you, this might be a surprise that how you can sort or arrange items without comparing with each other, but it's possible. There are some sorting algorithms that perform sorting without comparing the elements rather by making certain assumption about the data they are going to sort. The process is known as non-comparison sorting and algorithms are known as the non-comparison based sorting algorithms. No comparison sorting includes Counting sort which sorts using key value, Radix sort, which examines individual bits of keys, and Bucket Sort which examines bits of keys. These are also known as Liner sorting algorithms because they sort in O(n) time. They make certain assumption about data hence they don't need to go through comparison decision tree.

How to disable JUnit Test - @Ignore annotation Example

If you are using JUnit 4, then you can use @Ignore annotation to disable a test case; what this means is that, any method which is annotated by @Ignore, will not be executed by JUnit. Why would you want to disable a test? Well, It may be because that particular test is for a functionality which is not yet implemented fully and because of that your build is failing. Like that there could be some other scenarios where you would like to temporarily disable a test or a group of tests. From JUnit 4 onward test methods are annotated with @Test, so if they are also annotated with @Ignore will not be executed as tests. Apart from disabling a single method you can also disable all methods of a class by using @Ignore annotation at class level. For example, If you annotate a class containing test methods with @Ignore and none of the containing tests will be executed. Native JUnit 4 test runners should report the number of ignored tests along with the number of tests that ran and the number of tests that failed. Also worth noting is that @Ignore annotation takes an optional default parameter if you want to record why a test is being ignored, very useful if you are not the only person who is working on that piece of code. If there is a reason to disable a test case, later that can be enabled if reason is already sorted.

Friday, February 17, 2017

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.

Difference between UTF-8, UTF-16 and UTF-32 Character Encoding

Main difference between UTF-8, UTF-16 and UTF-32 character encoding is how many bytes it require to represent a character in memory. UTF-8 uses minimum one byte, while UTF-16 uses minimum 2 bytes. BTW, if character's code point is greater than 127, maximum value of byte then UTF-8 may take 2, 3 o 4 bytes but UTF-16 will only take either two or four bytes. On the other hand, UTF-32 is fixed width encoding scheme and always uses 4 bytes to encode a Unicode code point. Now, let's start with what is character encoding and why it's important? Well, character encoding is an important concept in process of converting byte streams into characters, which can be displayed. There are two things, which are important to convert bytes to characters, a character set and an encoding. Since there are so many characters and symbols in the world, a character set is required to support all those characters. A character set is nothing but list of characters, where each symbol or character is mapped to a numeric value, also known as code points.

On the other hand UTF-16, UTF-32 and UTF-8 are encoding schemes, which describe how these values (code points) are mapped to bytes (using different bit values as a basis; e.g. 16-bit for UTF-16, 32 bits for UTF-32 and 8-bit for UTF-8). UTF stands for Unicode Transformation, which defines an algorithm to map every Unicode code point to a unique byte sequence.

 For example, for character A, which is Latin Capital A, Unicode code point is U+0041, UTF-8 encoded bytes are 41, UTF-16 encoding is 0041 and Java char literal is '\u0041'. In short, you must need a character encoding scheme to interpret stream of bytes, in the absence of character encoding, you cannot show them correctly. Java programming language has extensive support for different charset and character encoding, by default it use UTF-8.

How to Create Tabs UI using HTML, CSS, jQuery, JSP and JavaScript

JSP is still a popular technology for developing view part of Struts and Spring based Java application, but unfortunately it doesn't have rich UI support available in GWT, or any other library. On other day, we had a requirement to display HTML tables inside tabs, basically we had two tables of different data set and we need to display them in their own tabs. User can navigate from one tab to other, and CSS should take care of which tab is currently selected, by highlighting active tab. Like many Java developers, our hands on HTML, CSS and JavaScript is little bit tight than a web guy, and since our application is not using any UI framework, we had to rely on JSP to do this job.

Since display tag is my favourite, I had no problem to dealing with tabular data, our only concern was how we will develop tabbed UI by just using HTML, CSS, JavaScript or may be jQuery. It looks everything is possible with these technology, we eventually able to develop our JSP page, which can show data in tabs.

So if you need to create tabs in JSP page, you can use this code sample, all you need to ensure is you have required libraries e.g. display tag library, JSTL core tag library and jQuery. I will explain you step by step how to create tabs in html or jsp page.

Repeating groups in FIX Protocol

FIX Protocol repeating group
In this FIX protocol tutorial, I am going to share my experience about FIX repeating block or group. This is a fundamental concept of FIX protocol and used to carry repeating data. A correct understanding of various available FIX repeating groups e.g. PartyID block, Allocation repeating group etc is very important for writing FIX based software. In this FIX tutorial, I will explain about how to parse a repeating group, how to prepare a repeating group and how to understand a repeating group. If you like to know more about basic concepts in FIX protocol then you may find my FIX Protocol tutorial interesting.

How to create and call stored procedure in MySQL with IN and OUT parameters

It's hard to remember exact syntax of, how to create stored procedure in MySQL, until you are creating and working on stored procedure frequently, simply because syntax is not a one liner. You need to remember exact syntax, if you are using MySQL database from command line. What help in this case is, quick examples. In last couple of MySQL tutorial we have seen How to find second highest salary and How to join 3 tables in one query; In this MySQL tutorial we will see couple of examples of creating stored procedure and calling stored procedure using IN and OUT parameters. All these MySQL examples are simple and help you to understand syntax of creating stored procedure with parameters in MySQL. These examples are tested in MySQL 5.5 database. We will also use following employee table to create and test these stored procedures :

Thursday, February 16, 2017

How to set Java Path and Classpath in Windows 8 and Windows 7 - Tutorial

So, you just bought a new PC or Laptop with Windows 8 operating system, and wondering how to set PATH and Classpath on Windows 8; Or, you might have just upgraded your windows 7 laptop to professional edition of Windows 8 and looking to set JDK Path to compile Java programs. Not to worry, this is the second step for anyone who wants to learn Java programming. Of course, the first step is to install JDK.  In this Java tutorial, we will see step by step guide to set Java PATH and CLASSPATH in Windows 8 operating system. By the way, if you are learning Java in Windows 7 operating system, You should still be able to set Java path and classpath in Windows 7 by following steps given here, because navigation steps for modifying environment variables on Windows 7 and Windows 8 are almost same.

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.

Wednesday, February 15, 2017

How to convert XMLGregorianCalendar to Date to XMLGregorianCalendar in Java - Example Tutorial

There are several ways to convert XMLGregorianCalendar to Date in Java. You can convert XMLGregorianCalendar to either java.util.Date or java.sql.Date based upon your need. JAXB (Java API/Architecture for XML Bindings) is a popular framework to create XML documents from Java Objects and Java objects from XML files. JAXB also helps to create Java classes from XML Schema file (.XSD file). By default JAXB maps XSD data type xs:date, xs:time and xs:dateTime to XMLGregorianCalendar in Java, but you can configure XJC to create java.util.Date objects instead of javax.xml.datatype.XMLGregorianCalendar. Since java.util.Date is most popular way of dealing with date and time in Java, we often need to convert XMLGregorianCalendar instance to Date instance in Java. Thankfully by using Java API, we can easily do this conversion of XMLGregorianCalendar to Date and Date to XMLGregorianCalendar in Java. By the way, It's good to remember that XML Schema has three different types which can represent either date, time or both, while java.util.Date contains date and time information together. In this Java and XML tutorial, we will see example of converting XMLGregorianCalendar to Date and inverse in Java.

Top 6 SQL Query Interview Questions and Answers

The SQL, short form of Structured Query Language is one of the essential skills in today's programming world. No matter whether you are a Java developer, C++ developer or Python developer, you must know how to write SQL queries. Every programming job interview has at least one or two questions which require you to write SQL query for given requirement and many developers struggles there. It's easy to answer theoretical questions like what is the difference between clustered and non-clustered index (see) or what is the difference between correlated and non-correlated subqueries (see), but when it comes time to actually write SQL queries to solve problems, it's not that easy, especially if you haven't done your homework and practice.

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.

Tuesday, February 14, 2017

How to Add Leading Zeros to Integers in Java – String Left Padding Example Program

From Java 5 onwards it's easy to left pad Integers with leading zeros when printing number as String. In fact, You can use the same technique to left and right pad Java String with any characters including zeros, space. Java 5 provides String format methods to display String in various format. By using format() method we can add leading zeros to any Integer or String number. By the way, this is also known as left padding Integers with zero in Java. For those who are not familiar with left and right padding of String, here is a quick recap; When we add characters like zero or space on left of a String, its known as left padding and when we do the same on the right side of String, it's known as right padding of String. This is useful when you are displaying currency amounts or numbers, which has fixed width, and you want to add leading zeros instead of space in front of Integers.

How to Implement Thread in Java with Example

How to implement Thread in Java
In my opinion, Thread is one of the most important features of Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming class in India how important Thread was portrait and how much emphasis given on clear understanding of multi-threading. It’s still popular and one of most sought after skill in Java programmer because writing concurrent and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. Main problem with using multiple threads and writing multi-threaded code is issues related to concurrency e.g. deadlock, livelock, race conditions etc, It takes lot of effort to implement multi-threading correctly in Java application.

Why Static Code Analysis is Important?

From last few years, Software code quality and security has went from being a “nice to have” to a necessity, and many organizations, including investment banks are making it mandatory to pass static code analysis test, penetration testing and security testing before you deploy your code in production. Static analysis tools like findbugs and fortify are getting popular every passing day and more and more companies are making fortify scan mandatory for all new development.  For those unaware of what static code analysis is, static code analysis is about analysing your source code without executing them to find potential vulnerabilities, bugs and security threats.

Solving java.lang.ArrayindexOutOfBoundsException: 1 in Java

The error ArrayIndexOutOfBoundsException: 1 means index 1 is invalid and it's out of bound i.e. more than the length of the array. Since array has a zero-based index in Java, this means you are trying to access the second element of an array which only contains one element. The ArrayIndexOutfBoundsException comes when your code, mostly for loop tries to access an invalid index of the array. If you have worked in C, C++ then you will notice this difference between array in C and Java. You simply cannot access invalid array index in Java i.e. indexes which are less than zero and more than the length of the array. ArrayIndexOutOfBounds is also a subclass of IndexOutOfBoundsException which is used to throw error related to invalid index e.g. try to access outside of length in String etc.

Monday, February 13, 2017

How to Find First and Last element in LinkedList Java - Doubly linked list

In this article you will learn how to get the first and last element of a linked list with the help of getFirst() and getLast() of LinkedList class. If you have programming or even gone to computer science course you probably know what is a linked list? It's a data structure which allows you to store objects in a such a way that you can don't need a big chunk of contiguous memory like another popular data structure array. It work perfectly even if you have a fragmented heap. LinkedList is Java's implementation of this fundamental data structure. There are two types of linked list, singly and doubly linked list, and Java's LinkedList is a doubly linked list. If you are wondering what is difference between a singly and doubly linked list, well in singly linked list you can traverse only in one direction from head to tail, or from first to last element because every node has address of only next node. While in doubly linked list, every node has reference to both previous and next node, thus allows you to traverse in both direction, from head to tail and backwards. You can verify this by yourself by looking at code of java.util.LinkedList in Eclipse, just use shortcut Ctrl + T and type the name, if you have added Java source code in Eclipse, it will open the class. You will find that LinkedList has a private static class called Node, which has reference to both previous and next node.

Top 5 Websites for Practicing Data structures and Algorithms for Coding Interviews Free

Are you preparing for Coding Interviews? If yes then you might know that there are a number of free online resources to practice important topics for coding Interviews e.g. data structure and algorithms, database and SQL, and others. These websites are equally useful for both, new programmers who are just learning the fundamentals and for experienced ones who are brushing up their coding skills for interviews. I have been sharing useful resources for programming and technical interviews from a long time in this book. In past, I have shared some recommended books for coding interviews and some of the frequently asked programming interview questions from tech companies (see here). But, my readers have been asking about some recommended websites for practicing programming challenges and coding interview questions.

Sunday, February 12, 2017

Difference between Right shift and Unsigned right shift in Java ( >> and >>> )

There are two types of right shift operator in Java >> and >>>,  former is known as right shift and later is known as right shift with zero fill or simply unsigned right shift operator in Java.  Though both of them are known as bit shift operators and moves bits patterns towards right hand side of a bit sequence, there is subtle difference between them. When we use right shift operator i.e. ">>" it keeps sign bit intact i.e. if original number is negative then it will remain negative even after right shift i.e. first or most significant bit never lost, doesn't matter how many times you shift. On the other hand unsigned right shift operator ">>>" doesn't preserve sign of original number and fills the new place with zero, that's why it's known as unsigned right shift operator or simply right shift with zero fill. Since Java represent negative numbers as 2's complement and all of its integral data types except char is signed, it's very important to remember this subtle difference between signed and unsigned right shift operator. This also means that negative numbers in Java has first or most significant bit (the left most) set, i.e. 1, while for positive number this bit is always zero. All these confusions will remain until you see an example of right shift operator and do it by yourself, so what are we waiting for, let's jump into an example.

5 JSTL Core IF Tag Examples in JSP - Tutorial

<c:if>  or if tag of JSTL core tag library in JSP is one of the most versatile and useful tag. JSTL if tag allows you
to test for a condition, like checking for a particular parameter in requestScope, sessionScope or pageScope. You can also  check any parameter in request parameters and headers or can check for a variable in JSP page using <c:if> tag. JSTL if tag helps a lot to reduce amount of Java code from JSP  page and if used, along with expression language JSTL core tag library, can remove almost all Java code from JSP files. Earlier we have seen examples of JSTL foreach tag and JSTL core set tag and this JSP JSTL tutorial is based on if tag of JSTL core tag library. We will, see how to use <core:if> tag inside JSP files and different example of <core:if> tag to get ourselves familiar with functionality and power offered by JSTL <c:if> tag. After seeing these examples of <core:if> tag along with expression language, You will be amazed to see, how clean your JSP looks like.

Saturday, February 11, 2017

Display tag Pagination, Sorting Example in JSP and Servlet

If you are a Java programmer, writing JSP pages for your web application and doesn't know much about JavaScript, jQuery, CSS and HTML, then display tag is best for creating dynamic tables, pagination, sorting, and exporting data into PDF, Word and Excel format. Display tag is a JSP tag library, where code is written in Java but you can use them like HTML tags e.g. <display></display> . Though display tag is old library, I have always used in JSP for displaying tabular data. It comes with sample CSS as well, which is good enough for many applications. Long time back, I have shared some display tag tips and example, and many of my reader asked me to write about how to do pagination and sorting in JSP page.

How to convert JSON String to Java object - Jackson Example

JSON stands for JavaScript object notation, is a lightweight text or string representation of an object and quickly becoming a popular data exchange format. Though it's pretty early to say that JSON is going to replace XML as popular data interchange format, It is certainly providing an alternative. JSON represent data in two format either an object or an array. JSON object is an unordered collection of key and value, similar to String representation of hash table. On the other hand, JSON Array is an ordered collection of values. The main difference between  JSON Object and  JSON array is there representation. JSON object is started with left brace { and ends with right brace } and key values are separated using a colon (:). On the other hand, JSON Array starts with left bracket [ and ends with right bracket ] and each value is separated by comma. By looking at structure, You can write  your JSON parser to parse JSON object or array to Java object, but you don't need to.