Friday, March 31, 2017

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementation of Set interface for an enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago until I come across one of the finest books for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and have pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet.

Failed to connect to queue manager - WebSphere MQ Error in Java

"Failed to connect to queue manager" error comes in WebSphere MQ if any Client e.g. Java program is not able to connect to MQ server due to any reason. The reason is actually identified by reason code in error message e.g. code 2397 comes when SSL is enabled between client and server and Java client is not able to connect to server due to unknown or expired SSL certificates. If you are working in Java application which is using WebSphere MQ for messaging over SSL then you are bound to face some setup, certificate and keystore vs truststore related error. For first timers understanding SSL and MQ errors is nightmare, forget about solving them. I have gone through that and after spending hours on Google and Websphere MQ documentations, I managed to solve some of the problems we face while connecting to MQ over SSL from our Java application. In this article, I am listing down these errors and exceptions and their cause and solution for everyone's benefit. Next time you face any MQ SSL issue, hopefully you will find the right solution to solve these tricky errors. In this tutorial we will mainly looked at three errors :
  • Unable to find valid certification path to requested target
  • JMSWMQ2020: Failed to connect to queue manager
  • Remote SSL peer name error for channel 'ABC.XYZ'

I have mostly encountered these while working with Java application which was connecting to other legacy system using MQ for sending and receiving XML files, but useful to anyone who is using over MQ over SSL.

Private in Java: Why should you always keep fields and methods private?

Making members private in Java is one of best coding practice. Private members (both fields and methods) are only accessible inside the class they are declared or inside inner classes. private keyword is one of four access modifier  provided by Java and its a most restrictive among all four e.g. public, default(package), protected and private. Though there is no access modifier called package, rather its a default access level provided by Java. In this Java tutorial we will see why should we always make members of class by default as private and answer to one of popular Java interview question can override private methods in Java.

This article is in continuation of my earlier post on Java e.g. 10 Object Oriented Design principles Java programmer should know and 10 best practice to follow while writing comments. If you haven’t read them already you may find them interesting and worth reading.

Thursday, March 30, 2017

What is Effectively Final variable of Java 8

Apart from big three, Lambda expression, Stream API and new Date and Time API, Java 8 has also introduced a new concept called "effectively final" variable. A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. It's very useful in the context of the lambda expression. If you remember, prior to Java 8, we cannot use a non-final local variable in an anonymous class. If you have to access a local variable ( a method parameter or a variable decreed in the method itself) in Anonymous class, you have to make it final. This restriction is relaxed a bit with lambda coming up. Java designers have taken the need to make local variable final if it's not changed once initialized. This is really a good proactive step from them, they must have anticipated frequent use of lambda expressions as compared to the minimal use of Anonymous class and realized the pain to declare a local variable final every time in order to access it inside the lambda. The rule has not changed, any local variable still has to be effectively final to be used inside lambda expression or anonymous inner class, its just that you don't need to use final keyword anymore, saving a few keystroke. If you don't follow this then you will get following error: "local variables referenced from a lambda expression must be final or effectively final". Let's see some examples of effectively final variables with lambdas and anonymous class and how it make the life of Java developer easy. You can also read Cay S. Horstmann's Java SE 8 for Impatient to learn more about Effectively final variables in Java 8.

Wednesday, March 29, 2017

How to Compare two String in Java - String Comparison Example

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

We will see String compare Example using each of this method in example section, before that let's get some theory:

This article is in continuation of my earlier post on String  e.g. Difference between String and StringBuffer in Java and How to replace String in java using regular expression etc. If you haven’t read them already you may find them useful and worth reading.

How to format Date in SQL Server and Sybase Example

How to format a date in SQL Server like in the "yyyymmdd" format? Suppose you have a date and time column in Sybase or Microsoft SQL Server,  which is displaying values in "Dec  31, 2011, 12:00 AM" and you want to display it in any particular DATE format like YYYYMMDD or DDMMYYYY, how will you do that? This is also one thing you need to keep in mind when you convert a DATE, TIME, DATETIME column into CHAR or VARCHAR values.

It's easy to format dates using the convert function in Sybase or SQL Server, but it's slightly difficult to remember the cryptic formatting style codes that go with it. For example using style code, 112 is used to format dates in "YYYYMMDD" format e.g. "20170329".

Tuesday, March 28, 2017

Hibernate NullPointerException due to Space in HQL named queries

If you are using Hibernate for implementing persistence layer in Java and JEE application from couple of years then you would have seen this notorious NullPointerException while executing HQL named queries, Exception in thread “main” java.lang.NullPointerException at org.hibernate.hql.ast.ParameterTranslationsImpl .getNamedParameterExpectedType (ParameterTranslationsImpl.java:63).  Hibernate has some poor logging in case of Exception, which has caused me hours to debug a simple problem. By looking at NullPointerException below (look full stacktrace below), I had no clue that it's coming because of a missing space on HQL (Hibernate Query language) query. You can also take a look if you can figure this out :

How to loop ArrayList in Java - List Itrator Traversal Code Example

Looping ArrayList in Java or Iteration over ArrayList is very similar to looping Map in Java. In order to loop ArrayList in Java we can use either foreach loop, simple for loop or Java Iterator from ArrayList. We have already touched iterating ArrayList in 10 Example of ArrayList in Java and we will see here in detail. We are going to see examples of all three approaches in this ArrayList tutorial and find out which one is clean and best method of looping arraylist in Java. Before start writing an example for loop in ArrayList let's think why do we need to iterate, traverse or loop an ArrayList if it’s based on index and backed by Array. If we know the index of element than we can directly get that particular element from ArrayList but if you want to print all elements of arraylist and do some operation one by one on each of them, only looping or traversing will help you.

This article is in continuation of my earlier tutorial on ArrayList e.g. How to sort ArrayList in Java on descending order and How to convert Array to ArrayList in Java. If you haven’t read them already then you may find them useful and interesting.

What is Assertion in Java - Java Assertion Tutorial

Java Assertion or assert keyword in Java is little unknown and not many programmers are familiar with this and it's been rarely used especially if you have not written a unit test using JUnit which extensively uses Java assertion to compare test result. Junit itself is the biggest manifestation of what assertion in Java can do and believe me by using assertion along with Exception you can write robust code. Assertion not only improves the stability of code but also help you to become a better programmer by forcing you to think about different scenario while writing production quality code and improving your think through ability.

2 Scenario Based Data Structure and Algorithm Design Interview Questions from Investment Banks

No doubt that Data structure and algorithms are an integral part of any Programming job interview, including Java, C++ or any other programming language. In fact Data structure and algorithms are quite a favorite one and all top notch companies including Google, Microsoft, Amazon and investment banks like Goldman Sachs, Citigroup, Barclays, Morgan Stanley or J.P. Morgan focus extensively on data structure and algorithms, while hiring both senior and mid-level developers in Java, C++, and C# positions. When I shared some traditional, popular, and more frequently asked questions on Data structure and Algorithms in my earlier article, I received a lot of feedback to share some practical, scenario-based questions on data structure e.g. which kind of data structure will you use in a particular scenario and why.

How to Convert and Print Byte array to Hex String in Java

We often need to convert byte arrays to Hex String in Java, In order to print byte array contents in a readable format. Since many cryptographic algorithms e.g. MD5 returns hash value as a byte array, In order to see and compare that byte array, you need to convert byte array to Hex String. As we have seen, while generating MD5 checksum of File, there are multiple ways to convert byte array to Hexadecimal String in Java. You can either write your own method, or you can use open source library e.g. Apache commons codec to create Hex String from a byte array in Java. Commons codec provides a utility class Hex, which contains an encodeHexString() method to create Hex String from a byte array. It's one of the best options to generate Hex String if you are already using this library to generate MD5 hash values. In this Java tutorial, we will see what is the issue with printing byte array as normal String, and 2 examples to convert a byte array into Hexadecimal String in Java.

Monday, March 27, 2017

Parsing Large JSON Files using Jackson Streaming API Example

In last couple of JSON tutorials for Java programmers, we have learned how to parse JSON using JSON-Simple library, parsing JSON array to Java array using GSon, and in this tutorial we will learn how to parse a large JSON file in Java using Jackson's Streaming API. Jackson is one of the most popular JSON processing framework and provides three main model to parse and process JSON data including Streaming API, data binding and tree model. Out of these three, Streaming works at lowest level and can be used to parse huge JSON response upto even giga bytes of size. If you are familiar with XML parsing, then you know that how difficult it is to parse huge XML files with DOM parser because it fully loads the file in memory before you can process it. In case you have low memory e.g. Android devices you can't use that to parse XML. Thankfully, XML provides SAX and StAX parsers which are streaming based and can be used to process huge files without loading them completely in memory. Out of these two, StAX is even better because it allows pull based processing where client pulls data from parser instead of parser pushing data, which is the case with SAX parser. Jackson's Streaming API is similar to StAX parser. You can pull the data you want and ignore what you don't want. Though performance doesn't come without cost, using Streaming API is little difficult then using other Jackson model which provides direct mapping between Java and Jackson objects. You have to handle all JSON data by yourself while using Streaming API.

3 ways to Find First Non Repeated Character in a String - Java Programming Problem

Write a Java program to find the first non-repeated character in a String is a common question on coding tests. Since String is a popular topic in various programming interviews, It's better to prepare well with some well-known questions like reversing String using recursion, or checking if a String is a palindrome or not. This question is also in the same league. Before jumping into solution, let's first understand this question. You need to write a function, which will accept a String and return first non-repeated character, for example in the world "hello", except 'l' all are non-repeated, but 'h' is the first non-repeated character. Similarly, in word "swiss" 'w' is the first non-repeated character. One way to solve this problem is creating a table to store count of each character, and then picking the first entry which is not repeated. The key thing to remember is order, your code must return first non-repeated letter.

Difference between Stack and Queue Data Structure in Java

Stack and Queue are two of important data structures in the programming world and have a variety of usage. As opposed to the array and linked list, which are considered as a primary data structure, they are a secondary data structure which can build using an array or linked list. You can use Stack to solve recursive problems and Queue can be used for ordered processing. The difference between Stack and Queue Data structure is also one of the common questions not only in Java interviews but also on C, C++, and other programming job interviews. Well, main difference comes the way these data structures are used, Stack is LIFO (last In First Out) data structure, which means the item which is inserted last is retrieved first, similar to a stack of plates in a dinner party, where every guest pick up the plate from the top of stack.

Sunday, March 26, 2017

How to Reverse Array in Place in Java? Solution With Explanation

Reversing an array sounds pretty easy, isn't it? It does sounds like that, because all you need to do is create an array of same size, iterate through original array from end to start and populate your new array. Boom!!, you have got an array which has elements in reverse order of original array, but problem is you have used and additional array here, which makes space complexity of your solution O(n). You cannot use this solution if array is big e.g. an array of 10 million orders and you don't have enough heap space available. Can we make it better? Can we reverse array in Java without using an additional buffer? Even If you encounter this question in your programming job interview, you will be surely asked to reverse array in place, without using an additional buffer as earlier solution takes lot of space. So now your task is to write a Java program to reverse an array in place. For the sake of this problem, you can assume that its an integer array (during interview, you should ask these question to your interviewer, because asking right question to fill the gap in requirement is a trait of good programmer and highly appreciated on both telephonic and face-to-face interviews). Key point to understand here is that you need to reverse the same array, you cannot use another array but one or two variable is fine. You are also not allowed to use any open source library or Java API which can reverse the array directly e.g. any method from java.util.Arrays class except Arrays.toString()to print arrays in Java. So now the requirement is clear, what approach comes in your mind? how do you solve this problem?

Saturday, March 25, 2017

Difference between WeakReference vs SoftReference vs PhantomReference vs Strong reference in Java

WeakReference and SoftReference were added into Java API from long time but not every Java programmer is familiar with it. Which means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in context of How Garbage collection works. As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory.

Java 1.5 Generics Tutorial: How Generics in Java works with Example of Collections, Best practices, Gotchas

Java Generics Tutorial
Generics in Java is one of important feature added in Java 5 along with Enum, autoboxing and varargs, to provide compile time type-safety. Generics is also considered to be one of the tough concepts to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too much technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering their head too much. In this Java generics tutorial, I will cover How Generics works in Java,  some mysterious wildcards in Generics and some important points about Generic in Java. I will try explaining generics concept in simple words and simple examples.

10 Exception handling Best Practices in Java Programming

Exception handling is an important part of writing robust Java application. It’s a non functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input and so on. Java provides several exception handling features, in built in language itself in form of try, catch and finally keywordJava  programming language also allows you to create new exceptions and throw them using  throw and throws keyword. In reality, Exception handling is more than knowing syntax. Writing a robust code is an art more than science, and here we will discuss few Java best practices related to Exception handling. These Java best practices are followed even in standard JDK libraries, and several open source code to better deal with Errors and Exceptions. This also comes as handy guide of writing robust code for Java programmers.

Friday, March 24, 2017

Difference between start and run method in Thread – Java Tutorial and Interview Question

Why do one call start method of thread if start() calls run() in turn" or "What is difference by calling start() over run() method in java thread" are two widely popular beginner level multi-threading interview question. When a Java programmer start learning Thread, first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and than calling start() method on thread, but with some experience he finds that start() method calls run() method internally either by looking API documentation or just poking around, but many of us just don’t care at that time until its been asked in Java Interview. In this Java tutorial we will see What is difference between calling start() method and run() method for starting Thread in Java.

This article is in continuation of my earlier post on Java multi-threading e.g. Difference between Runnable and Thread in Java and How to solve Producer Consumer problem in Java using BlockingQueue. If you haven’t read them already you may find them interesting and useful.

Difference between Wait and Sleep, Yield in Java

The difference between wait and sleep or the difference between sleep and yield in Java are one of the popular core Java interview questions and asked on multi-threading interviews. Out of three methods which can be used to pause a thread in Java, sleep() and yield() methods are defined in thread class while wait() is defined in the Object class, which is another interview question. The key difference between wait() and sleep() is that former is used for inter-thread communication while later is used to introduced to pause the current thread for a short duration. This difference is more obvious from the fact that, when a thread calls the wait() method, it releases the monitor or lock it was holding on that object, but when a thread calls the sleep() method, it never releases the monitor even if it is holding. 

Top 10 Servlet Interview Question Answers - J2EE

This time its servlet interview questions, I was thinking what to pick for my interview series and then I thought about J2EE and Servlet is my favorite on that space. Servlet is an important part of any J2EE development and serves as Controller on many web MVC frameworks and that’s why it’s quite popular on J2EE interviews. These Servlet questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for anyone who is not very familiar with servlet technology.

Servlet interview question and answerAs said earlier this interview question article is part of my earlier series java interview questions , UNIX command interview questions and Java threading interview questions.

You can find answers to all these questions on google but I have also listed my answers for quick reference.

Difference between Stack and Heap memory in Java

The difference between stack and heap memory is common programming question asked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers starts hearing once they started programming but without any clear and definite explanation. Lack of knowledge of what is a heap in Java and what is stack memory in Java results in misconceptions related to stack and heap. To add to this confusion, a stack is also a data structure which is used to store elements in LIFO(Last In First out) order and available in Java API as java.util.Stack. In general, both stack and heap are part of memory, a program is allocated and used for different purposes. Java program runs on JVM which is launched as a process by "java" command. Java also uses both stack and heap memory for different needs. In our last article 10 points on Java heap space, I have touched base on Java heap space and in this article we will see the difference between stack and heap memory in Java.

Why use PreparedStatement in Java JDBC – Example Tutorial

PreparedStatement in Java is one of several ways to execute SQL queries using JDBC API. Java provides Statement,
PreparedStatement and CallableStatement for executing queries. Out of these three, Statement is used for general purpose queries, PreparedStatement is used for executing parametric query and CallableStatement is used for executing Stored Procedures. PreparedStatement is also a popular topic in java interviews. Questions like Difference between Statement and PreparedStatement in Java and How to prevent SQL Injection attacks in Java are popular java interview questions. In this Java JDBC tutorial we will see why should you use use PreparedStatement in Java, What are the major advantages of using PreparedStatement in Java and how PreparedStatement prevents SQL Injection attacks in Java.

This article is in continuation of my earlier post on database and java like 4 tips to improve performance of Java application with database and Difference between truncate and delete in SQL.If you haven’t read  them already you may found  those tutorial useful and interesting.

Thursday, March 23, 2017

SimpleDateFormat in Java is not Thread-Safe Use Carefully

SimpleDateFormat in Java  very common and used to format Date to String and parse String into Date in Java but it can cause very subtle and hard to debug issues if not used carefully because DateFormat and SimpleDateFormat both are not thread-safe and buggy. call to format() and parse() method mutate state of DateFormat class and should be synchronized externally in order to avoid any issue. here are few points which you should take care while using SimpleDateFormat in Java:

How to find file and directory size in Unix with Example - Linux tutorial

How to find size of directory in unix
Finding file size or directory size in Unix and Linux is not very difficult but if you came from windows background than it may sounds difficult to you because you need to remember unix commands for file and directory size. This is a common complain from windows user when they exposed to Unix operating system be it Linux or Solaris. but In my opinion having commands for doing things is more powerful because you can write powerful scripts for removing large files or taking backup of directories in unix which is not possible with GUI based operating systems like Windows. In this unix command tutorial we will see how to find size of file and directory in unix, how to find large files in unix, how to find disk space in file system and some other file and directory related stuff.

This article is continuation of my earlier post on Unix e.g. 10 Example of grep command in Unix, 10 example of chmod command in unix and How to sort files and directory in Unix using sort command. If you haven’t read them already, You may find them useful and interesting.

How to Reverse a Linked List in Java Using Recursion and Iteration (Loop) - Example

There are a couple of algorithms exists to reverse a singly linked list in Java e.g. You can use the three-pointers approach or solve this problem using a stack, or simply using recursion without the external stack. As I had pointed out on the earlier post about linked list, that reversing a linked list is one of the most popular data structure interview question, based on linked list, which means, you just can't afford to prepare this one, before going for any programming interview. Despite being so common, It's not easy to solve this problem on the fly. Many Java programmer struggles to reverse a linked list using both iteration and recursion, which makes this question very useful for filtering programmers who can code and who are not so good with coding. Indeed, this is one of the confusing algorithms to understand and it's not easy to grasp, especially if you haven't practiced linked list based questions e.g. finding middle node of linked list in one pass or inserting and removing an element from linked list data structure.

How Garbage Collection works in Java

I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article. You can call it a tutorial about garbage collection in simple word, which would be easy to understand and have sufficient information to understand how garbage collection works in Java. Garbage collection works by employing several GC algorithm e.g. Mark and Sweep. There are different kinds of garbage collector available in Java to collect different area of heap memory e.g. you have serial, parallel and concurrent garbage collector in Java.

10 difference between Java and JavaScript for Programmers

Programmers, developers and internet users  have always been confused between Java and JavaScript.  Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client side scripting language for HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is Inventor of Java, popularly known as father of Java. While in today's world calling JavaScript just a client side scripting language would not be good, as its now been used in servers also using node.js and people are doing object oriented development in JavaScript, but that was what it was originally developed. There are several difference between Java and JavaScript, from how they are written, compiled and executed. Even capability of Java and JavaScript vary significantly. Java is full feature Object oriented programming language, used in almost everywhere, starting from programming credit card to server side coding. Android uses Java as programming language for creating Android apps, Swing is a Java API used to create desktop applications and Java EE is a Java platform for developing web and enterprise applications. On the other hand JavaScript is primarily used to bring interactivity into web pages, though there are other alternatives like Flash, JavaScript is the most popular one and regaining lots of ground lost earlier with introduction of powerful and easy to use libraries like jQuery and jQuery UI. You can use JavaScript to validate user input, create animation and cool effects in HTML page and can do lot of interactive stuff e.g. reacting on button click, mouse movement, image click etc. In this article, I will share some key differences between Java and JavaScript, mostly from a programmers perspective.

Wednesday, March 22, 2017

Difference between transient and volatile keyword in Java

Surprisingly "Difference between transient and volatile keyword in Java" has asked many times on various java interview. volatile and transient are two completely different keywords from different areas of Java programming language. transient keyword is used during serialization of Java object while volatile is related to visibility of variables modified by multiple thread during concurrent programming. Only similarity between volatile and transient is that they are less used or uncommon keywords and not as popular as public, static or final. Anyway its good to know what transient keyword do in Java or how to use volatile keyword in Java. In this article we will couple of points between volatile and transient which can be used to answer this interview question.

How to fix java.io.FileNotFoundException: (Access is denied)

Earlier my impression was that java.io.FileNotFoundException: (Access is denied) comes when you try to read a text or binary file for which you don't have permission from Java program but this can also come while you are using jar command. jar command internally use java.util.zip.ZipFile class to open any jar or war file which can throw java.io.FileNotFoundException: (Access is denied). I was trying to see contents of war file which was created using recent build when I stumble upon this error, see the exact command below:

test@dev454:war-store/target jar -tvf maven-eclipse-web-demo
java.io.FileNotFoundException: maven-eclipse-web-demo (Access is denied)
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:127)
        at java.util.zip.ZipFile.<init>(ZipFile.java:88)
        at sun.tools.jar.Main.list(Main.java:979)
        at sun.tools.jar.Main.run(Main.java:224)
        at sun.tools.jar.Main.main(Main.java:1149)

Top 10 basic networking commands in linux/unix

Networking is an essential part Unix and it offer lots of tools and command to diagnose any networking problem. When I was working on FIX Protocol we get a lot of support queries to see whether FIX Sessions are connected or not. Since FIX Protocol uses sockets you can use the netstat , telnet and other networking commands available in Linux for finding a problem and solve that.In this article, I will show you basic networking commands in Unix and for what purpose they are used. with the combination of grep and find command on them, you can troubleshoot most of the networking problem.

How to Reverse an Array in Java - Integer and String Array Example

This Java tips is about, how to reverse array in Java, mostly primitive types e.g. int, long, double and String arrays. Despite of Java’s rich Collection API, use of array is quite common, but standard JDK doesn’t has great utility classes for Java. It’s difficult to convert between Java Collection e.g. List, Set to primitive arrays. Java’s array utility class java.util.Arrays, though offers some of critical functionalities like comparing arrays in Java and support to print arrays, It lacks lot of common features, such as combining two arrays and reverse primitive or object array.  Thankfully, Apache commons lang, an open source library from Apache software foundation offers one interesting class ArrayUtils, which can be used in conjunction with  java.util.Arrays class to play with both primitive and object array in Java. This API offers convenient overloaded method to reverse different kinds of array in Java e.g. int, double, float, log or Object arrays. On a similar note, you can also write your own utility method to reverse Array in Java, and this is even a good programming question. For production usage, I personally prefer tried and tested library methods instead of reinventing wheel. Apache commons lang fits the bill, as it offer other convenient API to complement JDK. In this Java tutorial, we will reverse int and String array in Java using ArrayUtils to show How to reverse primitive and object array in Java.

Tuesday, March 21, 2017

Top 30 Scala and Functional Programming Interview Questions and Answers

Scala is a programming language which aims to provide best of both object-oriented programming and functional programming world. It not only allows you to  construct elegant class hierarchies for maximum code reuse and extensibility but also allows you to implement their behavior using higher-order functions and other functional programming technique. It is touted as one of the languages which can probably take over Java, though it didn't happen especially after Java 8 release which also provides some functional programming tools to Java e.g. lambda expression and stream. Nevertheless, Scala is a good language and created by following best practices from several other programming languages including Java. Scala is an acronym for “Scalable Language”. This means it is designed by keeping scalability in mind. Many companies e.g. Twitter, LinkedIn, and Intel uses it for their mission-critical application.

Binary Search vs Contains Performance in Java List

There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).

How to check if two String are Anagram in Java - Program Example

Write a Java program to check if two String are anagram of each other, is another good coding question asked at fresher level Java Interviews. This question is on similar level of finding middle element of LinkedList in one pass and swapping two numbers without using temp variable. By the way two String are called anagram, if they contains same characters but on different order e.g. army and mary, stop and pots etc. Anagrams are actually mix-up of characters in String. If you are familiar with String API, i.e. java.lang.String than you can easily solve this problem. In order to check if  Strings are anagram, you need to get there character array and see if they are equal or not. Though you can also use indexOf(), substring() and StringBuffer or StringBuilder  class to solve this question. In this Java program, we will see 3 ways to solve this interview questions, and check if two String are anagram or not. By the way, if you are preparing for Java interview, it's good to prepare some data structures and algorithms questions as well. More often, there is one or more questions from programming, coding and logic in these interviews.

Monday, March 20, 2017

How to Generate MD5 Hash in Java - String Byte Array Digest Example

There are multiple ways to generate the MD5 hash in Java program. Not only Java API provides a convenient method for generating MD5 hash, you can also use popular open source frameworks like Spring and Apache commons Codec to generate MD5 digest in Java. MD5 is popular Message Digest Algorithm, which is most commonly used to check data integrity e.g. comparing MD5 checksum to see, if any file is altered or not. Though MD5 has not considered a good cryptographic algorithm for security purpose due to several vulnerabilities found on it, it's still good enough or checking the integrity of the file. MD5 hashing algorithm generates a 128 bit or 16-byte long hash value. MD5 hash values, also known as MD5 digest is mostly represented as 32 character Hex String. You can generate an MD5 hash from a byte array, or String directly using Java, Spring and Apache commons codec. Spring and Apache commons codec has identical API e.g. class name DigestUtils is same and allows you to directly generate MD5 hash as Hex String, while if you use Java then you need to convert byte array to Hex String, as java.security.MessageDigest.digest() method returns MD5 hash as a byte array. Earlier we have seen, How to encode and decode String in base64 encoding, and In this Java tutorial we will see, How to generate a MD5 hash or digest using Java, Spring and Apache commons code library.

What is difference between SQL, T-SQL and PL/SQL?

Today, we are going to see another common and interesting SQL interview question, what is the difference between SQL, T-SQL and PL/SQL? It is also one of the most common doubt among SQL beginners. It's common for programmers to think that why there are many types of SQL languages, why not just single SQL across DB? etc. Well, let's first understand the difference between SQL, T-SQL and PL/SQL and then we will understand the need of these dialects. SQL is standard for querying, inserting and modifying data in relational database. It is categorized into DDL and DML and powerful enough to create a database objects e.g. table, view, stored procedure and can perform CRUD operation (SELECT, INSERT, UPDATE, and DELETE) query.

Sunday, March 19, 2017

5 ways to Convert Java 8 Stream to List - Example, Tutorial

One of the common problem while working with Stream API in Java 8 is how to convert a Stream to List in Java because there is no toList() method present in Stream class. When you are processing a List using Stream's map and filter method, you ideally want your result in some collection so that you can pass it to other part of program. Though java.util.stream.Stream class has toArray() method to convert Stream to Array, but  there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion method between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.io.File, they provided a toPath() method to File class. Similarly they could have provided convenient methods like toList(), toSet() into Stream class, but unfortunately they have not done that. Anyway, It seems they did thought about this and provided a class called Collector to collect the result of stream operations into different container or Collection classes. Here you will find methods like toList(), which can be used to convert Java 8 Stream to List. You can also use any List implementation class e.g. ArrayList or LinkedList to get contents of that Stream. I would have preferred having those method at-least the common ones directly into Stream but nevertheless there is something you can use to convert a Java 8 Stream to List. BTW, my research to this task also reveals several other way to achieve the same result, which I have summarized in this tutorial. If would suggest to prefer standard way, which is by using Stream.collect() and Collectors class, but its good to know other ways, just in case if you need.

2 Examples of Streams with Collections in Java 8

Finally Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting feature. Though Lambda expression is the most talked item of coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API were not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allow you to process elements of Java Collections in parallel. Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of orders, you can filter buy orders with sell orders, filter orders based upon there quantity and price and so on.

Difference between First and Second Level Cache in Hibernate

If you have used Hibernate in past then you know that one of the strongest points of Hibernate framework is caching, which can drastically improve the performance of Java application's persistence layer if configured and used correctly. Hibernate provides caching at many levels e.g. first level cache at Session level, second level cache at the SessionFactory level, and query cache to cache frequently executed SQL queries. The first level cache minimizes database access for the same object. For example, if you call the get() method to access Employee object with id = 1 from one session, it will go the database and load the object into memory, but it will also cache the object in the first level cache.

Saturday, March 18, 2017

How to enclose a list of values into single quotes for SQL query - Use Microsoft Excel

Many times you get a list of values which you want to check in the database to confirm if they exist in your tables or to get more information bout them. For example, you got a list of 100 stocks and you want to check their last day closing prices in the database. The problem arises when values to be searched are Strings e.g. VARCHAR or CHAR because VARCHAR values need to enclosed in the single quotes in most of the database e.g. SQL Server, Oracle or MySQL. If number of values are less than 5 then it make sense to add single quotes around them and separate them by comma manually so that you can use then on IN clause of your SQL query, but if it's more than 5 e.g. 50 or 100 then manually enclosing them into single quotes will take a lot of time and most importantly programmers are not supposed to do such silly stuff manually.

Can You Overload or Override Static methods in Java

Can static method be overridden in Java, or can you override and overload static method in Java, is a common Java interview question, mostly asked to 2 years experienced Java programmers. Answer is, No, you can not override static method in Java, though you can declare method with same signature in sub class. It won't be overridden in exact sense, instead that is called method hiding. But at same time, you can overload static methods in Java, there is nothing wrong declaring static methods with same name, but different arguments. Some time interviewer also ask, Why you can not override static methods in Java? Answer of this question lies on time of resolution. As I said in difference between static and dynamic binding , static method are bonded during compile time using Type of reference variable, and not Object. If you have using IDE like Netbeans and Eclipse, and If you try to access static methods using an object, you will see warnings. As per Java coding convention, static methods should be accessed by class name rather than object. In short Static method can be overloaded, but can not be overridden in Java. If you declare,  another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself. This is known as method hiding in Java.

Friday, March 17, 2017

Java Synchronization Tutorial : What, How and Why?

Multithreading and synchronization are a very important topic for any Java programmer. Good knowledge of multithreading, synchronization, and thread-safety can put you in front of other developers, at the same time, it's not easy to master this concept. In fact writing correct concurrent code is one of the hardest things, even in Java, which has several inbuilt synchronization utilities. In this Java synchronization tutorial we will learn what is meaning of Synchronization in Java, Why do we need Synchronization in Java, What is java synchronized keyword, examples of using Java synchronized method and blocks, What can happen in multithreading code in absence of synchronized constructs, tips to avoid mistakes, while locking critical section in Java and some of important points about synchronization in Java.

How to Check if a Number is Binary in Java - Programming Problem

Today we will take a look at another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example, 1010 is a binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here.

Thursday, March 16, 2017

What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Difference between Daemon and Non Daemon(User Threads)  is also an interesting multi-threading interview question, which asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM. In this java thread tutorial we will see example of Daemon thread in Java and some more differences between Daemon and non daemon threads.

How to get ServletContext in Servlet, JSP, Action class and Controller.

How to get ServletContext in Servlet, jsp, spring controller or struts action class is common need of any Java web developer. As ServletContext is an application wide object and used to store variables in global scope, getting a reference of ServletContext is pretty important. Every web application can have only one ServletContext though they can have multiple ServletConfig objects. In this article we will see :

How to get Servlet Context inside Spring MVC Controller?
How to find  Servlet Context inside Struts Action class?
How to get Servlet Context inside JSP File?
How to find Servlet Context inside HttpServlet Class?

How to Convert an Array to Comma Separated String in Java

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending comma. You just need Java 1.5 for that, even if you are not running on Java 5, you can use StringBuffer in place of StringBuilder. The joining of String has got even easier in JDK 8, where you have got the join() method right in the String class itself. The join() method takes a delimiter and a source, which can be array or collection and returns a String where each element is joined by a delimiter. If you want to create a CSV string, just pass comma as a delimiter. Btw, these two methods are not the only way to create a comma separated String from an array, you can also use Apache Commons or Spring framework's utility class to do the same.

Wednesday, March 15, 2017

Top 15 Data Structures and Algorithm Interview Questions for Java Programmer - Answers

Data structures and algorithm questions are an important part of any programming job interview, be it a Java interview, C++ interview or any other programming language. Since data structures are core programming concept, it's mandatory for all programmers, to know basic data structures like stack, linked list, queue, array, tree, and graph. Though tree and graph are on the tougher side, I still see programmers get familiar will all these. Any list of programming job interview questions is incomplete without questions from data structures and algorithms. Similarly, while going on questions from data structure you may get some programming exercise as well e.g. swapping numbers without temp variable.

Why character array is better than String for Storing password in Java

Why character array is better than String for storing password in Java was recent question asked to one of my friend in a java interview. he was interviewing for a Technical lead position and has over 6 years of experience.Both Character array and String can be used to store text data but choosing one over other is difficult question if you haven't faced the situation already. But as my friend said any question related to String must have a clue on special property of Strings like immutability and he used that to convince interviewer. here we will explore some reasons on why should you used char[] for storing password than String.

character array over string storing password javaThis article is in continuation of my earlier interview question post on String e.g. Why String is immutable in Java or How Substring can cause memory leak in Java, if you haven't read those you may find them interesting.Here are few reasons which makes sense to believe that character array is better choice for storing password in Java than String: