Java Integer Cache – Why Integer.valueOf(127) == Integer.valueOf(127) Is True

In an interview, one of my friends was asked that if we have two Integer objects, Integer a = 127; Integer b = 127; Why a == b evaluate to truewhen both are holding two separate objects? In this article, I will try to answer this question and also try to explain the answer.

Short Answer

The short answer to this question is, direct assignment of an int literal to an Integer reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts Integer a = 127; to Integer a = Integer.valueOf(127);.

TheInteger class maintains an internal IntegerCache for integers which by default ranges from -128 to 127andInteger.valueOf() method returns objects of mentioned range from that cache. So a == b returns true because aand b both are pointing to the same object.

Long Answer

In order to understand the short answer let’s first understand the Java types, all types in Java lies under two categories

  1. Primitive Types: There are 8 primitive types (byte, short, int, long, float, double, char and boolean) in Java which holds their values directly in the form of binary bits.
    For example int a = 5; int b = 5;, here a and b directly holds the binary value of 5 and if we try to compare a and b using a == b we are actually comparing 5 == 5 which returns true.
  2. Reference Types: All types other than primitive types lies under the category of reference types e.g. Classes, Interfaces, Enums, Arrays etc. and reference types holds the address of the object instead of the object iteslf.
    For example, Integer a = new Integer(5); Integer b = new Integer(5), here a and b do not hold the binary value of 5instead a and b holds memory addresses of two separate objects where both objects contain a value 5. So if we try to compare a and b using a == b, we are actually comparing those two separate memory addresses hence we get false, to perform actual equality on a and b we need to perform a.euqals(b)Reference types are further divided into 4 categories Strong, Soft, Weak and Phantom References.

And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.

1 // Example of auto-boxing, here c is a reference type
2 Integer c = 128// Compiler converts this line to Integer c = Integer.valueOf(128);
4 // Example of auto-unboxing, here e is a primitive type
5 int e = c; // Compiler converts this line to int e = c.intValue();

Now if we create two integer objectsa andb, and try to compare them using the equality operator==, we will getfalsebecause both references are holding different-different objects

Integer a = 128// Compiler converts this line to Integer a = Integer.valueOf(128);
Integer b = 128// Compiler converts this line to Integer b = Integer.valueOf(128);
System.out.println(a == b); // Output -- false

But if we assign the value 127 to both a and b and try to compare them using the equality operator ==, we will get true why?

Integer a = 127// Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127// Compiler converts this line to Integer b = Integer.valueOf(127);
System.out.println(a == b); // Output -- true

As we can see in the code that we are assigning different objects to a and b but a == b can return true only if both aand b are pointing to the same object.

So how the comparison returning true? whats actually happening here? are a and b pointing to the same object?

Well till now we know that the code Integer a = 127; is an example of auto-boxing and compiler automatically converts this line to Integer a = Integer.valueOf(127);.

So it is the Integer.valueOf() method which is returning these integer objects which means this method must be doing something under the hood.

And if we take a look at the source code of Integer.valueOf() method, we can clearly see that if the passed int literal i is greater than IntegerCache.low and less thanIntegerCache.high then the method returns Integer objects fromIntegerCache. Default values for IntegerCache.low and IntegerCache.high are -128 and 127 respectively.

In other words, instead of creating and retruning new integer objects, Integer.valueOf() method returns Integer objects from an internal IntegerCache if the passed int literal is greater than
-128 and less than 127.

 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 public static Integer valueOf(int i) {
     if (i >= IntegerCache.low && i <= IntegerCache.high)
         return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);

Java caches integer objects which fall into -128 to 127 range because this range of integers gets used a lot in day to day programming which indirectly saves some memory.

As you can see in the following image Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 we always get the same object.


The cache is initialized on first usage when the class get loaded into memory because of the static block. The max range of the cache can be controlled by the -XX:AutoBoxCacheMax JVM option.

This caching behavior is not applicable for Integer objects only, similar to Integer.IntegerCache we also haveByteCache,ShortCache,LongCache,CharacterCache forByteShort,
Long,Character respectively.

Byte, Short and Long have a fixed range for caching between –127 to 127 (inclusive) but for Character, the range is from 0 to 127 (inclusive). The range can be modified via argument only for Integer but not for others.

You can find the complete source code for this article on this Github Repository and please feel free to provide your valuable feedback.

15 Spring Core Annotation Examples

As we know, Spring DI and Spring IOC are core concepts of the Spring Framework. Let’s explore some Spring core annotations from the org.springframework.beans.factory.annotationand org.springframework.context.annotation packages.

We often call these “Spring core annotations,” and we’ll review them in this article.

Here’s a list of all known Spring core annotations.

Image title


We can use the @Autowired annotation to mark the dependency that Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.

Constructor Injection:

public class CustomerController {
    private CustomerService customerService;
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;

Setter Injection:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
public class CustomerController {
    private CustomerService customerService;
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;

Field Injection:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
public class CustomerController {
private CustomerService customerService;

For more details, visit our articles about @Autowired and Guide to Dependency Injection in Spring.


  •  @Bean is a method-level annotation and a direct analog of the XML element. The annotation supports some of the attributes offered by, such as the init-method, destroy-method, auto-wiring, and name.
  • You can use the  @Bean annotation in a  @Configuration-annotated or @Component-annotated class.

The following is a simple example of an @Bean method declaration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.companyname.projectname.customer.CustomerService;
import com.companyname.projectname.order.OrderService;
public class Application {
    public CustomerService customerService() {
        return new CustomerService();
    public OrderService orderService() {
        return new OrderService();

The preceding configuration is equivalent to the following Spring XML:

        <bean id="customerService" class="com.companyname.projectname.CustomerService"/>
        <bean id="orderService" class="com.companyname.projectname.OrderService"/>

Read more about the  @Bean annotation in this article  Spring @Bean Annotation with Example.


This annotation helps fine-tune annotation-based auto-wiring. There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using the @Qualifier annotation along with the  @Autowired annotation.

Example: Consider the EmailService and SMSService classes to implement the single  MessageService interface.

Create the MessageService interface for multiple message service implementations.

public interface MessageService {
    public void sendMsg(String message);

Next, create implementations:  EmailService and SMSService.

public class EmailService implements MessageService{
    public void sendMsg(String message) {
public class SMSService implements MessageService{
    public void sendMsg(String message) {

It’s time to see the usage of the @Qualifier annotation.

public interface MessageProcessor {
    public void processMsg(String message);
public class MessageProcessorImpl implements MessageProcessor {
    private MessageService messageService;
    // setter based DI
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    // constructor based DI
    public MessageProcessorImpl(@Qualifier("emailService") MessageService messageService) {
        this.messageService = messageService;
    public void processMsg(String message) {

Read more about this annotation in this article:  Spring @Qualifier Annotation Example.


The @Required annotation is a method-level annotation and applied to the setter method of a bean.

This annotation simply indicates that the setter method must be configured to be dependency-injected with a value at configuration time.

For example, @Required on setter methods marks dependencies that we want to populate through XML:

void setColor(String color) {
    this.color = color;

<bean class="com.javaguides.spring.Car">
   <property name="color" value="green" />

Otherwise, the  BeanInitializationException will be thrown.


The Spring @Value annotation is used to assign default values to variables and method arguments. We can read Spring environment variables as well as system variables using the @Value annotation.

The Spring @Value annotation also supports SpEL. Let’s look at some of the examples of using the @Value annotation.

Examples: We can assign a default value to a class property using the @Value annotation.

@Value("Default DBConfiguration")
private String defaultName;

The @Value annotation argument can be a string only, but Spring tries to convert it to the specified type. The following code will work fine and assign the boolean and integer values to the variable.

private boolean defaultBoolean;
private int defaultInt;

This demonstrates the Spring  @Value — Spring Environment Property

private String defaultAppName;

Next, assign system variables using the @Value annotation.

private String javaHome;

private String homeDir;

Spring @Value  – SpEL
private String javaHome;


The@DependsOn annotation can force Spring IoC containers to initialize one or more beans before the bean, which is annotated by the  @DependsOn annotation.

The @DependsOn annotation may be used on any class directly or indirectly annotated with the  @Component or on methods annotated with the @Bean.

Example: Let’s create  FirstBean and  SecondBean classes. In this example, the  SecondBean is initialized before bean  FirstBean.

public class FirstBean {
    private SecondBean secondBean;

public class SecondBean {
    public SecondBean() {
        System.out.println("SecondBean Initialized via Constuctor");

Declare the above beans in Java based on the configuration class.

public class AppConfig {
    @DependsOn(value = {
    public FirstBean firstBean() {
        return new FirstBean();
    public SecondBean secondBean() {
        return new SecondBean();

Read more about @DependsOn annotation on Spring – @DependsOn Annotation Example.


By default, the Spring IoC container creates and initializes all singleton beans at the time of application startup. We can prevent this pre-initialization of a singleton bean by using the @Lazy annotation.

The  @Lazy annotation may be used on any class, directly or indirectly annotated with the  @Component or on methods annotated with the @Bean.

Example: Consider we have below two beans — FirstBean and  SecondBean. In this example, we will explicitly load  FirstBean using the  @Lazyannotation.

public class FirstBean {
    public void test() {
        System.out.println("Method of FirstBean Class");
public class SecondBean {
    public void test() {
        System.out.println("Method of SecondBean Class");

Declare the above beans in Java based on the configuration class.

public class AppConfig {
    @Lazy(value = true)
    public FirstBean firstBean() {
        return new FirstBean();

    public SecondBean secondBean() {
        return new SecondBean();

As we can see, bean secondBean is initialized by the Spring container, while the bean firstBean is initialized explicitly.

Read more about the  @Lazy  annotation with a complete example onSpring – @Lazy Annotation Example.


A method annotated with  @Lookup tells Spring to return an instance of the method’s return type when we invoke it.

Detailed information about this annotation can be found on Spring @LookUp Annotation.


We use the  @Primary to give higher preference to a bean when there are multiple beans of the same type.

class Car implements Vehicle {}
class Bike implements Vehicle {}
class Driver {
    Vehicle vehicle;

class Biker {
    Vehicle vehicle;

Read more about this annotation on Spring – @Primary Annotation Example.


We use the@Scope annotation to define the scope of a  @Component class or the @Bean definition. It can be either singleton, prototype, request, session, globalSession, or some custom scope.

For example:

@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class TwitterMessageService implements MessageService {
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TwitterMessageService implements MessageService {

Read more about the @Scope annotations on Spring @Scope annotation with Singleton Scope Example and Spring @Scope annotation with Prototype Scope Example.


If we want Spring to use the @Component class or the @Bean method only when a specific profile is active, we can mark it with  @Profile. We can configure the name of the profile with the value argument of the annotation:

class Bike implements Vehicle {}

You can read more about profiles in this Spring Profiles.


The  @Import annotation indicates one or more @Configuration classes to import.

For example: in a Java-based configuration, Spring provides the @Import  annotation, which allows the loading @Bean definitions from another configuration class.

public class ConfigA {
    public A a() {
        return new A();
public class ConfigB {
    public B b() {
        return new B();

Now, rather than needing to specify both the ConfigA class and ConfigB class when instantiating the context, only ConfigB needs to be supplied explicitly.

Read more about the @Import annotation on Spring @Import Annotation.


Spring provides an @ImportResource annotation used to load beans from an applicationContext.xml file into an ApplicationContext. For example: consider that we have applicationContext.xml Spring bean configuration XML file on the classpath.

public class XmlConfiguration {

Read more about this annotation with a complete example onSpring @ImportResource Annotation.


The  @PropertySource annotation provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Eenvironment to be used in conjunction with the @Configurationclasses.

For example, we are reading database configuration from the file config.propertiesfile and setting these property values to the DataSourceConfig class using the Environment.

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

public class ProperySourceDemo implements InitializingBean {
    Environment env;
    public void afterPropertiesSet() throws Exception {

    private void setDatabaseConfig() {
        DataSourceConfig config = new DataSourceConfig();

Read more about this annotation on Spring @PropertySource Annotation with Example.


We can use this annotation to specify multiple  @PropertySource  configurations:

 public class AppConfig {

Read more about this annotation on Spring @PropertySources Annotation.

Hope you enjoyed this post on the best Spring annotations for your project! Happy coding!

@RestController vs @Controller : Spring Framework

Spring MVC Framework and REST

Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Image title

Figure 1: Spring MVC traditional workflow

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.


Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
  3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model;
import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement(name = “Employee”)
 public class Employee {
     String name
      String email;
    public String getName() {
       return name;
    public void setName(String name) { = name;
     public String getEmail() {
                 return email;
     public void setEmail(String email) { = email;
     public Employee() {

Then, create the following @Controller class:

 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.spring.model.Employee;
public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
     return employee;
    @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
        return employee;
 Notice the @ResponseBody added to each of the @RequestMapping methods in the return value. After that, it’s a two-step process:
  1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:output_json-cropXML — Use the
    URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:output_xml

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
 import com.example.spring.model.Employee;
 public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public Employee getEmployeeInJSON(@PathVariable String name) {
        return employee;
     @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public Employee getEmployeeInXML(@PathVariable String name) {
     return employee;

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.


As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!

Java 8 :: Streams – Sequential vs Parallel streams

Parallel streams divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. On the other hand sequential streams work just like for-loop using a single core.

The tasks provided to the streams are typically the iterative operations performed on the elements of a collection or array or from other dynamic sources. Parallel execution of streams run multiple iterations simultaniously in different available cores.


In parallel execution, if number of tasks are more than available cores at a given time, the remaining tasks are queued waiting for currently running task to finish.

It is also important to know that iterations are only performed at a terminal operation, that’s because streams are deisnged to be lazy.


Let’s test sequential and parallel behavior with an example.

import java.time.LocalTime;
import java.util.Arrays;

public class SequentialParallelComparison {

    public static void main (String[] args) {
        String[] strings = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

        System.out.println("-------\nRunning sequential\n-------");
        System.out.println("-------\nRunning parallel\n-------");

    public static void run (Stream<String> stream) {

        stream.forEach(s -> {
            System.out.println( + " - value: " + s +
                                " - thread: " + Thread.currentThread().getName());
            try {
            } catch (InterruptedException e) {

In above example we are printing various information, i.e. time, collection element value and thread name. We are doing that in forEach() terminal function. Other than parallel() and sequential(), we are not using any other intermediate operations, but that doesn’t matter if we use the same intermediate operations for the both. We are also making each iteration to sleep for 200ms so that we can cleary compare the time taken by sequential and parallel invocations.


This is the output, on an 8 logical processors (4 Core) machine.

Running sequential
02:29:02.817 - value: 1 - thread: main
02:29:03.022 - value: 2 - thread: main
02:29:03.223 - value: 3 - thread: main
02:29:03.424 - value: 4 - thread: main
02:29:03.624 - value: 5 - thread: main
02:29:03.824 - value: 6 - thread: main
02:29:04.025 - value: 7 - thread: main
02:29:04.225 - value: 8 - thread: main
02:29:04.426 - value: 9 - thread: main
02:29:04.626 - value: 10 - thread: main
Running parallel
02:29:04.830 - value: 7 - thread: main
02:29:04.830 - value: 3 - thread: ForkJoinPool.commonPool-worker-1
02:29:04.830 - value: 8 - thread: ForkJoinPool.commonPool-worker-4
02:29:04.830 - value: 2 - thread: ForkJoinPool.commonPool-worker-3
02:29:04.830 - value: 9 - thread: ForkJoinPool.commonPool-worker-2
02:29:04.830 - value: 5 - thread: ForkJoinPool.commonPool-worker-5
02:29:04.830 - value: 1 - thread: ForkJoinPool.commonPool-worker-6
02:29:04.831 - value: 10 - thread: ForkJoinPool.commonPool-worker-7
02:29:05.030 - value: 4 - thread: ForkJoinPool.commonPool-worker-3
02:29:05.030 - value: 6 - thread: ForkJoinPool.commonPool-worker-2

This clearly shows that in sequential stream each iteration waits for currently running one to finish, whereas, in parallel stream, eight threads are spawn simultaneously, remaining two, wait for others. Also notice the name of threads. In parallel stream, Fork and Join framework is used to create multiple threads. Parallel streams create ForkJoinPool instance via static ForkJoinPool.commonPool() method.

Difference Between Stored Procedure And User Defined Function In SQL Server

This article describes the differences between Stored Procedures and User Defined Functions in SQL Server.

Stored Procedure

A Stored Procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a Stored Procedure and then just call the Stored Procedure to execute the SQL code that you saved as part of the Stored Procedure.

In addition to running the same SQL code over and over again you also have the ability to pass parameters to the Stored Procedure, so depending on what the need is, the Stored Procedure can act accordingly based on the parameter values that were passed.

Stored Procedures can also improve performance. Many tasks are implemented as a series of SQL statements. Conditional logic applied to the results of the first SQL statements determine which subsequent SQL statements are executed. If these SQL statements and conditional logic are written into a Stored Procedure, they become part of a single execution plan on the server. The results do not need to be returned to the client to have the conditional logic applied; all of the work is done on the server.

Benefits of Stored Procedures

  • Precompiled execution

    SQL Server compiles each Stored Procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when Stored Procedures are called repeatedly.
  • Reduced client/server traffic

    If network bandwidth is a concern in your environment then you’ll be happy to learn that Stored Procedures can reduce long SQL queries to a single line that is transmitted over the wire.

  • Efficient reuse of code and programming abstraction

    Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you’ll find the development cycle requires less time.

  • Enhanced security controls

    You can grant users permission to execute a Stored Procedure independently of underlying table permissions.

User Defined Functions

Like functions in programming languages, SQL Server User Defined Functions are routines that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set.

Functions in programming languages are subroutines used to encapsulate frequently performed logic. Any code that must perform the logic incorporated in a function can call the function rather than having to repeat all of the function logic.

SQL Server supports two types of functions

  • Built-in functions

    Operate as defined in the Transact-SQL Reference and cannot be modified. The functions can be referenced only in Transact-SQL statements using the syntax defined in the Transact-SQL Reference.

  • User Defined Functions

    Allow you to define your own Transact-SQL functions using the CREATE FUNCTION statement. User Defined Functions use zero or more input parameters, and return a single value. Some User Defined Functions return a single, scalar data value, such as an int, char, or decimal value.

Benefits of User Defined Functions

  • They allow modular programming

    You can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code.

  • They allow faster execution

    Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic.

  • They can reduce network traffic

    An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Differences between Stored Procedure and User Defined Function in SQL Server

Sr.No. User Defined Function Stored Procedure
1 Function must return a value. Stored Procedure may or not return values.
2 Will allow only Select statements, it will not allow us to use DML statements. Can have select statements as well as DML statements such as insert, update, delete and so on
3 It will allow only input parameters, doesn’t support output parameters. It can have both input and output parameters.
4 It will not allow us to use try-catch blocks. For exception handling we can use try catch blocks.
5 Transactions are not allowed within functions. Can use transactions within Stored Procedures.
6 We can use only table variables, it will not allow using temporary tables. Can use both table variables as well as temporary table in it.
7 Stored Procedures can’t be called from a function. Stored Procedures can call functions.
8 Functions can be called from a select statement. Procedures can’t be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure.
9 A UDF can be used in join clause as a result set. Procedures can’t be used in Join clause

Volatile boolean vs AtomicBoolean

I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.

Check the JavaDocs of the java.util.concurrent.atomic package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)

Design Patterns

What is the design patterns?

Design Patterns in javaIn this design patterns tutorial, we will explain all type of design patterns in java with example. A design pattern is a common solution that is used to test generally repetitive problems in software development. The design does not exist as a complete program that can be transformed into an object or machine code but, as a template identify problems in the system and provide appropriate solutions. The design pattern testing is not present in normal procedural programming and is mostly adopted by developers in Object Oriented environment. These provide the interaction on Object-Oriented level involving classes and objects.It is used as an efficient programming approach where Object Oriented systems are being developed to provide robustly and error-free software generation.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

Need for Design Patterns

With the emerging needs of technology and the growth in the IT industry, typical software development practices, that required the completion of the entire software before testing, has also evolved. To avoid reverting to the stage of development after completion, a testing practice during development phase was introduced. It can be used to identify error conditions and problems in the code that may not be apparent at the time. The end modules that are obtained are already tested and are less error-prone.

Designing a template that can be reused on multiple codes saves time for test creation and is easy to understand by developers with prior experience working with it. The templates are code and problem independent and do not need to be specified by coders to deal with a problem

Types of Design Patterns

Design patterns are classified into four main categories and each individual design pattern in the category make up a total of 23 design patterns. The four main categories are:


  1. Creational Pattern
  2. Structural Pattern
  3. Behavioral Pattern
  4. J2EE Pattern

Creational Patterns

Creational Pattern is mostly concerned with the manner involved with creating class instances. It is further characterized as class-creation and object-creation Patterns. The object creation or instantiation is done implicitly using design patterns rather than directly. Thus, for a use-case, there is flexibility involved with the object creation.

  • Abstract Factory
    In this pattern, a factory of related objects is created by an interface without specification of the class name. The factory passes the objects by following the Factory Pattern.
  • Builder
    This pattern is used for a stage by stage creation of a complex object by combining simple objects. The final object creation depends on the stages of the creative process but is independent of other objects.
  • Factory Method
    This pattern is employed mostly during development in Java. It provides implicit object instantiation through common interfaces.
  • Object Pool
    Object pooling is used to reduce object creation cost when it is high for certain process and thus improves performance. It employs the method of object caching and simply retrieves objects from the cache pool instead of having to create it. The number of objects in the pool can be restricted to keep from continual growth.
  • Prototype
    In Prototype patterns, object duplication is performed while performance is monitored. A prototype interface pattern is present to produce a copy of an object. It is used to restrict memory/database operations by keeping modification to a minimum using object copies.
  • Singleton
    This pattern involves the present of one class and restricting object creation to a single object. The presence of a single object removes the need for object instantiation for accessing.

Structural Patterns

Structural Patterns deal with the composition of classes and objects. Inheritance is employed for interface composition and methods for addition of new functionalities are introduced by object composition. A better understanding of the entity relationship is established. Abilities of independent interfaces are combined in structural patterns.

  • Adapter
    To link two interfaces that are not compatible and utilize their functionalities, Adapter pattern is used. It is used to provide a new interface covering for any existing class.
  • Bridge
    In Bridge Pattern, there is a structural alteration in the main and interface implementer classes without having any effect on each other. These two classes are made independent of each other and are only connected by using the bridge which is an interface.
  • Composite
    Composite Pattern is used group together objects as one object. The objects are composed in a tree structure form with the representation of individual tree nodes and the hierarchy as well. The objects belonging to the same groups are modified using this pattern.
  • Decorator
    Decorator pattern restricts the alteration of object structure while a new functionality is added to it. The initial class remains unaltered while a decorator class wraps around it and provides extra capabilities.
  • Façade
    Façade provides clients with access to the system but conceals the working of the system and its complexities. The pattern creates one class consisting of user functions and delegates provide calling facilities to the classes belonging to the systems.
  • Flyweight
    Flyweight pattern is used to reduce memory usage and improve performance by cutting on object creation. The pattern looks for similar objects that already exist to reuse it rather than creating new ones that are similar.
  • Private Class Data
    Some of the class attributes may be available without requirement and thus may be prone to be corrupted. To prevent that the attributes may be allowed to be manipulated only once during operation after which it becomes private and thus data is protected.
  • Proxy
    It is used to create objects that may represent functions of other classes or objects and the interface is used to access these functionalities.

Behavioral patterns

Behavioral pattern deals with the communication between class objects. They are used to sense the presence of already present communication patterns and may be able to manipulate these patterns.

  • Chain of responsibility
    A chain of objects is created to deal with the request so that no request goes back unfulfilled.
  • Command
    Command pattern deals with requests by hiding it inside an object as a command and sent to be to invoker object which then passes it to an appropriate object that can fulfill the request.
  • Interpreter
    Interpreter pattern is used for language or expression evaluation by creating an interface that tells the context for interpretation.
  • Iterator
    Iterator pattern is used to provide sequential access to a number elements present inside a collection object without any relevant information exchange.
  • Mediator
    Mediator pattern provides easy communication through its mediator class that allows communication for several classes.
  • Memento
    Memento pattern involves the working of three classes Memento, CareTaker, and Originator. Memento holds the restorable state of the object. Originator’s job is the creation and storing of state and CareTaker’s job is the restoration of memento states.
  • Null Object
    Null Object is used instead of specifying a Null value and is used to represent a particular operation that does nothing when created. It is basically a check for Null value without the presence of the value.
  • Observer
    A One-to-Many relationship calls for the need of Observer pattern to check the relative dependencies of objects.
  • State
    In State pattern, the behavior of a class varies with its state and is thus represented by the context object.
  • Strategy
    Strategy pattern deals with the change in class behavior at runtime. The objects consist of strategies and the context object judges the behavior at runtime of each strategy.
  • Template method
    It is used with components having similarity where a template of the code may be implemented to test both the components. The code can be changed with minor alterations.
  • Visitor
    A Visitor performs a set of operations on an element class and changes its behavior of execution. Thus the variance in the behavior of element class is dependent on the change in visitor class.

J2EE Patterns

J2EE stands for Java 2 Enterprise Edition currently known as Java Enterprise Edition (J EE). It consists of many APIs that provide software developers with the capabilities to write server-side code. The J2EE patterns deal with testing on the presentation tier as offered by Sun Java Center. These design patterns are specifically concerned with the following listed layers.

  • Presentation Layer
  • Business Layer
  • Integration Layer

Core J2EE Pattern Catalog

Presentation Tier

  • Intercepting Filter
    It is used to provide interception and manipulation of requests as well as response prior to and preceding the processing of the request.   readmore
  • Context Object
    Context Object is present to keep from using system information that is specific to the protocol and doesn’t coincide with its context.   readmore
  • Front Controller
    A centralized access point allows for non-duplication of the control logic needed to handle a request. Front Controller is to handle such request by acting as an initial point.   readmore
  • Application Controller
    It provides support for action reuse and code to view-management. The code is made more readable and maintainable as well as modular. Request handling is also improved and made more extensible.   readmore
  • View Helper
    It is used to provide a different view, hiding the logic present in the code. Now the logic and the view are completely independent to provide ease for developers and designers.   readmore
  • Composite View
    Small sub views can be created using the composite view. These sub views can be integrated to create a singular view.   readmore
  • Dispatcher View
    To be able to support a small amount of multitasking, dispatcher view is used. It provides handling and response generation for requests while a business processing is taking place.   readmore
  • Service to Worker
    It is used to perform handling of requests as well as processing of the business transaction and after that, the control is transferred to the View.   readmore

Business Tier

  • Business Delegate
    The business delegate pattern is one of the Java EE design patterns. It is used in order to decouple or reduce the coupling between the presentation tier and business services.   readmore
  • Service Locator
    The design pattern, service locator is an important part in software development. Looking up for a service is one of the core features of service locator. A robust abstraction layer performs this function. The design pattern uses a central registry called Service Locator.   readmore
  • Session Facade
    The session façade pattern’s core application is development of enterprise apps. You can also call it a logical extension of GoF designs. The pattern encases the interactions which are happening between the low-level components, which is Entity EJB.   readmore
  • Business Object
    Object-oriented programming makes use of the business object. It represents the parts of a business. A business object is able to represent things like event, person, business process, place, and concept. The business object can exist in certain forms like a product, an invoice, and the details of a particular part of a transaction.   readmore
  • Composite Entity
    It is one if the Java EE software-design patterns. The composite entity pattern performs modeling, managing and representing a set of interrelated persistent objects. It does not represent them as separate fine-grained entity beans. Composite entity beans are able to represent a graph of objects.   readmore
  • Transfer Object
    It is one of the Java EE design patterns. We need transfer object when we need to pass the data across various attributes in a packet to the server. Value Object is another name for transfer object. The transfer object is just a class of POJO which has a method of the getter and setter.   readmore

Integration Tier

  • Data Access Object
    The data access object in a computer software which is as an object which is responsible for providing abstract interface for communication to a specific form of database.   readmore
  • Service Activator
    The service activator design pattern is one of the Java EE patterns. It is an SI (spring integration) component. It is responsible for triggering or activating a service object or bean which is managed by the spring. A service activator searches through the message channel in order to look for messages.   readmore
  • Web Service Broker
    The web service broker uses web protocols and XML. We can use this pattern to expose and broker the services. Assume a circumstance, where multiple organizations are lined up in order to request info from a number of service providers.   readmore

Happy Design Patterns Learning with us!!!