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.

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.

How to Reverse Array in Java - Int 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.

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.

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

10 Famous Laws of Computer Programming and Software Enginnering World

Like any other field, Software and Programming world too has some interesting and famous rules, principles and laws, which programmers, developers, managers and architects use often in conversations, meetings and chats. These laws are either rules, principles, or famous words from great personalities of computer programming world. At the same time these laws are interesting, funny, worth knowing, and few of them are just amazing to read. I have sharing things which is worth knowing and useful for not only Java programmer but also developers from other programming language e.g. we have seen 10 Object oriented design principles, which is not only useful for Java guys but also with any OOPS programmer. In this article, I am going to share my collection of 10 famous software and computer programming laws, I am sure you would have few more to add into this list. Please share a computer programming rules, or a thought of wisdom, which is worth knowing among software professional.

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.

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 tough 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. The linked list and array are favorite topics in any data structure interview, questions like reversing linked list, traversing linked list or deleting nodes from linked list, which involves algorithm and data structures are quite common. 

Difference between Struts 1 and Struts 2 framework

I had work previously on Struts 1 but never touched Struts 2, specially since Spring MVC was there to take the leading role. Recently one of my friend ask me to help with Struts2, which leads me to look on 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 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 difference between Struts 1 and Struts 2 is a good candidate to include in my list of Struts interview question for quick revision. To my surprise, Struts 2 seems to be completely different than Struts 1 framework, because some of the most familiar stuff like ActionForm, struts-config.xml, and Action classes are changed in Struts 2 framework. Struts 2 has also done good job on removing direct dependency of Action classes on Servlet API e.g. HttpServletRequest and HttpServletResponse, which makes testing easy by using Dependency Injection concept. In this article, we will some important differences between Struts 1 and Struts 2 framework.

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

Bitwise and Bit Shift operators in Java are powerful set of operators which allows you to manipulate bits on integral types like int, long, short, bytes and boolean data types in Java. Bitwise and Bit shift operator are among the fastest operator in Java but still many Java programmers doesn't familiar with bitwise and bitshift operations, especially those who doesn'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 bitwise operation in C. Some of the tricky programming interview questions e.g. checking if a number is power of two or swapping two numbers without temporary variable or, can be easily solved using bitwise operators. This Java programming tutorial is quick recap of different bitwise operator available in Java and how to use them. This tutorial also discusses bit shift operator, both signed and unsigned with example.

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. In order to answer these question, it’s important to remember fundamental difference between Singleton pattern and static class, former gives you an Object, while later just provide static methods. Since an object is always much more capable than a method, it can guide you when to use Singleton pattern vs static methods.

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

By default Eclipse IDE has limit on console output, also known as console buffer size. Which means, your Eclipse console will overfill quickly, if you are running a Java server program, which usually do lot of logging. Once this happen, you start losing logs. whenever new logs appear, 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 console buffer size, which is specified in characters by using Eclipse preferences. Eclipse Indigo has default console buffer size as 250000 characters. Eclipse also provides a check box Limit Console Output to put enforce limit on console output, In order to increase console output either you can unchecked this box or you can increase console buffer size. I usually unchecked, Limit Console Output to avoid guessing a good number for console buffer size.

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 addition 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 ability to interrupt, and a timeout on waiting for lock, these are key for writing responsive and scalable systems in Java. In short, ReentrantLock extends functionality of synchronized keyword in Java and open path for more controlled locking in Java. 

In this Java concurrency tutorial we will learn :
  • What is ReentrantLock in Java ?
  • Difference between ReentrantLock and synchronized keyword in Java?
  • Benefits of using Reentrant lock in Java?
  • Drawbacks of using Reentrant lock in concurrent program?
  • Code Example of ReentrantLock in Java?

How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like String, Integer and other wrapper classes. For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on code level, but its the decision to make, which class mutable or immutable which makes difference. I also suggest reading, Java Concurrency in Practice to learn more about concurrency benefit offered by Immutable object.

Steps to Create JUnit Test in Eclipse and Netbeans IDE

Writing JUnit tests for Java classes in Eclipse and Netbeans IDE are super easy, and I will show you with that later in this JUnit tutorial. Before that, let’s revise what is a unit test and why should you write them. A unit test is to test smaller unit of code, e.g. methods.  Writing a unit test to test individual unit of code is one of the best development practice and helps to find bug earlier in the development cycle. Though there is other unit testing framework available in Java e.g. TestNG, JUnit has its own place among Java developers. IMHO code review and unit testing are two most important practices for improving code quality and should always be followed during software development. Sad thing is that not every developer follows it; some programmer doesn't write unit test due to ignorance and others due to laziness. Anyway, it just starts which take time, once you start writing unit tests, you will automatically start enjoying it. I have seen Java developers testing their code with main() method, but now they prefer to test them with JUnit test cases.