10 Example of Lambda Expressions and Streams in Java 8

Java 8 release is just a couple of weeks away, scheduled on 18th March 2014, and there is a lot of buzz and excitement about this path-breaking release in Java community. One feature, which is synonymous with this release is lambda expressions, which will provide the ability to pass behaviors to methods. Prior to Java 8, if you want to pass behavior to a method, then your only option was Anonymous class, which will take 6 lines of code and the most important line, which defines the behavior is lost in between. Lambda expression replaces anonymous classes and removes all boilerplate, enabling you to write code in a functional style, which is sometimes more readable and expression.

String Deduplication of G1 Garbage collector to Save Memory from Duplicate String in Java 8

You might not be aware that Java 8 update 20 has introduced a new feature called "String deduplication" which can be used to save memory from duplicate String objects in Java application, which can improve the performance of your Java application and prevent java.lang.OutOfMemoryError if your application makes heavy use of String. If you have profiled a Java application to check which object is taking the bulk of memory, you will often find char[] object at the top of the list, which is nothing but internal character array used by String object. Some of the tools and profilers might show this as java.lang.String[] as well e.g. Java Flight Recorder, but they are essentially pointing to the same problem i.e. a major portion of memory is occupied with String objects.

Overriding equals() and hashCode() method in Java and Hibernate

Override equals and hashCode in Java
Equals and hashCode in Java are two fundamental methods which are declared in Object class and part of core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object. equals and hashCode have used extensively in Java core library like they are used while inserting and retrieving Object in HashMap, see how to get method of HashMap works in Java for the full story, equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects.

5 Differences between COALESCE and ISNULL in SQL Server

What is the difference between COALESCE and ISNULL is one of the frequently asked Microsoft SQL Server interview questions. Recently, one of my readers asked the same question to me, he got confused between these two because both are used to replace NULL values to default values in SQL Server. I'll try to answer this question here with a little bit of insight about when to use ISNULL and COALESCE in SQL Server. Even though both ISNULL and COALESCE is used to provide default values for NULLs there are some key differences between them like ISNULL() is a T-SQL or Microsoft SQL Server-specific function or operator, and datatype and length of the result depends upon a parameter, but COALESCE is a SQL ANSI standard, it can accept more than one parameter and unlike ISNULL, the result doesn't directly depend upon a parameter, it is always the type and length of the value returned.

5 Difference between Constructor and Static Factory method in Java- Pros and Cons

The common way to create objects in Java is by using public constructors. A class provides a public constructor e.g. java.lang.String so anyone can create an instance of String class to use in their application, but, there is another technique that can be used to create objects in Java and every experienced Java programmer should know about it. A class can provide a public static factory method that can return an instance of the class e.g. HashMap.newInstance(). The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.

10 points about volatile modifier or field in Java

The volatile modifier has always been an interesting and tricky topic for many Java programmers. I still feel that it's one of the most underutilized modifiers in Java, which can do a lot of good if understood and applied correctly, after all, it provides a lock-free way to achieve synchronization in Java. If a field is shared between multiple threads and one of them changes its value i.e. one thread reads from the field which is written by other threads, then, by using a volatile modifier, you can synchronize access to this field. The volatile modifier in Java provides visibility and ordering guarantee without any locking.

Difference between Comparison (QuickSort) and Non-Comparison (Counting Sort) based Sorting Algorithms?

For many of you, this might be a surprise that how you can sort or arrange items without comparing with each other, but it's possible. There are some sorting algorithms that perform sorting without comparing the elements rather by making a certain assumptions about the data they are going to sort. The process is known as non-comparison sorting and algorithms are known as the non-comparison based sorting algorithms. No comparison sorting includes Counting sort which sorts using key-value, Radix sort, which examines individual bits of keys, and Bucket Sort which examines bits of keys. These are also known as Liner sorting algorithms because they sort in O(n) time. They make certain assumptions about data hence they don't need to go through a comparison decision tree.

How to set Java Path and Classpath in Windows 8 and Windows 7 - Tutorial

So, you just bought a new PC or Laptop with Windows 8 operating system, and wondering how to set PATH and Classpath on Windows 8; Or, you might have just upgraded your Windows 7 laptop to the professional edition of Windows 8 and looking to set JDK Path to compile Java programs. Not to worry, this is the second step for anyone who wants to learn Java programming. Of course, the first step is to install JDK.  In this Java tutorial, we will see step by step guide to set Java PATH and CLASSPATH in the Windows 8 operating system. By the way, if you are learning Java in Windows 7 operating system, You should still be able to set Java path and classpath in Windows 7 by following steps given here, because navigation steps for modifying environment variables on Windows 7 and Windows 8 are almost same.

Why Static Code Analysis is Important?

From last few years, Software code quality and security has went from being a “nice to have” to a necessity, and many organizations, including investment banks are making it mandatory to pass static code analysis test, penetration testing and security testing before you deploy your code in production. Static analysis tools like findbugs and fortify are getting popular every passing day and more and more companies are making fortify scan mandatory for all new development.  For those unaware of what static code analysis is, static code analysis is about analysing your source code without executing them to find potential vulnerabilities, bugs and security threats.

How to remove all special characters from String in Java

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

17 Examples of Calendar and Date in Java

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

Java Comparable Example for Natural Order Sorting

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

How to Read/Write from RandomAccessFile in Java

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

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

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

How to Filter Collections in Java 8 with Streams and Predicates

Java 8 provides excellent features to support the filtering of elements in Java Collections. Prior to Java 8, the only better way to filter elements is by using a foreach loop or iterating over Collection using the Iterator and selecting the required object, leaving out rest. Though that approach work, it was very difficult to run them in parallel and take advantage of multiple CPU available in modern-day servers. Java 8 provides Streams, which not only makes it easy to run any operation parallel but also support lazy loading and lazy evaluation, which means as soon as filtering condition is satisfied, it stooped doing work, doesn't matter how many object collection contains.

Difference between JAX-RS, Restlet, Jersey, RESTEasy, and Apache CXF Frameworks

The JAX-RS is a Java specification request (JSR 311 & JSR 339) that standardizes the development and deployment of RESTful web services using Java and JEE technologies. It provides API in Java Programming language to create web services according to the REST (Representational State Transfer) architectural pattern. Both Restlet and Jersey are two of the most popular implementation of JAX-RS used for developing RESTful web services in Java ecosystem but there is a couple of other implementation also exist e.g. Apache Wink, Apache CXF, and JBoss RESTEasy.

How HashMap works in Java

HashMap in Java works on hashing principles. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method. When we call put method, the hashcode() method of the key object is called so that the hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table.
HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object.

StringTokenizer Example in Java with Multiple Delimiters

StringTokenizer is a legacy class for splitting strings into tokens. In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting string into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space. It's inferior to split() as it doesn't support regular expression, also it is not very efficient. Since it’s an obsolete class, don't expect any performance improvement either. On the hand split() has gone some major performance boost on Java 7, see here to learn more about splitting String with regular expression.

5 ways to check if String is empty in Java - examples

String in Java is considered empty if it's not null and its length is zero. By the way, before checking length you should verify that String is not null because calling length() method on null String will result in java.lang.NullPointerException. Empty String is represented by String literal “”. The definition of empty String may be extended to those String as well which only contains white space but its a specific requirement and in general String with white space is not considered as empty String in Java. Since String is one of the most frequently used classes and commonly used in method arguments, we often need to check if String is empty or not. Thankfully there are multiple ways to find if String is empty in Java or not.