Wednesday, May 31, 2017

Dealing with Password in Java Application? 5 Best Practices You Should Follow

While working in core Java application or enterprise web application there is always a need of working with passwords in order to authenticate user. Passwords are very sensitive information like Social Security Number(SSN) and if you are working with real human data like in online banking portal or online health portal its important to follow best practices to deal with passwords or Social security numbers. here I will list down some of the points I learned and take care while doing authentication and authorization or working with password. I recommend to read more on this topic and have a checklist of things based on your application requirement. Anyway here are few points which make sense to me:

Tuesday, May 30, 2017

ThreadLocal in Java - Example Program and Tutorial

ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application. In this Java ThreadLocal tutorial we will see important points about ThreadLocal in Java, when to use ThreadLocal in Java and a simple Example of ThreadLocal in Java program.

How to Check if Integer Number is Power of Two in Java - 3 examples

How to check if an integer number is a power of 2 in Java is one of the popular programming interview question and has been asked in many interviews. Surprisingly, this problem which looks simple enough to answer, doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less experienced,  struggle to write code for a function, which can check if number is power of 2 or not. There could be many different reasons for that, but it’s expected to at least come up with brute force solution. For those who are familiar with bitwise operators in Java , how positive and negative numbers are represented in binary format, this exercise is quite easy. Since negative numbers are represented as 2's complement value in Java, you can easily find if any number is power of 2 or not by looking at its bit pattern. Remember checking for power of two is different than checking if number is even or odd, that’s another thing to note. A number can be even, but it’s not necessary to be a power of  two, e.g. 6 is even but it’s not a power of two.

Monday, May 29, 2017

How to format JSON String in Java - Jackson Example Tutorial

You can format JSON String in Java using Jackson API's pretty print feature. As you might have noticed in my previous JSON tutorials that the output of the programs is not properly formatted, which makes them hard to read, especially in large log files where there are so many other texts, both JSON and normal text is there. That's why its advised to print JSON String properly formatted because then it will stand out in log file or console. Whenever we print JSON String from Java Programs by using method writeValueAsString(), it usually comes in one line, as shown in the following example :

Sunday, May 28, 2017

Java Tips and Best practices to avoid NullPointerException in Java Applications

A NullPointerException in Java application is best way to solve it and that is also key to write robust programs which can work smoothly. As it said “prevention is better than cure”, same is true with nasty NullPointerException. Thankfully by applying some defensive coding techniques and following contract between multiple part of application, you can avoid NullPointerException in Java to a good extent. By the way this is the second post on NullPointerException in Javarevisited, In last post we have discussed about common cause of NullPointerException in Java and in this tutorial,  we will learn some Java coding techniques and best practices, which can be used to avoid NullPointerException in Java. Following these Java tips also minimize number of !=null check, which litter lot of Java code. As an experience Java programmer, you may be aware of some of these techniques and already following it in your project, but for freshers and intermediate developers, this can be good learning. By the way, if you know any other Java tips to avoid NullPointerException and reduce null checks in Java, then please share with us.

Law of Demeter in Java - Principle of least Knowledge - Real life Example

Law of Demeter also known as principle of least knowledge is a coding principle, which says that a module should not know about the inner details of the objects it manipulates. If a code depends upon internal details of a particular object, there is good chance that it will break as soon as internal of that object changes. Since Encapsulation is all about hiding internal details of object and exposing only operations, it also assert Law of  Demeter. One mistake many Java programmer makes it exposing internal detail of object using getter methods and this is where principle of least knowledge alerts you. I first come to know about this principle, while reading one of the must read programming book,  Robert C. Martin's Clean code. Apart from many good thing the book teaches you, "principle of least knowledge" is one principle, which I still remember.

Saturday, May 27, 2017

Top 10 Java Multithreading and Concurrency Best Practices

Writing concurrent code is hard and and testing correctness with concurrency is even harder. Though Java programming language provides lots of synchronization and concurrency support from language to API level, it's eventually comes to individual's diligent and expertise to write bug free Java concurrency code. These Java concurrency and multi-threading best practices are collection of some well known tips, which helps you to write better concurrency code in Java. Some of you, may be familiar with these tips, it's often worth to revise them in couple of years. These Java multi-threading and concurrency tips are from my own learning and usage, and also inspired by reading books like Effective Java and Java Concurrency in Practice in particular. I suggest reading Java Concurrency Practice two times to every Java developer, yes, you heard it correctly, TWO times. Concurrency is confusing and difficult to comprehend, much like Recursion to few programmers; and in one reading, you might not get all of it.

Friday, May 26, 2017

Double Checked Locking on Singleton Class in Java

Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenge they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created. By the way, it was broken before Java fixed its memory models issues in JDK 1.5. In this article, we will see how to write code for double checked locking of Singleton in Java, why double checked locking was broken before Java 5 and How that was fixed.

By the way this is also important from interview point of view, I have heard it’s been asked to code double checked locking of Singleton by hand on companies in both financial and service sector, and believe me it’s tricky, until you have clear understanding of what you are doing. You can also see my full list of Singleton design pattern questions to prepare well.

Thursday, May 25, 2017

Class file in Java - things to know for programmer and developer

.class file in Java is core of achieving platform independence which is key feature of Java. class files are compiled form of any Java program written in byte codes. Since Java program executes inside JVM, these instructions are read by JVM and than translated into machine code for underlying platform. effectively you can run class file on any platform if you have a corresponding JVM supported for that platform. Java compilers are responsible for generating .class file and they follow class file format specified by Sun and its different based on different Java version. This article is not a detailed one focused on class file format instead it contains basic information about class files and intended to give an idea about what is a class file in Java and what are some important points related to class files.

This Java article is in continuation of my series of 10 points of interface in Java and 10 Object oriented design principles for Java programmer. If you haven’t got chance to read them you may find them useful.

How to Access Private Field and Method Using Reflection in Java

Reflection in Java is very powerful feature and allows you to access private method and fields which is not possible by any other means in Java and because of this feature of reflection many code coverage tool, static analysis tool and Java IDE like Eclipse and Netbeans has been so helpful. In last article we have seen details about private keyword in Java and learned  why we should always make fields and method private in Java. There we have mentioned that private fields and methods are only accessible in the class they are declared but with reflection you can call private method and access private fields outside the class. In this article we will see simple example of accessing private field using reflection and invoking private method using reflection in Java.

Wednesday, May 24, 2017

How to Copy File in Java Program - Example Tutorial

How to copy file in Java from one directory to another is common requirement, given that there is no direct method in File API for copying files from one location to another. Painful way of copying file is reading from FileInputStream and writing same data to FileOutputStream to another directory. Though this process works its pretty raw to work with and best approach is for anyone to create library for common File operation like cut, copy, paste etc. Thankfully you don't need to reinvent wheel here, there are some open source library available which allows us to copy file in Java easily from one directory to another. One of such library is Apache commons IO which contains a class called FileUtils, which provides utility method for file related operation. FileUtils.copyFile(sourceFile, targetFile) can be used to copy files in Java.  This Java program copy file from one location to other using FileUtils class.

This Java programming tutorial is next in series of earlier article in File API like how to create hidden file in Java  and how to read from text file. If you are new to Java File API you may find them useful.

10 XSLT or XML, XSL Transformation Interview Questions and Answers

XSLT stands for XML style sheet transformation and it as XML technology used to transform one XML into another XML or HTML format.  XML and XSLT interview questions are commonly asked Java developers, who happen to use XML in their project and mentioned XSLT as a key skill in their resume. Given XML’s popularity as data transfer protocol, many systems in middle and back office space uses XML messages to transfer trade details, for example, Bookings, Settlement, and Confirmation system use it as a data exchange protocol. Since each of this system performs some normalization, enrichment, and transform on incoming trade message, they use XSLT for that transformation. XSLT is rich, powerful and given its support in Java and several other programming languages, it comes the natural choice of XML transformation. What you need to is to write XSL files, also known as XML style sheet to specify your transformation rule and then XSLT engine will transform each incoming XML documents as per your XSL file. 

Different Types of JDBC Drivers in Java - Quick Overview

How many types of JDBC drivers in Java is a classical JDBC interview question , though I have not see this question recently but it was very popular during 2006 - 2008 period and still asked mostly on Junior programmer level interviews. There are mainly 4 types of JDBC drivers in Java, those are referred as type 1 to type 4 jdbc drivers. I agree its easy to remember them by type rather than with there actual name, Which I have yet to get in memory except plain old JDBC-ODBC bridge driver. By the way here are there full names :

Type 1 JDBC Driver is called JDBC-ODBC Bridge driver (bridge driver)
Type 2 JDBC Driver is referred as Native-API/partly Java driver (native driver)
Type 3 JDBC Driver is called AllJava/Net-protocol driver (middleware driver)
Type 4 JDBC Driver is called All Java/Native-protocol driver (Pure java driver)

This JDBC tutorial is in continuation of my earlier tutorials in JDBC like How to connect to Oracle database using JDBC 
and  4 tips to improve performance of JDBC applications. If you are new here and haven't read them already, Its worth looking.  Anyway out of all those 4 types, JDBC-ODBC Bridge driver is most common for connecting SQL Server, MS Access and mostly on training and development. here are quick review of all these four types of JDBC drivers. Also there has been some speculation of type 5 JDBC driver, I have to yet to see it.

Tuesday, May 23, 2017

How to Use Break, Continue, and Label in Loop – Java Program Example

break and continue in Java are two essential keyword beginners needs to familiar while using loops ( for loop, while loop and do while loop). break statement in java is used to break the loop and transfers control to the line immediate outside of loop while continue is used to escape current execution and transfers control back to start of the loop. Both break and continue allows programmer to create sophisticated algorithm and looping constructs. In this java tutorial we will see example of break and continue statement in Java and some important points related to breaking the loop using label and break statement. break keyword can also be used inside switch statement to break current choice and if not used it can cause fall-through on switch. Well break is not alone on breaking switch case you can also sued throw keyword on switch case.

This Java tutorial is next in series of articles in looping like 4 ways to loop Map in Java and How to loop on ArrayList in Java. If you are new here and haven’t gone through those articles then you may find them useful.

Monday, May 22, 2017

Why use SerialVersionUID inside Serializable class in Java

Serialization and SerialVersionUID is always remains a puzzle for many Java developers. I often see questions like what is this SerialVersionUID, or what will happen if I don't declare SerialVersionUID in my Serializable class? Apart from complexity involved and rare use, one more reason of these questions is Eclipse IDE's warning against absence of SerialVersionUID e.g. "The Serializable class Customer does not declare a static final SerialVersionUID field of type long". In this article, you will not only learn basics of Java SerialVersionUID but also it's effect during serialization and de-serialization process. When you declare a class as Serializable by implementing marker interface, Java runtime persist instance of that class into disk by using default Serialization mechanism, provided you have not customized the process using Externalizable interface.

Fixing Unsupported major.minor version 52.0 Error in Java

Unsupported major.minor version 52.0 comes when you are trying to run a class compiled using Java 1.8 compiler into a lower JRE version e.g. JRE 1.7 or JRE 1.6. Simplest way to fix this error is install the latest Java release i.e. Java 8 and run your program. If upgrading to Java 8 is not an option then make sure you use Java compiler's cross compilation feature and compile source code for lower Java version by using -target option of javac command. If you have multiple JRE installed make sure that the latest one comes first in PATH environment variable. You can get "java.lang.unsupportedclassversionerror unsupported major.minor version 52.0" while running a Java program explicitly using java command or running a Java Applet in browser or running a Java program from command line but compiled in Eclipse or any other build tool like Maven or ANT. Main reason of this error is that during compilation, you have used a higher version of JDK but during deployment, you have deployed into a lower version of JDK or JRE. Let's understand the cause and solution of Unsupported major.minor version 52.0 Error in little more detail.

TL:DR; upgrade to Java 8 or compile for lower JRE version using java -target 1.6 option.

What is Bean scope in Spring MVC framework with Example

Bean scope in Spring framework or Spring MVC are scope for a bean managed by Spring IOC container. As we know that Spring is a framework which is based on Dependency Injection and Inversion of Control and provides bean management facilities to Java application. In Spring managed environment bean (Java Classes) are created and wired by Spring framework. Spring allows you to define how those beans will be created and scope of bean is one of those details. This Spring tutorial is next on my earlier post on Spring like how to implement LDAP authentication using Spring security and  How to limit number of user session in web application, if you haven’t read them already you may find them useful.

In spring framework bean declared in ApplicationContext.xml can reside in five scopes:

1) Singleton (default scope)
2) prototype
3) request
4) session
5) global-session

Sunday, May 21, 2017

How to use Counting Semaphore in Concurrent Java Application? Example Tutorial

Counting Semaphore in Java is a synchronizer which allows to impose a bound on resource is added in Java 5 along with other popular concurrent utilities like CountDownLatch, CyclicBarrier and Exchanger etc. Counting Semaphore in Java maintains specified number of pass or permits, In order to access a shared resource, Current Thread must acquire a permit. If permit is already exhausted by other thread than it can wait until a permit is available due to release of permit from different thread. This concurrency utility can be very useful to implement producer consumer design pattern or implement bounded pool or resources like Thread Pool, DB Connection pool etc. java.util.Semaphore class represent a Counting semaphore which is initialized with number of permits. Semaphore provides two main method acquire() and release() for getting permits and releasing permits. acquire() method blocks until permit is available. Semaphore provides both blocking method as well as unblocking method to acquire permits. This Java concurrency tutorial focus on a very simple example of Binary Semaphore and demonstrate how mutual exclusion can be achieved using Semaphore in Java.

Saturday, May 20, 2017

Why wait notify and notifyAll called from synchronized block or method in Java

Most of the Java developers knows that wait(), notify(), and notifyAll() methods of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why? Recently this questions was asked to in Java interview to one of my friend, he pondered for a moment and replied that if we don't call wait() or notify() method from synchronized context we will receive IllegalMonitorStateException in Java. He was right in terms of the behavior of language but as per him, interviewer was not completely satisfied with the answer and wanted to explain him mor about it. After the interview, he discussed the same questions with me and I thought he should have to tell interviewr about race condition between wait() and notify() in Java which could exist if we don't call them inside synchronized method or block. Let’s see how it could happen in a Java program.

SED Command Examples in UNIX and Linux, Find and Replace using Regular Expression

SED command in UNIX  is stands for stream editor and it can perform lot's of function on file like, searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening it, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it. In this SED command tutorial we will see some practical examples of SED command in UNIX based systems e.g. Linux. I must say having a good grip on find, grep, sort, vi editor and SED can take you next level of UNIX and Linux working experience. These are very powerful UNIX command and helps with lot of different tasks in server. By the way we will use following text file for our SED common example. As I have said before, best way to learn any UNIX command is to use them in your day to day task, and a good example is a good start. This file contains details of some popular android and iPhone smartphones, e.g. Model, company, price etc, separated by colon. You can also use any CSV file for this example.

Friday, May 19, 2017

How to differentiate between an Average and a Good Programmer?

When it comes to interview, goal is to find the most suitable developer for job to get done but its very difficult to judge someone's caliber, experience and expertise in short duration of Interview. There is always a process starting from phone interview, written tests to face-to-face interview, but its still difficult to hire the right programmer. Process can help you to filter candidates but eventually it will come down to your experience and gut feeling. As you take more and more interviews, you will know what to ask and what not and like many other interviewers in the world, you will develop some of your own tips. Similarly, I have developed couple of tips from my experience which has helped me to differentiate an average programmer with a good programmer in past. Today I would like to share one of such tips with you guys, to see if you agree with my observation and hopefully I will get couple of more tips to find right programmers. One of my most used tip is finding gaps in requirement. I have found and learnt it over time that good developers has knack of breaking requirements and finding gaps, which is very important to produce quality software and products. Though this skill comes with experience, a good developer even with less experience has this ability. In this article, I will share my hypothetical interview with two programmers and see what they produced.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 - Solving Array IndexOutOfBoundsException in Java

If you are coming from C background than there is pleasant surprise for you, Java programming language provides implicit bound checks on Array, which means an invalid array index access is not allowed in Java and it will result in java.lang.ArrayIndexOutOfBoundsException. Array is one of the most used data structure across all programming language and it’s no different in Java. In fact Java API has used array to build several useful data structures e.g. HashMap and ArrayList. These classes also throws IndexOutOfBoundsException if invalid index is supplied to their get(int index) methods. One of the common mistakes Java programmer makes is invalid end condition on classical index based for loops.

Thursday, May 18, 2017

5 Difference between Application Server and Web Server in Java

Application server and web server in Java both are used to host Java web application. Though both application server and web server are generic terms, difference between application server and web server is a famous J2EE interview question. On  Java J2EE perspective main difference between web server and application server is support of EJB. In order to run EJB or host enterprise Java application (.ear) file you need an application server like JBoss, WebLogic, WebSphere or Glassfish, while you can still run your servlet and JSP or java web application (.war) file inside any web server like Tomcat or Jetty.

This Java interview question are in continuation of my previous post on interviews like Top 10 Spring interview questions and  Top 10 Struts interview question.  Here we will see some difference between application server and web server in point format which will help you to answer this question in any java interview.

Wednesday, May 17, 2017

How to Generate Random Numbers in Java Between Range - Example Tutorial

In software development and programming world, we often need to generate random numbers, sometimes random integers in a range e.g. 1 to 100 etc. Thankfully, Random number generation in Java is easy as Java API provides good support for random numbers via java.util.Random class, Math.random() utility method and recently ThreadLocalRandom class in Java 7, along with more popular features like String in Switch and ARM blocks. While random() method seems the most convenient way of generating randoms in Java it only returns random doubles, on the other hand by using Random,  you can generate pseudo-random integer, floating point numbers e.g. double and even random boolean values. In this article Java tutorial, we will see how to generate random numbers in Java, examples to generating random integers and real numbers, and random numbers within a range e.g. between 1 to 6. we will also explore the difference between Math.random() and java.util.Random class in Java.

Tuesday, May 16, 2017

How to Find Prime Factors of Integer Numbers in Java - Factorization Algorithm

One of the common homework/tasks in programming courses is about Prime Factorization. You are asked to write a program to find prime factors of given integer number. The prime factors of a number are all of the prime numbers that will exactly divide the given number. For example, prime factors of 35 are 7 and 5, both are prime in itself and exactly divides 35. Last time I did this exercise when I was in college, and it was something like, writing a program that asks the user for an integer input and then displays that number's prime factorization on the command line.   There are variants of this program as well e.g. look at this exercise, Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. It's more or less same as the earlier mentioned version of prime factorization problem, but with a catch of displaying them in decreasing order.

Sunday, May 14, 2017

Difference Between Abstract Class vs Interface in Java

When to use interface and abstract class is one of the most popular object oriented design questions and almost always asked in Java, C#, and C++ interviews. In this article, we will mostly talk in the context of Java programming language, but it equally applies to other languages as well. The question usually starts with a difference between abstract class and interface in Java, which is rather easy to answer, especially if you are familiar with the syntax of Java interface and abstract class. Things start getting difficult when interviewer ask about when to use abstract class and interface in Java, which is mostly based upon a solid understanding of popular OOPS concepts like Polymorphism, Encapsulation, Abstraction, Inheritance, and CompositionMany programmers fumbles here, which is natural because most of them haven't gone through real system design process and haven’t seen the impact of choosing one over other. 

Top 30 UNIX command Interview Questions asked in Investment Banks

UNIX Interview Questions and Answers
UNIX or Linux operating system has become default Server operating system and for whichever programming job you give interview you find some UNIX command interview questions there. These UNIX command interview questions are mostly asked during Java development and Support role interviews on various investment banks mostly because most of electronic trading systems or stock trading system works on Unix servers. As we know that high volume low latency systems which wants to take advantage of little bit of volatility in market for Equity , Futures and options or Foreign exchange trading need a stable server side operating system and Redhat Linux is doing great job there. with the advent of Algorithmic trading this speed factor becomes more important so getting someone who has good knowledge of operating system and commands on which these trading system runs is definitely required. but these UNIX command interview questions are equally applicable for any job interview which requires some work on Unix Operating System. With the growing use of Linux in form of RedHat, Solaris and IBM AIX its must to keep you familiar with essential Linux commands available on various platforms. 

jQuery Tutorial - How to modify multiple HTML elements in one line

jQuery allows you to modify multiples elements in one go, you can modify attributes, text, or color of multiple HTML elements by executing just one line of jQuery code. In this jQuery tutorial, I will show you how to modify multiple <li> elements in one go. In our example, we have a couple of <li> tag to display sub-headings, now we will change them in one go using jQuery. If you look at our HTML, we have an ordered list <ol> to display top 10 programming languages, each of them is a <li> item. We also have one button, "Click Me", which will when clicked, changes all <li> item's text to "jQuery is the new Boss". Here is the jQuery code, which does that.

Saturday, May 13, 2017

10 Articles Every Programmer Must Read

Being a Java programmer and Software developer, I have learned a lot from articles titled as What Every Programmer Should Know about ..... , they tend to give a lot of useful and in-depth information about a particular topic, which otherwise is very hard to discover. In my quest of learning, I have come across some very useful articles, which I have bookmarked for reference and multiple reading. I personally think that all programmer can benefit by reading these articles, which makes me write this post and share all of these "What Every Programmer Should Know" articles with you guys. These are from my personal bookmarks. In this article, you will see classic what every programmer should know article from topics like memory, Unicode, floating point arithmetic, networking, object oriented design, time, URL Encoding, String and many more.

How to Find If Linked List Contains Loop or Cycle in Java - Coding Interview Question With Solution

Write a Java program to check if a linked list is circular or cyclic,  and how do you find if a linked list contains loop or cycles in Java are some common linked list related data structure interview questions asked in various Java Interviews. This is some time asked as follow-up question of basic linked list questions like inserting element at beginning, middle and end of linked list or finding length of linked list. In order to solve linked list related algorithmic question in Java, you need to be familiar with concept of singly linked list, doubly linked list and circular linked list. Until stated specifically, most questions are based on singly linked list. For those who are not familiar of linked list data structure, its a collection of nodes. Each node contains two parts data and address, where address part points to another node in linked list. Last node of linked list, often referred as tail points to null. Also a singly list can only move in one direction, towards end. Now, let's come back to this question. Good thing about this question is that, it can also be solved by using two pointer approach discussed in How to find middle element of linked list in single pass. If a linked list contains a loop or cycle it is known as circular or cyclic linked list. As I said we can use two pointer approach to check if a linked list is circular or not.

Friday, May 12, 2017

Can you take Spring certification without Pivotal Training Course?

Yes, you can take Spring certification without taking mandatory Spring training. Pivotal, the company behind Spring, has announced on 10th May 2017 that "Spring Certification Exams are now available for individual purchase, without enrolling in the course". This is one of the most exciting changes in the Spring certification program since it's launched 10 years back. The cost of Spring certification was the single, biggest obstacle for many experienced Java and Spring developers to get certified for their Spring framework skills. This step from Pivotal is a really positive step and gives a real chance to many experienced developers in cost-sensitive countries like India to get certified for their skill. Now, you don't have to enroll for a 50K training if you have good knowledge of Spring certification and exam objectives, just like Java certification, you can buy the Spring certification voucher @ 200 USD and take the exam online or offline at any test center.

Thursday, May 11, 2017

Solution of java.lang.OutOfMemoryError: GC overhead limit exceeded

The java.lang.OutOfMemoryError: GC overhead limit exceeded is another type of OutOfMemoryError in Java which comes when JVM spent too much time doing garbage collection without any success.  For example, if almost 98% of CPU for a Java process is busy doing GC and reclaims very less amount of Java heap space around 2%, then JVM throws "java.lang.OutOfMemoryError: GC overhead limit exceeded" error. Though, the definition of 98% CPU time may vary between different Garbage collector and different JVM version.  Unlike java.lang.OutOfMemoryError: Java heap space and java.langOutOfMemory: Permgen space, this is not so frequent and you will rarely encounter this error in your Java application, but this also denotes resource exhaustion.

Wednesday, May 10, 2017

tibrvnative.dll : Can't load IA 32-bit .dll on a AMD 64-bit platform - Windows 8

Can't load IA 32-bit .dll on a AMD 64-bit platform is a generic error, which comes when a 64-bit process tries to load a 32-bit dll, but when it comes its not that easy to resolve. One of my reader was getting this error tibrvnative.dll : Can't load IA 32-bit .dll on a AMD 64-bit when he was trying to install Tibco Rendezvous 8.2 on his Windows 8 HP Laptop. He was working on Java application which was dependent upon Tibco Rendezvous for inter process communication. After installing Tibco on his machine he was having hard time to run his Java application, first he was getting errors like java.lang.UnsatisfiedLinkError: no tibrvnative in java.library.path and after resolving that he was getting a new error tibrvnative.dll: Can't find dependent libraries.

Difference between LEFT and RIGHT OUTER Joins in SQL - MySQL Join example

There are two kinds of OUTER joins in SQL, LEFT OUTER join and RIGHT OUTER join. The main difference between RIGHT OUTER join and LEFT OUTER join, as there name suggest, is the inclusion of non-matched rows. Sine INNER join only include matching rows, where the value of joining column is same, in the final result set, but OUTER join extends that functionality and also include unmatched rows in the final result. LEFT outer join includes unmatched rows from table written on the left of join predicate. On the other hand, RIGHT OUTER join, along with all matching rows, includes unmatched rows from the right side of the table.

Monday, May 8, 2017

How to print 1 to 100 without using loop in Java

This is one of the interesting problems  I have seen on coding interviews  for beginners. The program has surprise element by saying that you need to print 1 to 100 without using a loop e.g. for, forEach or enhanced for loop. This brings out some innovative solutions from candidates which tell a lot about their approach, knowledge, and attitude. I remember, asking this question during campus recruitment to at least 5 candidates. The first one took 5 minutes to think and then come up with the brute force way where he just copies pasted 100 System.out.println() and printed number 1 to 100 but when we asked to improve that, he couldn't too that. Unfortunately, he didn't think that recursion can replace an iterative algorithm without using a loop.

How to Convert List of Integers to Int Array in Java - Example

So, you have a List of Integers and you want to convert them into int array? Yes you read it write, not on Integer array but int array. Though in most practical purpose, Integer array can be used in place of int[] because of autoboxing in Java, you still need an int[] if your method accepts it. In Java, you can not type cast an Integer array into int array. Many Java programmer think about toArray() method from java.util.List to convert a List into Array, but unfortunately toArray() is useless in most of times. It doesn't allow you to convert List into primitive arrays. Though you can convert List of Integers to array of Integers, but not array of primitive int. This is true for List of all wrapper class e.g. List of Float, Double, Long, toArray() method can return array of wrapper class but not primitives. After looking into Java Collection API, It seems that only traditional for loop or foreach can help, which involves iterating over Integer array and storing them into int[], but fortunately, I came across Apache Commons ArrayUtils class. ArrayUtils can do this work for us, It has several overloaded methods to convert Object arrays into primitive arrays. 

Sunday, May 7, 2017

Open source Java Libraries to Create PDF documents - iText vs Apache FOP

PDF format is a popular format for sending receipt, email confirmation and other documentation and we often has requirement to create PDF documents using Java, mostly in JSP pages. Since most of official documentation uses PDF format now days, it becomes imperative to support PDF files. Recently I received couple of question regarding suggestion of open source Java PDF libraries, like which is the best open source PDF library in Java  or should I use iText or Apache FOP in my Java application for PDF processing. These questions motivates me to write this post. In this article, I will share couple of Java based open source PDF libraries, both FREE and with some licensing fees, which you can use to generate PDF documents in Java projects.

Saturday, May 6, 2017

Difference between Servlet and JSP?

Servlet and JSP are two of the most popular Java web technologies to generate dynamic content in Java web applications there is some key difference between them. For example, Servlet is designed for Java developers as most of the coding is done in Java, while JSP was designed and developed for web GUI developer e.g. guys who write HTML and JavaScript and that's why you see the coding in JSP is tag based. Even though you can use HTML tags as String inside Servlet and Java code as Scriptlet inside JSP, both are considered as bad practice and should be avoided at all cost because they are very hard to maintain. The different nature of Servlet and JSP also allows frontend and backend developers to work in parallel, JSP work is mostly done by frontend developers while Servlet work is done by backend developers.

10 points about Java Heap Space or Java Heap Memory

10 Points about Java heap memory
When I started Java programming I didn't know what is java heap or heap space in Java, I was even not aware of where does object in Java gets created, it’s when I started doing professional programming I came across error java.lang.OutOfMemoryError in Tomcat then I realized What is Heap in Java or Java Heap Space. It happens with most of the programmer because learning language is easy but learning basics are difficult since there is no formal process which can teach you every basic of programming its experience and work which reveals the secret of programming. For Java developer knowledge of Heap in Java, setting the size of Java heap space, dealing with Java heap space OutOfMemoryError, analyzing heap dumps is very important. You should read Java Performance from Charlie Hunt to learn more about how to troubleshoot Java performance issue, profiling and advanced tools to take the heap dump and analyze it to form problem areas.

Friday, May 5, 2017

How String in Switch works in Java 7

Ever Since Java allows using String variable in switch and case statements, there are many programmers using this feature in code, which can be better written using integer and enum pattern. This was one of the popular features of JDK 7 release, including automatic resource management and multi exception catch blocks. Though I upfront didn't like this feature because of better alternative available in terms of using enumeration type, I am not totally against this feature. One reason of this is convenience and given usage of String in Java program, it's quite handy as well, but I prefer to learn more before using any new feature in production code.

When I first come to know about this feature, I had an idea that String in Switch can be implemented using equals() and hashCode() method, I was more interested on how String in Switch works in Java 7.

One more reason I was curious to know about internal working of this feature because I wanted to ask this during Java interviews, having one of such question makes interviews little more interesting. Testing was simple, you just need to write code using String variables in switch block, and then decompile the code to see, how compiler has translated them.

So what are we waiting for, Let's see how String in switch block actually works?

Tibco Tutorials for beginners

This Tibco Tutorial is collection of all my previous Tibco rendezvous and Tibco EMS tutorials. I have written this compilation post to provide all tibco tutorials at one place for easy navigation and access. Anyone who is started working on Tibco on any investment bank or brokerage house for there electronic trading systems or algorithmic trading system can benefit from these tibco tutorials because these are based on my experience in stock trading systems which uses Tibco Rendezvous for all there Front-End backend communication. Tibco Certified messaging is used by Electronic trading system or Order Management system to receive orders and Send Execution in FIX Protocol.

Thursday, May 4, 2017

Which Java 8 Certification Should you Take? OCAJP8 (1Z0-808) , OCPJP8 (1Z0-809) , or Upgrade(1Z0-810 and 1Z0-813)

There are a lot of confusion among Java programmers and Oracle Java Certification aspirants related to various Java 8 certifications e.g. what are exam codes, which exams they should go for, whether they are eligible for Java SE 8 upgrade exams, and what should they do if they have just passed Java SE 7 Programmer II certification. I will try to answer each of these questions here, but to get it right let's first clear the confusion about various Java SE 8 exams There are four Java 8 certifications available in Oracle's site:

1) Oracle Certified Associate, Java SE 8 Programmer OCAJP8, exam code 1Z0-808
2) Oracle Certified Professional, Java SE 8 Programmer OCPJP8, exam code 1Z0-809
3) Oracle Certified Professional, Java SE 8 Programmer (upgrade), exam code 1Z0-810
4) Upgrade to Java SE 8 OCP ( Java SE 6 and all prior versions) - exam code 1Z0-813

Tuesday, May 2, 2017

Top 5 Cloud Service Providers and Companies, Java IT professionals Should Know

Cloud computing is Hot, it's the biggest IT trend of last few years and will continue to grow strong in coming future. Cloud computing provides several not-so-easy-to-ignore advantages, especially to public and small enterprises, which cannot afford to own and maintain expensive data centres. Since most of online business now days need high avaibility, scalability, and resiliency, with-in quick time, it's not possible to achieve all these by your own, and cloud computing becomes a best alternative here. Cloud service providers like Amazon Web Services (AWS) has helped several firms to remain focus on their business, without worrying for IT and infrastructure too much, this has yield big result for them.

Java Program to Find Sum of Digits in a Number using Recursion - Interview Question

Recently this question to asked was one of my reader, which inspired me to write this tutorial. There was usual check to solve this problem using both recursion and iteration. To be frank, calculating sum of digit of an integral number, is not difficult, but I have still seen quite a few programmers fumbles, even after providing hint in terms of division and modules operator. Key point here is to know how to use division and modules operator in Java. For this kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modules operator or % to get right most digits. For example if you have number 1234 than 1234/10 will give you 123 i.e. right most digit 4 is removed, while 1234%10 will give you 4, which is the right most digit in that number. If you know this property, you can easily solve lots or problems which are related to reversing numbers e.g. checking if a number is palindrome or finding Armstrong numbers in Java.

Top 10 Tips on Logging in Java - Tutorial

Java logging or logging in java is as much an art as science. knowing write tools and API for java logging is definitely science part but choosing format of java logs , format of messages, what to log in java , which logging level to use for which kind of messages are purely an experienced based things and sort of art which you learn by applying logging in java. Since its proven fact that java logging severely affects performance and I have seen latency of online stock trading application goes multiple times if they run in DEBUG mode than in WARN or higher level mode. Since latency and speed is major concern for any electronic trading system or high volume low latency stock trading system, it becomes absolutely necessary to understand and learn java logging in great details and best practices and tips available on logging in java. This is not just for finance and investment banking domain but also to any java server or client application which requires speed and java logging at same time. 

Monday, May 1, 2017

Cause of "java.lang.SecurityException: Missing required Permissions manifest attribute in main jar" [Solved]

If you are working Java Web start application using JNLP and suddenly started throwing "java.lang.SecurityException: Missing required Permissions manifest attribute in the main jar", then check whether you have updated the Java or JRE on your machine. From JDK 1.7 update 51, Java has tightened the security further with number of changes e.g.

1) Block all self-signed and unsigned Java application and Applet if you have opted for HIGH security in Java Control Panel, which is also the default one.

2) Require "Permission" attribute for High-security setting

3) Warning users of missing permission attribute for medium security setting.