One common requirement in Java application is to iterate through the elements of a collection. Prior to Java 8, the three most common ways to iterate through a collection are by using the while loop, for loop, and enhanced for loop. As the Java Collection interface extends Iterable, you can also use the hasNext() and next() methods of Iterable to iterate through collection elements.

Starting from Java 8, we have a new forEach method in Iterable to loop through elements in a collection – but in a different way.

In this post, I will discuss the  forEach method introduced in Java 8.

External vs Internal Iterators

Based on who controls iterations, Java Iterators can be classified into external and internal iterators.

External iterators are also known as active or explicit iterators. When using an external iterator, the client code performing the iteration controls the iteration. The client creates the iterator and instructs it when to advance to the next element. The client also checks whether or not all the element has been visited, and so on.

Enumerations, iterators, and enhanced for-loop are all examples of external iterators. Remember the old hasMoreElements() and nextElement() of Enumeration that you write to control iteration? Similarly, next() and hasNext() of Iterator?

The enhanced for loop introduced in Java 5 is another example of external iterator. An example of the enhanced for loop is this.

As evident from this code, the enhanced for loop shields developers from explicitly controlling looping via code. However, internally the next() and hasNext() methods get called, and therefor making it an external iterator.

Internal iterators are also known as passive, implicit or callback iterator. When you use an internal iterator, it is the iterator itself that controls the iteration. The client code essentially says to the iterator, “perform this operation on the elements in the collection.

Internal iterator has been introduced in Java 8 with the introduction of Lambda expression. The forEach method of this post covers is an internal iterator.

List Iteration using Java 8 forEach

The code to iterate through the elements of a list using forEach is this.

This code declaratively states what is meant to be done with the elements of the List. The internal iterator manages the iterations in the background.

To make the code clearer, the same iterateThroughList() method can be written using method reference like this.

You can test the code with this.

The output of the code in the IntelliJ console is this.
forEach List Iteration

Inside Java 8 forEach

In the example we just saw, we used lambda expressions. Let us dissect the forEach method and look what is happening inside.

The signature of the forEach method is this.

The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. The Consumer parameter of forEach is a functional interface with the accept(Object) method.

We can therefore rewrite the previous iterateThroughList() method like this.

This code uses an anonymous class to instantiate a Consumer implementation. The Consumer instance is then passed as an argument to forEach. This code will produce the same result as the lambda expression we wrote.

Map Iteration using Java 8 forEach

Map in Java does not extends Iterable and therefore does not inherit Iterable’s forEach. However, Map itself has its own forEach method that you can use to iterate through key-value pairs.

The following code uses a lambda expression to do so.

You can test the code, with this.

The output of the code in the IntelliJ console is this.
forEach Map Iteration

Stream Iteration using Java 8 forEach

With both the new forEach method and the Java 8 Stream API, you can create a stream of elements in a collection and then pipeline the stream to a forEach method for iteration.

The code to iterate through a stream of elements in a List is this.

The code to test this method is this.

The output of the code is this.

For parallel streams, the only difference is that you need to call the parallelStream() method instead of stream() on the List. Then iterate through the stream of elements using forEach, like this.

The code to test this method is this.

The output of the code is this.
forEach Parallel Stream Iteration

As you can notice, the order in which the list elements are processed is not the order in which the elements are stored in the list. However, when dealing with larger sets of data, parallel streams bring in considerable performance gain to your program.


The new forEach method of Java 8 brings in a more declarative approach to iteration. As a developer, you write code to specify the result rather than how to compute it.

This new declarative approach is more readable but also less error prone.

In addition, the forEach() method fits intuitively with the Stream API and particularly makes using parallel streams easy.

, , ,

When developing Spring Boot applications, you need to tell the Spring Framework where to look for Spring components. Using component scan is one method of asking Spring to detect Spring managed components. Spring needs the information to locate and register all the Spring components with the application context when the application starts.

Spring can auto scan, detect, and instantiate components from pre-defined project packages. Spring can auto scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository

In this post, I will discuss how Spring component scanning works.

Sample Application

Let us create a simple Spring Boot application to understand how component scanning works in Spring.

We will start by writing few components.

The @SpringBootApplication Annotation

Spring needs to know which packages to scan for annotated components in order to add them to the IoC container. In a Spring Boot project, we typically set the main application class with the @SpringBootApplication annotation. Under the hood, @SpringBootApplication is a composition of the @Configuration, @ComponentScan, and @EnableAutoConfiguration annotations. With this default setting, Spring Boot will auto scan for components in the current package (containing the @SpringBoot main class) and its sub packages.

To know more about these annotations go through my Spring Framework Annotations post.

Note: It is recommended that you locate your main application class in a root package above the component classes of the application.

The code to create the main class and access components is this.

The output of running the main class is this.
Output of class

As you can notice, all the classes in the sub packages of the main class BlogPostsApplication are auto scanned by Spring.

@ComponentScan – Identifying Base Packages

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

The basePackageClasses attribute is a type-safe alternative to basePackages. When you specify basePackageClasses, Spring will scan the package (and subpackages) of the classes you specify. 

A Java class annotated with @ComponentScan with the basePackageClassesattribute is this.

The output on running the main class is this.
Output of Class

The @ComponentScan annotation uses the basePackages attribute to specify three packages (and subpackages) that will be scanned by Spring. The annotation also uses the basePackageClasses attribute to declare the DemoBeanB1 class whose package Spring Boot should scan.

As demoBeanC is in a different package, Spring did not find it during component scanning.

Component Scanning Filters

You can configure component scanning by using different type filters that Spring provides.

By using filters, you can further narrow the set of candidate components from everything in basePackages to everything in the base packages that matches the given filter or filters.

Filters can be of two types: include and exclude filters. As their names suggest, include filters specify which types are eligible for component scanning, while exclude filters specify which types are not.

You can use the include and/or exclude filters with or without the default filter. To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

The code to disable the default filter is this.

In the preceding code, the value member defines the specific package to scan, while the useDefaultFilters member disables the default filter.

The output on running the main class is this.
Output of Class

As you can notice, the class DemoBeanA in the package demopackageA is unavailable when the useDefaultFilters element of the @ComponentScan annotation is set to false.

Component Scanning Filter Types

Spring provides the FilterType enumeration for the type filters that may be used in conjunction with @ComponentScan.

The available FilterType values are:

  • FilterType.ANNOTATION: Include or exclude those classes with a stereotype annotation
  • FilterType.ASPECTJ: Include or exclude classes using an AspectJ type pattern expression
  • FilterType.ASSIGNABLE_TYPE: Include or exclude classes that extend or implement this class or interface
  • FilterType.REGEX: Include or exclude classes using a regular expression
  • FilterType.CUSTOM: Include or exclude classes using a custom implementation of the org.springframework.core.type.TypeFilter interface

Include Filters

With include filters, you can include certain classes to be scanned by Spring. To include assignable type, use the includeFilters element of the @ComponentScan annotation with FilterType. ASSIGNABLE_TYPE. Using this filter, you can instruct Spring to scan for classes that extends or implements the class or interface you specify.

The code to use the includeFilters element of @ComponentScan is this.

The output on running the main class is this.
Output of Class

As shown in the preceding figure, Spring detected and used the demoBean3 component that extends demoBean2.

Include Filters using Regex

You can use regular expressions to filter out components to be scanned by Spring. Use the includeFiltersnested annotation @ComponentScan.Filter type FilterType.REGEXto set a pattern.

The code to use an exclude filter based on regular expression is this.

The output of the following code snippet is this.
Output of Class
As shown in the preceding figure, the classes whose names end with A, or 2 are detected by Spring.

Exclude Filters

The @ComponentScan annotation enables you to exclude those classes that you do not want to scan.

The code to use an exclude filter is this.

In this code, the nested annotation @ComponentScan.Filter is used to specify the filter type as FilterType.ASSIGNABLE_TYPE and the base class that should be excluded from scanning.

The output is this.
Output of using the FilterType.ASSIGNABLE_TYPE type

As you can see, the class DemoBeanB2 has been excluded from being scanned.


When using Spring Boot, most of the time the default auto scanning will work for your project. You only need to ensure that your @SpringBoot main class is at the base package of your package hierarchy. Spring Boot will automatically perform a component scan in the package of the Spring Boot main class and below.

One related annotation that I didn’t mention in this post is @EntityScan is more about JPA entity scanning rather than component scanning. The @EntityScan annotation, unlike @ComponentScan does not create beans. It only identifies which classes should be used by a specific persistence context.


While developing applications, we often need to generate random numbers. Java provides support to generate random numbers primarily through the java.lang.Math and java.util.Random classes.

In this post, I will discuss different ways to generate random numbers based on different types of requirements.

Random Numbers using the Math Class

Java provides the Math class in the java.util package to generate random numbers.

The Math class contains the static Math.random()method to generate random numbers of double type.
The random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. When you call Math.random(), under the hood, a java.util.Random pseudorandom-number generator object is created and used.

You can use the Math.random() method with or without passing parameters. If you provide parameters, the method produces random numbers within the given parameters.

The code to use the Math.random() method is this.

The getRandomNumber() method uses the Math.random() method to return a positive double value, that is greater than or equal to 0.0 and less than 1.0.

The output of running the code is this.

Random Numbers within a Given Range

For generating random numbers between a given a range, you need to specify the range. A standard expression for accomplishing this is:

Let us break this expression into steps:

    1. First, multiply the magnitude of the range of values you want to cover by the result that Math.random() produces.
      Math.random() * ( max - min )This returns a value in the range [0, max min] where max is excluded. For example, if you want [5,10] you need to cover 5 integer values. So you can use Math.random()*5. This would return a value in the range [0,5], where 5 is not included.
    2. Next, shift this range up to the range that you are targeting. You do this by adding the min value.

(Math.random() * ( max - min )) + min

But, this still does not include the maximum value.

    1. To get the max value included, you need to add 1 to your range parameter (max - min). This will return a random double within the specified range.

double x = (Math.random()*((max-min)+1))+min;

There are different ways of implementing the above expression. Let us look at a couple of them.

Random Double within a Given Range

By default, the Math.random() method returns a random number of the type double whenever it is called. The code to generate a random double value between a specified range is this.

You can call the preceding method from the main method by passing the arguments like this.

The output is this.

Random Integer within a Given Range

The code to generate a random integer value between a specified range is this.

The preceding getRandomIntegerBetweenRange() method produces a random integer between the given range. As Math.random() method generates random numbers of double type, you need to truncate the decimal part and cast it to int in order to get the integer random number. You can call this method from the main method by passing the arguments as follow:

The output is this.

Note: You can pass a range of negative values to generate a random negative number within the range.

Random Number Generation using the Random Class

You can use the java.util.Random class to generate random numbers of different types, such as int, float, double, long, and boolean.

To generate random numbers, first, create an instance of the Random class and then call one of the random value generator methods, such as nextInt(), nextDouble(), or nextLong().

The nextInt() method of Random accepts a bound integer and returns a random integer from 0 (inclusive) to the specified bound (exclusive).

The code to use the nextInt() method is this.

The code to use the nextInt() method to generate an integer within a range is this.

The nextFloat() and nextDouble() methods allow generating float and double values between 0.0 and 1.0.

The code to use both the methods is this.

New Random Number Generation Features in Java 8

Java 8 has introduced a new method ints() in the java.util.Random class. The ints() method returns an unlimited stream of pseudorandom int values. You can limit the random numbers between a specified range by providing the minimum and the maximum values.

The code to use the Random.ints() method to generate random integer values within a specified range is this.

The getRandomNumberInts() method generates a stream of random integers between the min (inclusive) and max (exclusive). As ints() method produces an IntStream, the code calls the findFirst() method that returns an OptionalInt object that describes the first element of this stream. The code then calls the getAsInt()method to return the int value in OptionalInt.

The code to use the Random.ints() method to generate a stream of specified random integer values is this.

The code to call the preceding method is this.

The output of the preceding code is this.

The code to use the Random.ints() method to generate a stream of a specified number of random integer values between a range is this.

The code to call the preceding method is this.

The output of the preceding code is this.

In addition to ints(), some other frequently used methods that Java 8 introduces to the Random class which can return a sequential stream of random numbers are:

      • LongStream longs()
      • DoubleStream doubles()


The java.util.Random class implements what is generally called a linear congruential generator (LCG). It is designed to be fast but does not meet requirements for real-time use. For example, use in unique session ID generation on a web server, scientific experiments, cryptography, or lotteries and sweepstakes where monetary stake is involved. For such scenarios, there are other alternatives, which I will cover in a later post.

For the impatient readers, you can have a look at the SecureRandom class and Xorshift random number generators.

Also, an interesting resource is, a true random number service that generates randomness via atmospheric noise.


If you are still using System.out to print debugging or diagnostic information in your application, it’s time to look for a more elegant and efficient solution in the form of a logging framework. Although there are lots of logging frameworks around for Java applications, Log4J is one of the most widely adopted one because of the simplicity and flexibility it provides.

Note: The Log4J version 1 was first released on 1999 and quickly became the most used logging framework ever. But due to some inherent architectural flaws, Apache announced End of Life of Log4j version 1 on August 2015 and encouraged users to upgrade to Log4j 2 – A framework that is far more reliable, faster, and much easier to develop and maintain. Log4J 2 is almost a compete changed framework with a different API and support for different configuration files having different syntax. Therefore, from here onward, I will refer the framework as Log4J 2

Log4J 2 is an open source logging package distributed under the Apache Software License. The advantages it provides over System.out is monumental. Log4J 2 allows you to define different levels of importance, such as ERROR, WARN, INFO, and DEBUG for log messages. Log4J 2 also allows you to define one or more destinations, such as console, file, database, and SMTP server to send log messages. And the great thing is that using Log4J 2, you can perform logging asynchronously.

Additionally, Log4J 2 allows you to control logging on a class-by-class basis. For example, one class of an application can redirect logs to the console while another to a file. By contrast, a programmer can only control System.out at the granularity of the entire application. If a programmer redirects System.out, the redirect happens for the whole application.

Another important feature of Log4J 2 is that it’s easy to enable or disable only some type of log message. For example, you can configure Log4J 2 to disable every debug message in production.

So how Log4J 2 do all this? It’s through the loggers, appenders, and layouts  – the components of the Log4J 2 API. These components work together to provide developer full control on how messages are logged, formatted, and where they are reported.


Loggers are the key objects in Log4J 2 that are responsible for capturing logging information. Loggers are stored in a namespace hierarchy and a root logger, an implementation of the Logger interface, sits at the top of the hierarchy. Logger names are case-sensitive and they follow the hierarchical naming rule.

You can retrieve the root logger by calling the LoggerManager.getRootLogger() method. For all other loggers, you can instantiate and retrieve them by calling LoggerManager.getLogger(String loggerName) passing the name of the desired logger as a parameter. Although, you can specify any name for a logger, its recommend to name the logger with the fully qualified name of the class. In a large application, with thousands of log statements, it is easy to identify the origin of a log message as the log output bears the name of the generating logger. Since it is a common practice to name loggers after their owning class, Log4J 2 provides the overloaded convenience method LogManager.getLogger(). This method, by default, uses the fully qualified class name of the owning class.

Loggers can be assigned levels in the following order.

Log Levels

As you can see in the figure above, TRACE is the lowest level and the level moves up through DEBUG, INFO, WARN, ERROR, till FATAL – the highest level. What this means is that if you set the logger level to ERROR then only the ERROR and FATAL level log messages will be displayed and the rest will be ignored.

In addition to the levels I mentioned, there are two special levels:

  • ALL: Turns on all levels.
  • OFF: Turns off all levels.

While developing in your local machine, it is common to set the log level to DEBUG. This will give you detailed log messages for your development use. While on production, its typical set the log level to ERROR. This is to avoid filling your logs with excessive debug information. And while logging is very efficient, there is still a cost.

In your application, once you have retrieved a logger, you call one of the printing methods debug(), info(), warn(), error(), fatal(), and log() on the logger to log messages. These messages are contained in the Logger interface and part of the root logger that all Log4J 2 loggers inherit.


Once you capture logging information through a logger, you need to send it to an output destination. The output destination is called an appender, and it is attached to the logger. Log4J 2 provides appenders for console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons.

Appenders are inherited additively from the logger hierarchy. This means, if the console appender is attached to the root logger, all child loggers will inherently use the console appender. If you have a child logger named Foo attached with a file appender, then Foo will use both the console and file appenders, unless you explicitly ask it not to do so by setting the additivity attribute to false.


In addition to specifying your preferred output destination, you can also specify the format of log messages. You can do so by associating a layout with the appender. Some key layouts that Log4J 2 provides are PatternLayout, Htmlayout, JsonLayout, and XmlLayout. If you want to format logging data in an application-specific way, you can create your own layout class extending from the abstract AbstractStringLayout class – the base class for all Log4J 2 layouts that result in a String.

Using Log4J 2

Let’s jumpstart to create a trivial application to use Log4J 2 and start logging. For the application, I have used Spring Boot and started out with a Spring Boot starter POM. If you are new to Spring Boot, you can start with my introductory post on Spring Boot here.

As the Spring Boot starter POM uses Logback for logging, you need to exclude it and add the Log4J 2 dependencies.

Here is the code of the POM file to use Log4J 2 in a Spring Boot application.

We can now start logging messages in the classes of the program. Let’s write a class for that.

In the class we wrote above, we retrieved a logger through a call to getLogger(). We then called the various printing methods on the logger.

Now let’s write a test class.

On running the test class, the output in the IntelliJ console is this.

Log4J 2 Output in IntelliJ

You may have noticed that I did not specify an appender or layout. I did not configure either one, and Log4J 2 rightfully pointed that out with an error message, as shown in the figure above. Rather, I relied upon defaults inherited from the Log4J 2 root logger. The Log4J 2 root logger is associated with the console appender (ConsoleAppender class) by default, and our logger inherited it. Therefore the log messages were sent to the IntelliJ console. If you notice, only the error and fatal messages got logged. This happened because by default Log4j 2 assigns the root logger level to ERROR and without external configuration, messages of the lower levels (WARN, INFO, and DEBUG) were not send to the destination. Also, the root logger by default uses PatternLayout, which our logger inherited and used.


In this post, I have only scratched the surface of Log4J 2. You will realize the power of Log4J 2 when you start working with external configuration files. These configuration files can be .properties, XML, YAML, and JSON files containing Log4J 2 configuration options. This means, you can set and change the configuration options without having to modify and recompile the application. In upcoming posts, I will discuss using external configuration files to help you explore what a powerful logging tool Log4J 2 is.

There are a number of logging solutions available for Java. Each has its own merits and drawbacks. Yet all of them are far better options than using System.out.println()!  Printing out to the console, simply is not an enterprise class solution. Often in the enterprise, your log files need to be secured, and are often indexed by monitoring tools such as Splunk. Professional Java developers will use a logging framework such as Log4J 2.

Related Posts on Log4J 2


The latest TIOBE index has Java language moving strongly into the #1 programming language for January 2016. If you’re not familiar with the TIOBE Index, it’s an index that looks at searches on the major search engines, blogs, forums, and Youtube (Did you know Youtube is now the second biggest search engine?) The “Popularity of Programming Language” index uses a slightly different approach, also has Java remaining at the #1 position for January 2016. Both indexes are giving Java over 20% of the market.

The Java Language Into the Future

I’ve read a lot of articles predicting the demise of the Java language. I don’t see that happening anytime soon. The Java language continues to evolve with the times. Java 7 was a fairly boring release. Java 8, however, has a number of exciting features. Java 8 lambdas are a really neat new feature to Java. It’s a feature that is long overdue. But I have to give kudos to the Java team. They did a real nice job of implementing lambdas.

It’s these new features that allow Java to evolve and remain relevant as modern programming languages. Functional programming has been a big buzz in the last few years. Guess what, with Java 8 and lambdas, you can do functional programming in Java now.

The JVM is the crown jewel of the Java community. With each release, the JVM becomes more stable and faster. Early releases of Java were dreadfully slow. Today, Java often approaches the performance of native code.

Another fun trend in the Java community is the rise of alternative JVM languages. That same Java runs more than just Java. My personal favorite alternative JVM languages are Groovy and Scala. Both are trending nicely in the programming indexes. And you’re seeing greater support for Groovy and Scala in Spring too. (Expect to see more posts on both in 2016!) If you account for these two alternative JVM languages, you can see how Java is truly dominating the Microsoft languages in the marketplace.

It’s going to be interesting to see what the future holds. I’m personally interested in the Swift programming language. Could Swift someday dethrone Java from the #1 spot? I think that’s going to depend on how the Swift open source community develops. I thought about building an enterprise class application in Swift. Is there a DI / IoC framework like Spring for Swift? No, not yet. An ORM like Hibernate for Swift? No, not yet. And Enterprise Integration framework like Spring Integration or Apache Camel for Swift? No, not yet. I find languages like Swift and Go very interesting, but they just don’t have the open source ecosystem which Java has. If a language is going to dethrone Java from the top, it’s going to need a thriving open source community behind it.

Like Java, all the popular open source projects continue to evolve with the language. So any calls for the demise of Java are premature. The future for the Java language is bright. The future for the Java community is brite!

java duke in shades


I woke this morning to an email linked to a blog post warning me if I’m using Java, this is the next heartbleed bug I need to be worried about. That’s a pretty serious headline, so I checked out the post.

Heartbleed Bug

For those not familiar with the heartbleed bug, it was a pretty significant vulnerability in OpenSSL allowing attackers to run code on the server. OpenSSL is a popular open source library, used in many flavors of linux, and used by web servers to support https communications. Thousands of applications were affected. Hundreds of thousands (perhaps millions) of web sites were left vulnerable. The heartbleed bug was serious business. Internet facing machines could be compromised. This last part is very important about the serious nature of the heartbleed bug, since the vulnerability could be exploited from the internet.

Heartbleed Bug

Java Serialization Exploites

Serialization in Java has long been known as a dance with the devil. In a nutshell, you’re taking a Java object, saving that object and its current state in binary format, transmitting the binary content to another server (and JVM), then restoring the object. The Java “heartbleed” exploit works by manipulating the binary content of the serialized object, then sending it to the receiving JVM. The unsuspecting JVM can then be tricked into executing code injected by the attacker.

A popular library from Apache is vulnerable to being compromised. The Apache Commons Collections library is used in a number of popular Java application servers and applications. This library is of particular concern because code is executed when the library deserializes objects. But this is just one feature of the library. A large part of its usage is around Java collections. You’ll find Apache Commons Collections in the dependencies of many Spring projects, but the vulnerable InvokerTransformer class is not used by Spring.

The only internet facing threat I know of is the practice of storing Serialized Java objects as cookies on the client. Let me be blunt, if you’re not encrypting the binary cookie data before you send it to the client, you’re an idiot and deserve to get hacked.

The rest of the exploits I looked at required access to the network behind the internet firewall. This is a significant reduction in the threat. If an attacker is inside your internet firewall, you’ve already been compromised.

Okay, let’s say the attacker is inside, now the server needs to be listening for, and accepting serialized objects on a network port. Fairly common for RMI. And yes, this can be exploited.

Java Serialization Exploites in the Modern Enterprise

But now let’s look at the modern enterprise. Compliance with regulations such as PCI, SOX, and SAS-70 have driven a number of security measures into the enterprise.

For example, PCI compliance is a fan of encrypting data in flight. Just by encrypting the communication channel neuters this exploit.

But compliance doesn’t stop there. In the old days, I could get on the corporate network and access production systems. As long as I was on the network, I could get to the servers. Even ‘sniff’ for traffic going to said production servers.

Not anymore. Modern production systems live in private networks. Often the networks are layered. They are firewalled to minimal access. If you have a memcache server, only the associated application servers will be allowed to communicate with it. Disgruntled Sally hacker on her PC in the call center will not have network access to the production servers.

Keep in mind, I’m referring to large enterprises. You still see a lot more security hardening in the financial services sector than you do in other industries, such as retail. But regulatory compliance is driving even retailers to adopt better IT security practices. (Target hack anyone?) A small business is not going to have the depth on the IT bench as a large business, but it’s still no excuse to not follow best practices.

Java Serialization Risks and the Spring Framework

As I mentioned above, Spring does not use Apache Commons Collections, and does not use the Apache InvokerTransformer class. But this vulnerability is specific to Java serialization, and not limited to the Apache InvokerTransformer class. The Spring team did identify a similar risk in the Spring Framework code. This has been fixed in Spring versions 4.1.9 and 4.2.3. You can read details about the fix here.

Java Heartbleed Bug?

But is this the Java “heartbleed” bug? No, not even close. The risk is nowhere close to the original heartbleed bug. Let me be even more blunt. If you’re not following best practices in your coding, and you’re not adopting IT security best practices popularized by PCI, SOX, and SAS-70 compliance – you’re a lazy moron and deserve to get hacked.

People referring to this as Java’s heartbleed bug are overly alarmist. It is a vulnerability we need to be aware of. Good coding practices and IT security best practices significantly mitigate the risks in Java serialization.

In Java development, you’re also seeing a move away from using RMI and serialization in general. For RMI, the trend is to use web services, in which the object is converted to XML or JSON. For JMS, you often see XML or JSON again over serialized objects. JMX, that is going to be secured.

This is not Java’s heartbleed bug. Millions of websites are not as risk. The risk from internet exposed machines is small. Risks around Java serialization are very narrow. There are very specific use cases you need to be concerned with. Relax, the sky isn’t falling. Whew.

keep calm and use java


ArrayList is one of the most commonly used collection classes of the Java Collection Framework because of the functionality and flexibility it provides. ArrayList is a List implementation that internally implements a dynamic array to store elements. Therefore, an ArrayList can dynamically grow and shrink as you add and remove elements to and from it. It is likely that you have used ArrayList, therefore I will skip the basics. If you are not familiar with ArrayList yet, you can go through its API documentation here, which is very descriptive and easy to understand to perform basic operations on ArrayList.

In this post, I will discuss one of the most important operation on ArrayList that you will most likely require implementing during enterprise application development. It’s sorting the elements of an ArrayList.

Sorting an ArrayList of String Objects

Consider an ArrayList that stores country names as String objects. To sort the ArrayList, you need to simply call the Collections.sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order). Lets’s write some code for it.

In the class above, we initialized an ArrayList object in the constructor. In the sortAscending() method, we called the Collections.sort() method passing the initialized ArrayList object and returned the sorted ArrayList. In the sortDescending() method we called the overloaded Collections.sort() method to sort the elements in descending order. This version of Collections.sort() accepts the ArrayList object as the first parameter and a Comparator object that the Collections.reverseOrder() method returns as the second parameter. We will come to Comparator a bit later. To test the sorting functionality, we will write some test code.

In the test code above, we created a ArrayList object and added five String objects that represent the names of five countries to it. We then called the getArrayList(), sortAscending(), and sortDescending() methods and printed out the ArrayList objects that the methods return.

The output is this.

At this point, it might appear that sorting elements of an ArrayList is very simple. We only need to call the Collections.sort() method passing the ArrayList object whose elements needs to be sorted. But, there is more to sorting ArrayLists as you encounter additional scenarios.

The Collections.sort() method sorts ArrayList elements or elements of any other List implementation provided the elements are comparable. What this means programmatically is that the classes of the elements need to implement the Comparable interface of the java.lang package. As the String class implements the Comparable interface, we were able to sort the ArrayList of country names. Some other classes standard to Java which implement the Comparable interface include the primitive wrapper classes, such as Integer, Short, Double, Float, and Boolean. BigInteger, BigDecimal, File, and Date are also examples of classes that implement Comparable.

Sorting an ArrayList using Comparable

Comparable is an interface with a single compareTo() method. An object of a class implementing Comparable is capable of comparing itself with another object of the same type. The class implementing Comparable needs to override the compareTo() method. This method accepts an object of the same type and implements the logic for comparing this object with the one passed to compareTo(). The compareTo() method returns the comparison result as an integer that has the following meanings:

  • A positive value indicates that this object is greater than the object passed to compareTo().
  • A negative value indicates that this object is less than the object passed to compareTo().
  • The value zero indicates that both the objects are equal.

Let’s take an example of a JobCandidate class whose objects we want to store in a ArrayList and later sort them. The JobCandidate class has three fields: name and gender of type String and age that is an integer. We want to sort JobCandidate objects stored in the ArrayList based on the age field. To do so, we will need to write the JobCandidate class to implement Comparable and override the compareTo() method.

The code of the JobCandidate class is this.

In the overridden compareTo() method of the JobCandidate class above, we implemented the comparison logic based on the age field. I have seen many programmers restoring to the shortcut version of returning the comparison result as return (this.getAge() - candidate.getAge());. Although using this return statement might appear tempting and will not anyhow affect our example, my advice is to stay away from it. Imagine, the result of comparing integer values where one or both of them are negative values. It can lead to bugs that will make your application behave erratically and more than that, such bugs being subtle, are extremely difficult to detect especially in large enterprise applications. Next, we’ll write a helper class which will sort ArrayList objects containing JobCandidate elements for clients.

In the JobCandidateSorter class we initialized a ArrayList object that client will pass through the constructor while instantiating JobCandidateSorter. We then wrote the getSortedJobCandidateByAge() method. In this method, we called Collections.sort() passing the initialized ArrayList. Finally, we returned back the sorted ArrayList.

Next, we will write a test class to test our code.

In the test class above, we created four JobCandidate objects and added them to an ArrayList. We then instantiated the JobCandidateSorter class passing our ArrayList to its constructor. Finally, we called the getSortedJobCandidateByAge() method of JobCandidateSorter and printed out the sorted ArrayList that the method returns. The output on running the test is this.

Sorting ArrayList using Comparable is a common approach. But, you need to be aware of certain constraints. The class whose object you want to sort must implement Comparable and override the compareTo() method. This essentially means you would only be able to compare the objects based on one field (which was age in our example). What if the requirements state you need to be able to sort JobCandidate objects by name and also by age? Comparable is not the solution. In addition, comparison logic is part of the class whose objects needs to be compared, which eliminates any chance of reusability of the comparison logic. Java addresses such comparison requirements used in sorting by providing the Comparator interface in the java.util package.

Sorting an ArrayList using Comparator

The Comparator interface similar to the Comparable interface provides a single comparison method named compare(). However, unlike the compareTo() method of Comparable, the compare() method takes two different objects of the same type for comparison.
We will use Comparator to sort objects of the same JobCandidate class we used earlier but with few differences. We will allow sorting JobCandidate objects both by name and age by implementing Comparator as anonymous inner classes.

Here is the code of the JobCandidate class using Comparator.

In the class above, from Line 29 – Line 35, we wrote an anonymous class and implemented the compare() method that will allow sorting JobCandidate objects by age in descending order. From Line 37 – Line 42, we again wrote an anonymous class and implemented the compare() method that will allow sorting JobCandidate objects by name in ascending order. We will now write a class that will sort the elements of the ArrayList for clients.

In the class above, we wrote the getSortedJobCandidateByAge() method. In this method we called the overloaded version of Collections.sort() passing the ArrayList object to be sorted and the Comparator object that compares age. In the getSortedJobCandidateByName() method, we again called the overloaded version of Collections.sort() passing the ArrayList object to be sorted and the Comparator object to compare names.

Let’s write a test class to test our code.

In the test class we populated JobCandidate objects in an ArrayList and created a JobCandidateSorter object in the JUnit setup() method annotated with @Before. If you are new to JUnit, you can refer my post covering JUnit annotations (Part of a series on unit testing with JUnit) here. In the testGetSortedJobCandidateByAge() test method we called the getSortedJobCandidateByAge() method and printed out the sorted ArrayList that the method returns. In the testGetSortedJobCandidateByName() test method, we called the getSortedJobCandidateByName() method and printed out the sorted ArrayList that the method returns. The output of the test is this.


In this post we looked at different approaches of sorting elements of ArrayList. One using Comparable and the other using Comparator. The approach to choose has always been a cause of confusion for programmers. What you should essentially remember is that a Comparable object can say “I can compare myself with another object” while a Comparator object can say “I can compare two different objects”. You cannot say that one interface is better than the other. The interface you choose depends upon the functionality you need to achieve.


As a Java programmer, you will often need to work with date and time. In this post, we will learn how to get the current time of the day in Java applications. In Java, there are several ways for this and the primary classes that programmers typically use are the Date and Calendar classes. You can use both the classes to calculate the current time of the day and then use the SimpleDateFormat class to format the time according to your requirements.

Using the Date and Calendar Classes

To calculate the current time you create a Date object, specify a format to present the current time of the day, and finally use the SimpleDateFormat class to format the time as you specified.

Here is the code.

In the code above, we created a Date object and specified the format for the time. In the format string, the lower case hh represents a 12 hour format while mm and ss represents minutes in hour and seconds in minutes respectively. Also, a in the format string is the am/pm marker. We then created a SimpleDateFormat object initialized with the format string and called the format() method on it passing the Date object. The format() method returns the current time in the format we specified.

Using the Calendar class is equally simple. Here is the code.

In the code above, we called the getInstance() factory method of the Calendar class to obtain a Calendar object and then called the getTime() method on it. This method returns a Date object. The remaining code is the same as I explained in the preceding Date example. The only difference you should observe is the format string. Here we specified hour as HH (Upper case) which will give us the time in 24 hour format.

Here is the complete code.


We will next write a test class.



The output is this.

By now, you might be thinking that calculating current time in Java can never be easier. But the Date and Calendar classes have some inherent disadvantages. When you start developing enterprise applications, the disadvantages become more obvious. Primarily, both the classes are not thread-safe, which might lead to concurrency issues. Also, both the classes have the limitation of calculating time to milliseconds only. In mission-critical enterprise applications, it is often required to represent time to nanosecond precision.
In addition, even though the Date class is not itself deprecated, due to poor API design most of its constructors and methods are now deprecated. Because of such issues, enterprise application developers turned toward third-party specialized date and time APIs, particularly Joda-Time.

Using java.time

The Java specification team of Oracle realized the limitations of the in-built date and time handling API and to provide a more efficient API introduced the java.time package in the new Java SE 8. This project is developed jointly by Oracle and Stephen Colebourne, the author of Joda-Time. The new java.time API “is inspired by Joda-Time“.

Calculating Time of the Default Time Zone

The java.time package have several classes to work with date and time. Let’s start with some code to calculate the current time of the default time zone.

As you can observe, the code is pretty straight forward. We called the now() method of LocalTime that returns a LocalTime object. This is an immutable object that represent a time without a date and a time-zone in the ISO-8601 calendar system.

The output of the code is.

In the output above, observe that the time is represented to nanosecond precision.

Calculating Time of a Different Time Zone

The java.time package provides classes that you can use to get the current time of a different time zone. As an example, if you are located in your default time zone and you want the current time of the day of a different time zone, say America/Los_Angeles, you can use the following classes:

  • ZoneId: Represents a particular time zone.
  • DateTimeFormatter: Similar to the SimpleDateFormat class we discussed earlier, this class is a formatter for parsing and printing date-time objects.

The code to calculate the current time of a different time zone is this.

In Line 4 – Line 5, we created a ZoneId object to represent the America/Los_Angeles time zone and then obtained the current time of the time zone by calling the now() method passing the ZoneId. The LocalTime object that the now() method returns holds the current time of the day of America/Los_Angeles. From Line 6 – Line 8, we formatted the time into 24 hour format using DateTimeFormatter and printed out the formatted time.

The output of the code is.

Calculating Time of a Different Time Offset

Time offset is the amount of time in hours and minutes added to or subtracted from Coordinated Universal Time (UTC). The java.time package provides the ZoneOffset class to calculate the current time of the day of a different time offset.

The code to use the ZoneOffset class is this.

In the code above, we created a ZoneOffset object in Line 4 to represent the -8:00 time offset. In Line 5 we created a ZoneId object initialized with the ZoneOffset object. The remaining code from Line 6 to Line 9 uses a LocalTime object initialized with the ZoneId and a DateTimeFormatter object to format the time in the 12 – hour format with the am/pm marker

The output of the preceding code is.

The complete code of the snippets we discussed is this.

Let’s write a test class to see the code in action.

The output I got on running the test using Maven is shown below, which obviously will differ based on your current time and time zone.


In terms of working with time in Java, this post has only scratched the surface. The java.time package has an extensive set of classes that simplifies working with date and time. However, you will also encounter the Date and Calendar classes and the Joda-Time API when you work on legacy applications. But, with the powerful features built in java.time, you can easily convert your legacy date and time calculation code to java.time. Go ahead and explore the java.time API, which is very well documented and easy to use.

Keep in mind when you’re using the local time options, Java is going through the JVM to talk to whatever machine it is running on. This is how Java is determines the time and the locale of time operations. Thus, your code can produce different results when running on different machines. As a word of caution, when you’re working on small applications, often you won’t need to worry about time timezone. But in larger applications, you will. You will need to make your code aware of the timezone. Many developers overlook the timezone component, then run into problems later as their application grows.



I remember in the late 90s / early 2000 all the buzz in programming was about XML. All the ‘experts’ said you had to be using XML for data exchange. XML does have many benefits. But often when programming today, XML is looked as ‘old school’ or too restrictive. XML sure can be finicky to work with. Many developers when given a choice (including myself) will use JSON over XML. JSON is much more forgiving than XML is, which makes it simpler to work with.

While XML may be old school, it still can be good to use. Even when you’re doing JSON based Restful web services.

Restful Web Services in Spring

I’m not going to cover building Restful Web Services in Spring in this post. That’s a future topic. But when you’re using Spring MVC to develop Restful Web Services, you can set up a lot of flexibility. I typically design my web services so the client can use JSON or XML. The standards support this, and it’s fairly easy to do.

Many of the examples you will see on the internet will start with using JAXB annotated Java POJOs. This works, but I also feel this is a mistake. The ‘contract’ for your web services is now a Java class. Which may work for you, but it’s not portable. What if one of your clients is writing in PHP??? A JAXB annotated Java class is useless to them.

XML Schema

XML Schema is a specification for describing XML documents. Think of it as strong typing for an XML document. You can specify the properties, if they can be null, their data types, if they can be a list, etc. The capabilities of XML schema is very robust.

A really cool feature of JAXB is you can generate JAXB annotated Java POJOs from a XML Schema document. And when you do this, you now have a portable contract for the data types of your web services. Your ‘contract’ is no longer tied to the Java programming language. You could give the XML schema to someone building a client for your web service in another programming language, like C# maybe, and they can use the XML Schema to generate code for the client.

XML Schema is a widely accepted standard that is not tied to a specific programming language. By using XML schema and providing it to your clients you make your Restful Web Service easier to consume. Your clients have a standardised specification of exactly what they need to send.

JAXB Generated Classes for Restful Web Services

In this post, I’m going to show you how to setup a Maven project to create a Jar file of Java classes generated by JAXB from an XML Schema.

Generating a Maven Project in IntelliJ

For the purposes of this example, I’m going to use IntelliJ to create a Maven project. In real use, you’ll want to set this up as either a independent Maven project, or a Maven module. This will allow the JAXB generated classes to be bundled in a JAR file and reused in other projects or modules.

1. Create a new project in IntelliJ.

Create Maven Project in IntelliJ

2. Set the GroupId and ArtifactId in the New Project dialog of IntelliJ.

New Project Dialog in IntelliJ

3. Select where to store the project on your drive.

path location in IntelliJ

4. IntelliJ will as your to verify the creation of a new directory. Click OK.

Directory Does Not Exist dialog in IntelliJ

5. Depending on your settings in IntelliJ, you may be asked to import changes. I often keep this feature off when dealing with large complex Maven projects due to performance reasons. If you see this dialog, click on ‘Import Changes’.

import Maven changes into IntelliJ

6. At this point you’ve created a new Maven project in IntelliJ. You can see the Maven standard directory structure has been created.

Maven project in IntelliJ


Create the XML Schema

The first file we will create is the XML Schema we will be using. Let’s say we’re creating a Web Service to add a product, and need a create product command object.

In our XML Schema we are creating a Product class, and the a CreateProductRequest class too. This is going to extend the ProductClass and add a field for the API key. This file is placed in the folder /main/resources. This is the default location for XML Schema files.


Configure Maven

Creating the project in IntelliJ gave us a very basic Maven POM file. Here is the Maven POM created for us.

Maven Dependencies

We need to add three dependencies to our Maven POM. This first is the JAXB API, the second is the JAXB implementation, and finally the third is for the Maven JAXB plugin.

Maven JAXB Plugin

Next we need to configure the JAXB plugin for Maven to the Maven POM.

Complete Maven POM

Here is the final Maven POM.

Building Our JAXB Maven Project

Running the Maven Package Goal

IntelliJ makes working with Maven very easy. On the right side of the IDE, you’ll see a button for ‘Maven Projects’, clicking that will open the ‘Maven Projects’ dialog. To build our project, under Lifecycle, double click on the ‘package’ goal.

Maven Projects in IntelliJ

You should see Maven run and build successfully.

Maven Build Artifacts

Maven will build into the ‘Target’ directory. You can see the Java classes generated in IntelliJ.

JAXB Maven Artifacts

JAXB Generated Classes

We expected two classes generated from the XML Schema we defined.

Notice how this class actually extends the Product class.


This is just a very simple example of generating classing from an XML Schema using JAXB and Maven. In this post, I’ve shown you step by step how to use an XML Schema and JAXB to generate Java classes. The generated classes are bundled into a JAR file, which is portable and can be shared with other Java projects.

As a Spring Source consultant, I was at a large company which built a number of Restful APIs. The team building the APIs did not use JAXB to generate classes from an XML Schema. Rather they built the JAXB classes by hand and could not offer their clients an XML Schema. As a consumer of their APIs, it was a time consuming process to configure and troubleshoot my data types.

I’ve also done consulting in organizations where the team did use XML Schemas for building their APIs. Having the XML Schema made writing the client code a snap.



You can find the documentation for the JAXB project here.

JAXB Maven Plugin

I used the default settings for the JAXB Maven plugin. Additional options are available. Documentation for the JAXB Maven plugin is here.

Project Source Code

The source code used in this tutorial is available on Github here.



I was recently asked on my Facebook page, “How do I become a Java Web Developer?” There is  really no simple answer for this question. There are many facets to becoming a Java web developer. I’ve encountered Java developers who were good front end developers, or good backend developers. By ‘front end’, I mean more of the browser side technologies – HTML, CSS, Javascript and then Java templating technologies such as Thymeleaf, Sitemesh, or just good old JSPs. Backend developers are going to have stronger skills with Java, databases (SQL and NoSQL), messaging (JMS/AQMP), and web services (SOAP / REST).

You also have what is known as a “full stack” Java developer. This is my personal skill set. A full stack developer is equally skilled as a front end developer and as a back end developer. This is probably the most difficult track to follow, just because of the diversity of technologies involved. One one day you might be debugging something in JQuery, and the next you’re performance tuning an Oracle database query. It takes time and experience to become a full stack Java developer.

Where to Start?

For aspiring developers, the technology landscape can be overwhelming. The technology landscape is always evolving too. Do you risk learning something that will soon be obsolete?

Client Side Technologies

My advice to new developers is to start with the basics. HTML, CSS, and Javascript. These technologies are core to web development. These technologies are also generic in the sense that it does not matter if you’re a Java web developer, or a Ruby web developer.


HTML – Hypertext Markup Language. This is what makes a web page. You need to have a solid understanding of HTML. Back in the beginning of the World Wide Web HTML was traditionally a file that was served by a web server to the browser. This worked great for static content. Stuff that never changed. But this is becoming rare. People want dynamic content. Thus, the HTML is no longer a static file, the HTML is generated on demand. As a Java Web Developer you’re going to be writing code that generates the HTML document for the web browser. You will need to have a solid understanding of the structure of an HTML document.


CSS – Cascading Style Sheets. This is what styles a page. It controls the fonts, the colors, the layout. While HTML defines the content of a web page, CSS defines how it looks when presented in a browser. For example, you may use one set of CSS rules for a desktop web application, and a different set of CSS rules for a mobile application. Same HTML, but two completely different looks when rendered by the browser.


Javascript – Do stuff on the web page. Do not confuse Javascript with Java. While there are some syntax similarities, these are two completely different programming languages. Javascript is what really drives Web 2.0 applications. Through the use of Javascript, you can dynamically change the HTML/CSS based on user actions, giving the web page a more application like feel for the user.


Hypertext Transfer Protocol – The communication between the client and the web server. I see too many web developers who do not understand HTTP. This is absolutely critical for you to understand. Especially as you get into working with AJAX. You need to know the difference between a POST and a GET. You should have memorized the meanings of HTTP status codes 200, 301, and 404 – and more. As a Java web developer you will work with HTTP everyday.

Server Side Technologies


Java – The question is how to become a Java web developer. So, of course you are going to need to know the Java programming language.In addition to just Java itself, you should be familiar with the Java Servlet API. There’s a number of Java web frameworks, which obscure the usage of the Java Servlet API. When things go wrong, you’re going to need to know what’s happening under the covers.


JPA – Java Persistence API – Using the database. JPA is the standard for working with traditional relational databases in Java. Hibernate is the most popular JPA implementation in use today. As a Java web developer, you’re going to be working with databases. You’ll get getting content from the database to display on a web page, or receiving content from the user to store in the database. Java Web Developers need to know how to use JPA.

Java Application Servers

Java Application Servers – The runtime container for Java web applications. Tomcat is, by far, the most popular Java application server. There is a Java standard for a Web Application Archive file – aka WAR file. These are deployed to Application servers such as Tomcat to provide the runtime environment for your web application. A decade ago, the trend was to use a more complex coupling between your application and the application server. However, the current trend is in favor of a looser coupling between your application and the application server.

Java Frameworks

Notice so far, I have not mentioned anything about the plethora of Java frameworks available for you to use? So far, I’ve described the different technologies you will use as a Java web developer. The client side technologies are completely independent of the server side technologies. Firefox doesn’t care if the server is running Java, Python or .NET. New developers often seem to forget this.

It is possible to do Java web development without using one of the Java frameworks. If you do, you will be writing a lot code to handle things which a framework would take care of for you. Which is why when developing Java web applications, you typically will want to use one of the frameworks.

Spring Framework

The Spring Framework is an outstanding collection of tools for building large scale web applications. Exact metrics are hard to determine, but I’ve seen some estimates which say Spring is used in over 60% of Java based web applications. Which really isn’t too surprising. You have the IoC container and dependency injection from Spring Core. Spring MVC, a mature and flexible MVC based web framework. Spring Security, best in class tool for securing your website. Spring Data to help with persistence. Spring has other projects which will help you in building large scale applications.

There really is no alternative to Spring when it comes to a holistic framework. There are competing technologies against the various Spring Projects. But there is no single solution that has the depth and breadth of the Spring Framework family of projects. In my Introduction to Spring online tutorial, I give you a good overview of the major Spring Framework projects and how they are used to build enterprise class applications.


Grails is a rapid application development framework built on top of Spring. You get everything Spring, and then the productivity benefits of Groovy. I like to describe Grails as Spring with a Groovy wrapper. An oversimplification for sure, but important to remember, Spring is still under the covers.

Grails is seeing more and more use in the enterprise. One of the strengths of Grails is its outstanding community support.

Spring Roo

Spring Roo is a pure Java framework, which seems to try to do what Grails does, without Groovy. I’m not a fan of Spring Roo, and last time I checked neither was the marketplace. Spring Roo has not been widely adopted.


A Scala based Framework. I have not had a chance to try out Play yet. I hear a lot of good things about Play in the marketplace. I feel Play is an interesting alternative. But it’s just not widely used in the enterprise. Not yet at least. Play is getting some encouraging traction.

JBoss Seam

JBoss Seam is probably the closest thing to an alternative to the Spring Framework. JBoss Seam follows the JEE standard. JBoss Seam is a good alternative, with good support, and adoption in the enterprise. JBoss Seam is often criticised as being slower than Spring in terms of development and performance. Some are much more critical of JBoss Seam.


Becoming a Java web developer is not something you can become overnight. There is no book called “Teach yourself Java Web Development in 21 days.” There are no short cuts to becoming a Java web developer. There are a lot of different technologies you need to learn and master. Each of these take time to learn.

Being a Java web developer can be a very rewarding career. You can get started just focusing on the front end, or just the backend technologies. Larger Java development shops will allow you to specialize in one area of the technologies over another.

If I was starting out as a Java web developer today, I probably would focus first on the client side technologies. The client side technologies are agnostic to the server side technologies. Thus, as you’re starting out you will have greater employment options. Compensation on the client side technologies is generally lower than the server side, but it’s a good place to start out. You can quickly gain the skills to be employable, then shift focus and broaden your skill set and later seek better employment opportunities.