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 comes 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 the language allows you to catch anything which is an 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 an instance of java.lang.Throwable is a 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 the 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.

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

The string is very popular among the Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based on 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 question, how to count the number of words in Java String. Before jumping to the solution, just read below to make sure what a word means here. It's a sequence of one or more non-space characters.

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 the Microsoft SQL Server database, Sometimes, it's better to connect the 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 databases you have heard e.g. Oracle, MySQL, PostgreSQL, DB2, etc. All the steps are pretty much the same, so once you know how to connect the 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.

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 bytes unsigned data type in java mainly used to store characters. You can convert a single character into String for any purpose in Java in more than one way. I thought about this article while writing how to convert Integer to String in Java but t it took a little longer to get this post completed. In this Java tutorial, we will see different ways to convert a 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 on 18th March 2014, and there is a lot of buzz and excitement about this path-breaking release in Java community. One feature, which is synonymous with this release is lambda expressions, which will provide the ability to pass behaviors to methods. Prior to Java 8, if you want to pass behavior to a method, then your only option was Anonymous class, which will take 6 lines of code and the most important line, which defines the behavior is lost in between. Lambda expression replaces anonymous classes and removes all boilerplate, enabling you to write code in a functional style, which is sometimes 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 the 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 the 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.

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 doesn’t know what is remote debugging? It’s a way of debugging any process that 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 increases 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.  

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. The beauty of this question is that it has an 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 skills 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 objects 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 the persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields the rest of the 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.

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 boilerplate 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.

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

Displaying financial amounts in the respective currency is a common requirement in Java-based E-commerce applications. For example, if you are selling products on-line globally, you will show price of products 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 applications prefer stores price of books, electronic goods, or whatever product they are selling in USD, and the responsibility of converting that price to local currency and displaying is left to client-side code. If your client is a 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 of 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.

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 questions. Recently, one of my readers 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 a 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 like ISNULL() is a T-SQL or Microsoft SQL Server-specific function or operator, and datatype and length of the result depends upon a parameter, but COALESCE is a SQL ANSI standard, it can accept more than one parameter and unlike ISNULL, the result doesn't directly depend upon a 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 the picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functions. Those codes were at times both difficult to read and maintain. Having written JavaScript before using this excellent library, I realized the true power of jQuery, just after using it for a month. Given its huge popularity, jQuery interview questions are increasingly asked in any web developer interview, not just beginners but also experienced developers, including HTML and JavaScript.

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 methods to combine int, long, float, double, or any Object array.

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 a 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 that 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 that 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 some time it’s become necessary to execute a 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 the 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 the JDK installation directory. When you install JDK in your machine (Windows, Linux, or UNIX) it creates a home directory and puts all it's binary (bin), library(lib), and other tools. In order to compile the java program "javac" tool should be in your PATH and in order to get that in PATH we use the 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 the different operating systems 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 the same time, Since Java is a multi-threaded programming language hence the risk of Race condition is higher in Java which demands a clear understanding of what causes a race condition and how to avoid that. Anyway, Race conditions are just one of the hazards or risks presented by the use of multi-threading in Java just like deadlock in Java. Race conditions occur when two thread operate on the same object without proper synchronization and their operation interleaves on each other.

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 a 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 colleagues faced this issue in Windows. As soon as Java programmers see java.net.BindException, they come to the conclusion that its an issue with two processes listening on the 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 a common interview question not just on Java interviews but also on C and C++ interviews. It is also a good programming question for freshers. This question was asked to me long back and didn't have any idea about how to approach this question without using temp or third variable, maybe lack of knowledge on bitwise operators in Java or maybe 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 the interviewer kept asking about other approaches of swapping two variables without using temp or third variable.

Monday, February 20, 2017

10 points about volatile modifier or field in Java

The volatile modifier has always been an interesting and tricky topic for 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 changes 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.

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 suggests, the Insertion sort is based upon the insertion of an element in a sorted list. To start, we assume that the 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.

How to Install JDK on Windows - Java Programming Tutorial

Installing JDK is the first step in learning Java Programming. If you are using Windows 8 or Windows 7 Operating System, then installing JDK is quite easy as you just need to follow instructions given by Java SE Installation wizard. The 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 the latest Java version but JDK 6 is still most popular in the software and programming world. You can choose to install JDK 7 or JDK 6 based upon your course material.

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 lie. The main difference between ArrayList and LinkedList is that ArrayList is implemented using a resizable 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 a certain assumptions 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 assumptions about data hence they don't need to go through a 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 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.

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

The main difference between UTF-8, UTF-16, and UTF-32 character encoding is how many bytes it requires to represent a character in memory. UTF-8 uses a minimum of one byte, while UTF-16 uses a minimum of 2 bytes. BTW, if the character's code point is greater than 127, the 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 a 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, the character encoding is an important concept in the process of converting byte streams into characters, which can be displayed.

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 another 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. Users can navigate from one tab to another, and CSS should take care of which tab is currently selected, by highlighting the active tab. Like many Java developers, our hands-on HTML, CSS, and JavaScript is a 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.

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 the exact syntax of, how to create a stored procedure in MySQL until you are creating and working on stored procedure frequently, simply because the syntax is not a one-liner. You need to remember the exact syntax if you are using the MySQL database from the 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 a couple of examples of creating stored procedure and calling stored procedure using IN and OUT parameters. A

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 the 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 the 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

The 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 requirements to produce items or consuming items. by using producer-consumer patterns both Producer and Consumer Thread can work with different speeds.

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.

Top 6 SQL Query Interview Questions and Answers for Software Engineers and Data Scientists

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 a given requirement and many developers struggle 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 the biggest nemesis of someone who has just started programming and that too in Java. Since the main method in java is the 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 the 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

Hello guys, you may know that 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 formats. By using the format() method we can add leading zeros to an 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 the left and right padding of String, here is a quick recap;

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 the 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 classes in India how important Thread was a portrait and how much emphasis is given on a clear understanding of multi-threading. It’s still popular and one of most sought after skills in Java programmer because writing concurrent and multi-threaded applications in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword.

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 an 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 to Learn Data structures and Algorithms FREE - Best of Lot

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 for a long time in this book. In the past, I have shared some recommended online courses and books for coding interviews, as well as 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.

5 JSTL Core IF Tag Examples in JSP - Tutorial

<c:if>  or if the tag of JSTL core tag library in JSP is one of the most versatile and useful tags. 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 the 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 the tag of the JSTL core tag library.

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 the display tag is an old library, I have always used it 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 examples, and many of my readers asked me to write about how to do pagination and sorting on the 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 the 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 (:).

Friday, February 10, 2017

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, the reason it touches concurrency a bit, and the interviewee can go deep on it to ask how fail-safe or fail-fast behavior is implementedIn this article, we will see what is fail-safe and fail-fast iterators in java and differences between fail-fast and fail-safe iterators. The concept of the fail-safe iterator is relatively new in Java and first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap and CopyOnWriteArrayList.

Constructor vs Init method in Servlet - JEE Interview Question

Can we have a Constructor in Java Servlet? or Why do we need a constructor in Servlet if there is already an init() method for initializing Servlet, or what is the difference between init() method and constructor in Servlet are a couple of questions I have seen in various Java web developer interviews. All of these questions are related to the role of the constructor and init() method in the Servlet implementation class. Though I had shared few thoughts on this, when I wrote the top 10 Servlet questions for Java programmers,  I thought to cover it in more detail here.

Thursday, February 9, 2017

How to Implement Linked List in Java With JUnit Test Example

In this article, we will learn two things, how to implement a linked list from scratch in Java and how to write a unit test using JUnit framework. Though Java has LinkedList class, which is an implementation of the doubly linked list, its good to know how to implement singly linked list in Java, mostly to practice coding interview questions. Coming to back to writing a unit test, from time to time, I have said that a Java programmer must write unit tests. IMHO, unit testing is the best development practice to improve code quality. Fortunately, Java ecosystem has the luxury of great unit testing frameworks in form of JUnit and TestNG, and every Java developer should take advantage of this.

How to remove all special characters from String in Java

You can use a regular expression and replaceAll() method of java.lang.String class to remove all special characters from String. A special character is nothing but characters like ! #, %, etc. Precisely, you need to define what is a special character for you. Once you define that you can use a regular expression to replace those characters with empty String, which is equivalent to removing all special characters from String. For example, suppose, your String contains some special characters e.g. "Awesome!!!" and you want to remove those !!! to reduce some excitement, you can use replaceAll("!", "") to get rid of all exclamation mark from String.

Introduction of How Android Works for Java Programmers

Android development is a current buzz in the Java programming world. It's Android, which keeps Java at the forefront of the last couple of years. Now, How important is it to understand or learn Android for Java programmers? Well, it depends on, if you like application development and wants to reach a mass, Android offers that opportunity to you. Millions of Android phones are available and they keep increasing, with pace, much higher than iPhone or iOS. What all these means is, it does make a lot of sense to learn Android programming for Java programmers, and this article is about that, but this is also one of the good reasons to learn Java programming. This tutorial will give you a basic idea of How Android works? not detailed but a good overview.

Wednesday, February 8, 2017

17 Examples of Calendar and Date in Java

The java.util.Calendar class was added in Java on JDK 1.4 in an attempt to fix some flaws of the java.util.Date class. It did make some task simpler, e.g. create an arbitrary date comes easier using new GregorianCalendar(2016, Calendar.JUNE, 11) constructor, as opposed to Date class where the year starts from 1900 and Month was starting from zero. It didn't solve all the problems e.g. mutability and thread-safety of Date class still remains, but it does make life easier at that time. Now with Java 8 everything related to Date and Time has become super easy and consistent but unfortunately, it will take another 5 to 10 years before the older version of Java goes away. Don't believe me, there are still applications running on JDK 1.5 which was released 12 years ago. The bottom line is it's still important to know about Date and Calendar in Java.

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 the open-source frameworks like Struts, Spring, and Displaytag which uses a 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.

How to Fix java.net.ConnectException: Connection refused: connect in Java

java.net.ConnectException: Connection refused: connect is one of the most common networking exceptions in Java. This error comes when you are working with client-server architecture and trying to make a TCP connection from the client to the server. Though this is not as cryptic as java.lang.OutOfMemoryError: Java heap space or java.lang.UnsupportedClassVersionError, it’s still a frequent problem in distributed Java applications. java.net.ConnectException: Connection refused: connect also comes in the case of RMI (Remote Method Invocation) because RMI also uses TCP-IP protocol underneath. While writing client socket code in Java, You should always provide proper handling of this exception

Tuesday, February 7, 2017

Java Comparable Example for Natural Order Sorting

Java allows you to sort your object in natural order by implementing Comparable interface. It's one of the fundamental interfaces of Java API and defined in java.lang package, which means you don't need to implement this unlike its counterpart Comparator, which is defined in java.util package.  Comparable is used to provide natural order of sorting to objects e.g. numeric order is a natural order for numbers, alphabetic order is a natural order for String and chronological order is natural for dates. Similarly when you define your own objects e.g. Person, sorting it on name sounds natural. Similarly, for teams, ranking seems their natural order. It all depends on how the object is looked into in their domain.

Top 5 Concurrent Collections Java Programmer Should Know

Several new Collection classes are added in Java 5 and Java 6 especially concurrent alternatives of standard synchronized ArrayList, Hashtable and  synchronized HashMap collection classes. Many Java programmer still not familiar with these new collection classes from java.util.concurrent package and misses a whole new set of functionality which can be utilized to build more scalable and high-performance Java application. In this Java tutorial, we will some of the useful collection classes like ConcurrentHashMap, BlockingQueue which provides some of the very useful functionalities to build concurrent Java applications.

Monday, February 6, 2017

Top 10 Java wait, notify, Locking and Synchronization Interview Questions

There has been a lot of articles and books written on how to use wait and notify in Java, how they work, when do you need synchronization, and how to write concurrent code in Java, but, unfortunately, I still see many Java programmer struggles to solve even the classic producer-consumer problem. I know, writing correct concurrent code is challenging and it takes a lot of practice, think through ability and experience to get it right, but at the same time, every Java programmer should be familiar with basics of inter-thread communication, synchronization, locking and understand how all the things work together.

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.

How to Read/Write from RandomAccessFile in Java

Random access file is a special kind of file in Java which allows non-sequential or random access to any location in the file. This means you don't need to start from 1st line if you want to read line number 10, you can directly go to line 10 and read. It's similar to the array data structure, Just like you can access any element in the array by index you can read any content from the file by using file pointer. A random-access file actually behaves like a large array of bytes stored in the file system and that's why it's very useful for low latency applications which need some kind of persistence e.g. in front office trading application and FIX Engine, you can use random access file to store FIX sequence numbers or all open orders.

How to Join Multiple Threads in Java - Thread Join Example

Join method from Thread class is an important method and used to impose order on execution of multiple Threads. The concept of joining multiple threads is very popular on a multithreading interview question. Here is one such question, “You have three threads T1, T2, and T3, How do you ensure that they finish in order T1, T2, T3 ?. This question illustrates the power of the join method on multithreaded programming. Unlike classical thread questions like the difference between wait and sleep method or solving the producer-consumer problem in Java, This one is a bit tricky.

Sunday, February 5, 2017

FIX Protocol Session or Admin messages tutorial

FIX Protocol Session or Admin messages tutorial
I have been working on FIX protocol for almost 5 years when I started working on FIX protocol I looked upon internet for some good tutorial which could supplement or complement lengthy FIX protocol specification there was nothing at that time so when I started my blog I thought to write about my own experience in FIX protocol as short, clear and concise tutorial format. Since I like question answer type of knowledge sharing too I have written some blog post on FIX protocol Interview questions you may find it interesting. In today’s FIX tutorial we are going to have a look on FIX protocol session level messages. As you guys may know all FIX messages can be broadly classified into two categories Admin messages also called session level messages and Application messages which include Trade, pre trade and post trades messages.

Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two objects is known as the association in object-oriented general software design and depicted by an arrow in Unified Modelling Language or UML. Both Composition and Aggregation are the forms of association between two objects, but there is a subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer association between two objects as Composition, when one class owns other classes and other classes can not meaningfully exist, when it's owner destroyed, for example, Human class is a composition of several body parts including Hand, Leg, and Heart. When human object dies, all its body part ceased to exist meaningfully, this is one example of Composition.

Saturday, February 4, 2017

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

Why wait, notify and notifyAll is declared in Object Class instead of Thread is a 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. The beauty of this question is that it reflects what does interviewee knows about the wait notify mechanism, how does it sees the whole wait and notify feature, and whether his understanding is not shallow on this topic. Like Why Multiple inheritances 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 everyone could justify their reason.  

How to disable submit button in HTML JavaScript to prevent multiple form submission

Avoiding multiple submissions of HTML form or POST data is a common requirement in Java web application. Thankfully, You can prevent multiple submissions by disabling the submit button in HTML and JavaScript itself, rather than handling it on the server-side. This is a very common requirement while developing a web application using Servlet and JSP or any other web technology. At the same time, there is a lot of information and noise available in web, and its very hard to find a simple approach to the disable submit button. When I search for a simple way to disable the submit button in HTML and JavaScript, I was overwhelmed by responses on forums and various online communities.

Introduction to Tibco Hawk as Tibco Tutorial

Tibco Hawk
This is another short  TIBCO tutorial from my TIBCO tutorial series. in this i am gonna discuss what is TIBCO hawk , Where do we use TIBCO hawk , What are components of TIBCO hawk , what benefit TIBCO hawk offers and how Tibco hawk works.  if you are interested to know more about TIBCO  Rendezvous , TIBCO EMS and there fundamental concept  or if you are looking for some TIBCO Interview questions you may find this link interesting TIBCO Tutorial