Friday, March 31, 2017

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementations of the 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.

Thursday, March 30, 2017

What is Effectively Final variable of Java 8

Apart from the 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 the 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.

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

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 the "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 the persistence layer in Java and JEE application from a 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.

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

Looping ArrayList in Java or Iteration over ArrayList is very similar to a 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 the 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 the index and backed by Array.

What is Assertion in Java - Java Assertion Tutorial

Java Assertion or assert keyword in Java is a 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.

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

Monday, March 27, 2017

Parsing Large JSON Files using Jackson Streaming API Example

In the 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 frameworks and provides three main models to parse and process JSON data including Streaming API, data binding, and tree model. Out of these three, Streaming works at the lowest level and can be used to parse huge JSON response up to even gigabytes 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.

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

Difference between Stack and Queue Data Structure in Java

Stack and Queue are two of the 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 that 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.

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 sound like that, because all you need to do is create an array of the same size, iterate through the original array from end to start and populate your new array. Boom!!, you have got an array that 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.

Saturday, March 25, 2017

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

WeakReference and SoftReference were added into Java API for a long time but not every Java programmer is familiar with it. This means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in the 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 programmers know that this eligibility is decided based upon which kind of references are pointing to that object. This is also the main difference between WeakReference and SoftReference in Java.

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

Friday, March 24, 2017

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

Why to do one call start method of the thread if start() calls run() in turn" or "What is the 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, the first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and then calling start() method on the 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 it been asked in Java Interview.

Difference between Wait and Sleep, Yield in Java

The difference between wait and sleep or the difference between sleep and yield in Java is one of the popular core Java interview questions and asked on multi-threading interviews. Out of three methods that 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 the former is used for inter-thread communication while later is used to introduced to pause the current thread for a short duration.

Top 10 Servlet Interview Question Answers - J2EE

This time its servlet interview questions, I was thinking about what to pick for my interview series and then I thought about J2EE and Servlet is my favorite in that space. Servlet is an important part of any J2EE development and serves as a 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 a common programming question asked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers start 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 that is used to store elements in LIFO(Last In First Out) order and available in Java API as java.util.Stack.

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

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 the state of DateFormat class and should be synchronized externally in order to avoid any issue. here are a 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 the size of a 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 sound difficult to you because you need to remember UNIX commands for file and directory size. This is a common complaint from windows users 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.

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 words, 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 algorithms e.g. Mark and Sweep. There are different kinds of garbage collectors available in Java to collect different areas of heap memory e.g. you have serial, parallel, and concurrent garbage collectors 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 think that JavaScript is part of the Java platform, which is not true. In truth, JavaScript has nothing to do with Java, the only common thing between them is the 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 the father of Java. While in today's world calling JavaScript just a client-side scripting language would not be good, as it's 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.

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 interviews. volatile and transient are two completely different keywords from different areas of Java programming language. the transient keyword is used during serialization of Java object while volatile is related to the visibility of variables modified by multiple threads during concurrent programming. The only similarity between volatile and transient is that they are less used or uncommon keywords and not as popular as public, static, or final.

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 of Unix and it offers lots of tools and commands 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. 

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 is an anagram of each other, is another good coding question asked at fresher level Java Interviews. This question is on a similar level of finding the middle element of LinkedList in one pass and swapping two numbers without using temp variable. By the way, two String is called anagram, if they contains the same characters but on different order e.g. army and mary, stop and pots, etc. Anagrams are actually a mix-up of characters in String. If you are familiar with String API, i.e. java.lang.String then you can easily solve this problem.

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 a 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 purposes 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.

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 doubts 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 for these dialects. SQL is standard for querying, inserting, and modifying data in a 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 problems 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 parts of the 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.

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 features. Though Lambda expression is the most talked item of the coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API was not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allows you to process elements of Java Collections in parallel. Java is inheritably sequential and there are no direct means to introduce parallel processing at the library level, stream API is going to fill that gap. By using this, you can filter elements of collection on a 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 the 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 a static method be overridden in Java, or can you override and overload static method in Java, is a common Java interview questions mostly asked to 2 years experienced Java programmers. The answer is, No, you can not override static method in Java, though you can declare a method with the same signature in a subclass. It won't be overridden in the exact sense, instead, that is called method hiding. But at the same time, you can overload static methods in Java, there is nothing wrong declaring static methods with the same name, but different arguments. Some time interviewer also ask, Why you can not override static methods in Java? The answer to this question lies in the time of resolution.

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 the 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 the 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 is those thread that runs in the background and mostly created by JVM for performing background tasks like Garbage collection and other housekeeping tasks. The 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.

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 to need of any Java web developer. As ServletContext is an application-wide object and used to store variables in the 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.

Wednesday, March 15, 2017

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

Why character array is better than String for storing a password in Java was a recent question asked to one of my friends 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 a 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 a special property of Strings like immutability and he used that to convince the interviewer. here we will explore some reasons why should you use char[] for storing password than String.

Tuesday, March 14, 2017

JDBC - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Solution

"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"  is a frequent Exception Java programmer face while writing JDBC connectivity code for MySQL, especially if you are trying to establish a JDBC connection to MySQL database first time. we have touched base on ClassNotFoundException in MySQL on our earlier articles on how to resolve ClassNotFoundException in Java and here we will see in detail what causes "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver" and how to fix com.mysql.jdbc.Driver error in Java.

Monday, March 13, 2017

How to find Largest Prime Factor of a Number in Java - Programming Kata

One of the common programming kata to learn coding is to write a program to find the largest prime factor of a number. Like any other programming problem, you need to build the logic to solve this problem. Before solving the problem, let's revise the concept of number theory. Prime factors of a positive integer are the prime numbers that divide the number exactly i.e. without any remainder, and prime factorization is the process of finding all prime numbers when multiplied together make original number.

Mixing static and non static synchronized method - Java mistake 2

Using a static and non-static synchronized method for protecting shared resources is another Java mistake we are going to discuss in this part of our series “learning from mistakes in Java”. In last article, we have seen why double and float should not be used for monetary calculation, In this tutorial, we will find out why using static and non-static synchronized methods together for protecting the same shared resource is not advisable.  I have seen some times Java programmer mix static synchronized method and instance synchronized method to protect the same shared resource.

Why use Underscore in Numbers from Java SE 7 - Underscore in Numeric Literals

JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One such feature is the introduction of underscores in numeric literals. From Java 7 onwards you can write a long digit e.g. 10000000000 to a more readable 10_000_000_000 in your Java source code. One of the most important reasons for using an underscore in numeric literal is avoiding subtle mistakes that are hard to figure out by looking at code. It's hard to notice a missing zero or extra zero between 10000000000 and 1000000000, than 10_000_000_000 and 1_000_000_000.

What is Method References in Java 8? An Example

Lambda expression allows you to reduce code compared to an anonymous class to pass behaviors to methods, method reference goes one step further. It reduces code written in a lambda expression to make it even more readable and concise. You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

Difference between Struts 1 and Struts 2 Web Development Framework

I had worked previously on Struts 1 but never touched Struts 2, especially since Spring MVC was there to take the leading role. Recently one of my friends ask me to help with Struts2, which leads me to look on the Struts2 framework from start. First thing I wanted to find out differences between Struts 1 and Struts 2 framework, because in my experience, if you have worked in the previous version looking differences between two versions of Struts can quickly help to find, what changes and What are the new features, concepts and improvement is offered by Struts 2. Also the difference between Struts 1 and Struts 2 is a good candidate to include in my list of Struts interview questions for quick revision.

Sunday, March 12, 2017

10 Hibernate Interview Questions and Answers for Java Developers

Hibernate Interview Questions are asked on Java J2EE Interviews, mostly for web-based enterprise application development role. Success and acceptability of Hibernate framework on Java world have made it one of the most popular Object Relational Mapping (ORM) solution in the Java technology stack. Hibernate frees you from database-specific coding and allows you to focus more on utilizing powerful object-oriented design principles to implement core business logic. By using Hibernate you can switch between database rather easily and also take advantage of out of box caching facilities provided by Hibernate, in terms of second-level cache and query cache.

How to delete a directory with files in Java - Example

Deleting an empty directory is easy in Java, just use the delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non-empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and subdirectories inside this folder. This may seem cumbersome, but unfortunately, there is no method that can delete a directory with files in Java, not even on Java 7 Files and Paths class.

Bitwise and BitShift Operators in Java - AND, OR, XOR, Signed Left and Right shift Operator Examples

Bitwise and Bit Shift Operators in Java are a powerful set of operators that allows you to manipulate bits on integral types like int, long, short, bytes, and boolean data types in Java. Bitwise and Bit shift operator is among the fastest operator in Java but still, many Java programmers don't familiar with bitwise and bitshift operations, especially those who don't come from C programming backgrounds. If you have already learned C or C++ before starting with Java then understanding bitwise and bitshift operators are quite easy in Java, because its similar to the bitwise operation in C.

Saturday, March 11, 2017

How to Clone Collection in Java - Deep copy of ArrayList and HashSet

Programmers often mistook copy constructors provided by various collection classes, as a means to clone Collection e.g. List, Set, ArrayList, HashSet, or any other implementation. What is worth remembering is that copy constructor of Collection in Java only provides shallow copy and not a deep copy, which means objects stored in both original List and cloned List will be same and point to the same memory location in Java heap. One thing, which adds into this misconception is shallow copy of Collections with Immutable Objects. Since Immutable can't be changed, It's Ok even if two collections are pointing to same object. This is exactly the case of String contained in pool, update on one will not affect other.

How to Remove First and Last Character of String in Java - Example Tutorial

You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java. Alternatively, you can convert String to StringBuffer or StringBuilder and then use its remove() method to remove the first or last character. Both StringBuffer and StringBuilder provides a convenient deleteCharAt(int index) method which removes a character from the corresponding index. You can use this method to remove both first and last characters from String in Java.

Difference between Singleton Pattern vs Static Class in Java

Singleton pattern  vs  Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and  what are differences between Singleton pattern and static in Java. I

What is GET and POST method in HTTP and HTTPS Protocol

GET and POST method in HTTP and HTTPS are two most popular methods used to transfer data from client to server using  HTTP(HyperText Transfer Protocol)  protocol. Both GET and POST can be used to send requests and receive response but there are significant differences between them. The difference between GET and POST in HTTP or HTTPS is also a popular interview question in JSP and any web programming interview. Since HTML is independent of any web server technology like Java, ASP or PHP and HTTP is core protocol in space of the internet, the importance of a clear understanding of GET and POST method can not be ignored.

Friday, March 10, 2017

What is Static and Dynamic binding in Java with Example

Static and dynamic binding in Java is two important concepts that Java programmer should be aware of. this is directly related to the execution of code. If you have more than one method of the same name (method overriding) or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of there reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with the binding operation, its process used to a link which method or variable to be called as a result of there reference in code.

10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like the main method in java. finalize() is called before Garbage collector reclaims the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing the connection if open etc. The main issue with finalize() method in Java is it's not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example, an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called it's not guaranteed it will be immediately collected.

Thursday, March 9, 2017

What is Encapsulation in Java and OOPS with Example

Encapsulation in Java or object-oriented programming language is a concept that enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having the least impact or no impact on other parts of a program due to change in protected code. Encapsulation in Java is visible at different places and Java language itself provides many constructs to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifiers like protected or the public.

10 example of chmod command in UNIX Linux

chmod command in UNIX or Linux is used to change file or directory permissions. This is one of many UNIX basic commands which a UNIX or Linux user must be familiar with. In this UNIX command tutorial we will see how to change file permissions using the chmod command, what are file permissions in UNIX, how to change permissions of directory and sub-directory using UNIX chmod command and finally how to create executable files in UNIX using the chmod command. Before going directly into examples of chmod command let's spend a few minutes on understanding file permissions in UNIX and why do we need to change file permissions etc.

Java 8 Date Time - 20 Examples of LocalDate, LocalTime, LocalDateTime

Along with lambda expressions, streams, and several minor goodies, Java 8 has also introduced brand new Date and Time API, and in this tutorial, we will learn how to use Java 8 Date Time API with simple how-to-do task examples. Java's handling of Date, Calendar, and Time is long been criticized by the community, which is not helped by Java's decision of making java.util.Date mutable and SimpleDateFormat not thread-safe. It seems, Java has realized a need for better Date and time support, which is good for a community which already used to of Joda Date and Time API.

Top 50 Java Thread Interview Questions Answers for Experienced

You go to any Java interview, senior or junior, experience or freshers,  you are bound to see a couple of questions from the thread, concurrency, and multi-threading. In fact, this built-in concurrency support is one of the strongest points of Java programming language and helped it to gain popularity among the enterprise world and programmers equally. Most of the lucrative Java developer position demands excellent core Java multi-threading skills and experience in developing, debugging, and tuning high-performance low latency concurrent Java applications. This is the reason, it is one of the most sought after skills on Java interviews. The multithreading and concurrency are also hard to master the concept and only good developers with solid experience can effectively deal with concurrency issues.

Wednesday, March 8, 2017

How to Increase Console Buffer Size in Eclipse IDE - Output and Debug Console

By default Eclipse, IDE has a limit on console output, also known as console buffer size. This means, your Eclipse console will overfill quickly if you are running a Java server program, which usually does a lot of logging. Once this happens, you start losing logs. whenever new logs appear, an equal number of oldest logs are truncated. Thankfully there is a way to increase output capacity in Eclipse IDE. I discovered this tip, on my search of Eclipse productivity tips e.g. Eclipse shortcuts and settings to organize import. You can increase the console buffer size, which is specified in characters by using Eclipse preferences. Eclipse Indigo has default console buffer size as 250000 characters.

How to Implement Stack in Java Using Array and Generics - Example

The stack is one of the popular data structure which supports LIFO (Last In First OUT) operation. Due to the LIFO advantage, you can use a stack data structure to convert a recursive algorithm to an iterative one. The stack data structure is very easy to implement using an array or linked list, but you don't have to implement it on your own because Java already provides a Stack implementation in java.util.Stack class. This class is a subclass of the Vector class and you should use it whenever you need Stack for your production code, there is no point in inventing the wheel again when the focus is on developing your application.

Top 10 EJB Interview Question and Answer asked in Java J2EE Interviews

10 EJB Interview Questions and Answer from my collection of interview questions. I have been sharing interview questions on various topics like Singleton interview question, serialization interview question, and most recently Spring interview questions. No doubt these questions are very important from performing better in J2EE and EJB interviews but also they open a new path for learning as you may find some concept new even while revising your knowledge in EJB. EJB interviews have always been tough because its difficult to find people who have hands-on experience on Enterprise Java Beans (EJB) and most of the guys either have worked only on sample project and not aware of critical functionalities like distributed transaction management, container-managed persistence and various other services which EJB provides.

Tuesday, March 7, 2017

java.lang.UnsatisfiedLinkError: no dll in java.library.path - Cause and Solution

"Exception in thread "main" java.lang.UnsatisfiedLinkError: no dll in java.library.path" is one of the frustrating errors you will get if your application is using native libraries e.g. .DLL in Windows or .SO files in Linux. Java loads native libraries at runtime from either PATH environment variable or location specified by java.library.path system property depending upon whether your Java program is using System.load() or java.lang.System.loadLibarray() method to load native libraries. If Java doesn't find them due to any reason it throws "java.lang.UnsatisfiedLinkError: no dll in java.library.path". Some of the most common UnsatisfiedLinkError is "java.lang.UnsatisfiedLinkError: no ocijdbc10.dll in java.library.path" and "java.lang.UnsatisfiedLinkError: no ocijdbc11.dll in java.library.path", which comes when you try to connect to Oracle 10g or 11g database from Java program using OCI JDBC driver.

ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock

ReentrantLock in Java is added on java.util.concurrent package in Java 1.5 along with other concurrent utilities like CountDownLatch, Executors, and CyclicBarrier. ReentrantLock is one of the most useful additions in Java concurrency package and several of concurrent collection classes from java.util.concurrent package is written using ReentrantLock, including ConcurrentHashMap, see How ConcurrentHashMap works in Java for more details. Two key feature of ReentrantLock, which provides more control on lock acquisition is trying to get a lock with the ability to interrupt, and a timeout on waiting for a lock, these are key for writing responsive and scalable systems in Java.

Monday, March 6, 2017

Why we use Threads in Java?

In one word, we use Threads to make Java application faster by doing multiple things at the same time. In technical terms, Thread helps you to achieve parallelism in Java programs. Since CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores, which means your costly hardware will remain idle for most of the time. By using multiple threads, you can take full advantage of multiple cores by serving more clients and serving them faster. Since, in today's fast-paced world, response time matters a lot and that's why you have multi-core CPUs, but if your application doesn't make full use of all resources then there is no point adding them, multi-threading is one way to exploiting huge computing power of CPU in Java application.