Full Stack Java Developer Guide!

One of the challenges that  beginner Java developers face, is that they don’t know the learning path.

The below webinar, will guide you on the same. The webinar will teach you the learning path to become a highly paid full stack Java developer!

Enroll using the link below and watch the webinar.

Webinar Link : https://karpado.teachable.com/p/become-a-highly-paid-full-stack-developer

 

 

Arrays in Java Tutorial – Easy Explanation from Karpado

This tutorial is intended for beginner/intermediate java programmers, who want understand everything about Arrays in Java in easy manner with examples. After you finish this tutorial you will not only gain practical knowledge on Arrays in Java, but also solve coding problems during interview 😎

Goal(s) of this tutorial..

  • Familiarize you with  Arrays in Java with examples and coding exercises
  • Make you feel confident to solve a given Array problem during coding interviews
  • Give you satisfaction of learning something new!

But first, Why should you learn Arrays in Java?

  • Crucial for interviews. Literally there is no Java interview without Arrays.
  • Good understanding of Arrays is an absolute must, for day to day programming.

Before you proceed, make sure you have..

  1. Some knowledge on Java Programming (If you know how to write a “Hello World” program, you are good to go!)
  2. Willingness to go though this tutorial completely without distractions

Course Recommendation : 

[the_ad id=”2285″]

Here is the summery of content we will cover in this tutorial..

This tutorial on Arrays in Java will cover the following topics,

Setup requirements

You just need to have JDK installed. If you are able to run Java programs, you are good to go!

Why did Someone Introduce Arrays in Java? (Need for Arrays!)

Some random dude (Let’s call him ‘Bill’) was given with a task. He was given with a list of employee names with their salaries and was asked to find out their average salary.

Bill is a lazy guy (Like me). So instead of manually calculating the average salary using a calculator, he decided to write a program and get things fast and also to get accurate results.

The program may look something like this..

//List of employees and their salaries
int ron = 10000;
int ben = 20000;
int sundar = 15000;
-
-
int krish = 10000;

//Doing the math to find the average salary. Sum of all the salaries div by no of employees

int avgSal = (ron + ben + sundar +....+krish) / n

The above program works great, but is it efficient 😟 ? Let’s think about the following..

  1. In the above program, bill has to manually count the number of employees accurately to get the average. If he get the count wrong, the number would change. If there are 838 employees, bill has to put that exact number in the formula to get the avgSal. Obviously, it’s not practical to not make mistakes
  2. If a new employee is added, you have to update the formula as well.
  3. Takes too many lines of code and the formula gets bigger and bigger as we keep adding new employees.

The above points concerned bill and he introduced “Arrays in Java”.

Real World Example of Arrays!

Imagine that you are running a Car transport company. I mean, you take money to ship your customer car to another location.

Lets say you got 10 orders. How are you going ship them?

 

Approach 1:

You hire 10 drivers give them each car and let them drive to their destinations. But it has the following drawbacks,

  • You have to keep track on 10 vehicles and make sure they reach destination (I mean what if driver takes the car and never to see you again?)
  • You’d need to bare the fuel expenses of 10 vehicles
  • You will have to pay 10 drivers

Approach 2:

You will have a single truck that carries 10 cars and you hire only 1 driver. This will have the following advantages

  • It’s easier to track 1 large vehicle than 10 sneaky vehicles
  • You will bare fuel cost of only 1 vehicle
  • You pay only to 1 driver

Obviously Approach 2 is the best 👍

The truck has 10 car cabins named car[0], car[1], car[2], car[3],..car[9]. Car 1 will be stored in car[0], Car 2 will be stored in car[1], etc.

Now imagine that the truck has a robotic arm that will give you the car that you ask. For example, if you ask for car[0], it will drop car 1. If you ask for car[6], it will drop car 7. This is the concept on Indexing.

Ladies and gentlemen! That’s exactly what is an Array in Java (More or less. We will discuss).

Declaration and Initializing an Array

To declare and initialize a variable, we do

int ron = 10;
int ben = 20;
int sundar = 10;

The above code will create a 3 memory locations each taking 4 bytes of memory. However, the syntax for declaring an array is different and will create a huge chunk of memory in one go (Like a truck with certain capacity)

Here is how you’d declare and initialize an array,

int[] arrayName = new int[10];

Let’s break it down,

int[] -> Telling java that we want to create an array of integer type

arrayName -> Name of the Array

new int[10] -> Asking JVM to allocate a new memory of capacity 10. Each with size 4 bytes.

The above instruction is like, manufacturing a truck with capacity 10 and each of it can accommodate a vehicle of type Car. Now guess what? We need to insert values in that array (Like we insert cars in to Truck). Here’s how you do it

arrayName[0] = 10000
arrayName[1] = 20000
arrayName[2] = 30000
-
-
arrayName[n] = 20000

Even better, instead of assigning each element with array index, you can actually add them directly during array declaration and let the Java compiler do the heavy lifting. Like below code.

In this case, you don’t have to give a fixed size to the array. Java compiler will take care of replacing it with relevant code, depending on the number of elements added.

int[] arrayName = {10000, 20000, 15000..., 20000};

Let’s now introduce the code to find the average of all the values. The code may look like this.

//Loop through all the array elements in 'arrayName' and find sum of all the values by adding each other
int sum = 0;
for(int d : arrayName) sum +=d;

//Find the average using the formula. Multiply by 1.0d to make sure the result is of double value
double average = 1.0d * sum / arrayName.length;

//Print the average
System.out.println("Average : "+ average)

The above code has certain advantages over our earlier example that did not use arrays

  1. We don’t have to count the number of emplyees. ‘array.length’ will do the job
  2. Adding a new element (employee) in to array doesn’t require you to change the above code
  3. Improved no of lines of code

Java Arrays : Memory Management

Declaring a primitive variable would result in creation of memory, regardless of initialization. For example the below code will create a memory of 4 bytes (for Int) with a default value as ‘0’ (Even without assigning a value)

int var;

However, when you declare an array(Like below), it doesn’t actually create any memory unless you initialize it with a value (That’s why in Java all arrays are dynamically allocated.). Once you initialize an array however (say with int array) JVM however will automatically initialize the values to zero (for numeric types), false (for boolean), or null (for reference types).

int[] array;

In case of variables, if you have 10 int variables declared, you’re going to have 10 memory locations created. Where as if you create an array ‘int’ of size 10, it will result in creation of a huge chunk of memory with multiple segments, each of size 4 bytes (for int type).

The total size of an array is not certain and is implementation specific. But typically the size includes the number of elements you add to array, the type of the elements that you add, size of array index, etc.

Arrays are Object in Java and just as any other Object in Java, they are stored in Heap Memory. Look at the below code

int[] array = new int[8];

The above code is going to create an array of integers of size 8 and a reference of that array would be returned back. So that we can use the reference to index through this array and get items in it.

Note: Although Array is an Object time it can store both primitive and non-primitive data types.

Java Arrays : Storing Reference Types

As mentioned before, you can also store reference types in an Array. Look at the code below..

Say you have the following class,

class Employee
{
    public int emp_no;
    public String name;
    Employee(int emp_no, String name)
    {
        this.emp_no = emp_no;
        this.name = name;
    }
}

and then you have the following class

 public class ArrayExample
{ 
public static void main (String[] args) 
{ 
// declares an Array of Employee. 
Employee[] arr; 

// allocating memory for 8 objects of type Employee. 
arr = new Employee[4]; 

// initialize the first elements of the array 
arr[0] = new Employee(1,"Bob"); 

// initialize the second elements of the array 
arr[1] = new Employee(2,"Sundar"); 

// so on... 
arr[2] = new Employee(3,"Shankar"); 
arr[3] = new Employee(4,"Johnny"); 

// accessing the elements of the specified array 
for (int i = 0; i < arr.length; i++) 
System.out.println("Element at " + i + " : " + 
arr[i].emp_no +" "+ arr[i].name); 
} 
}

In this case, student objects would be created prior to creation of the array and the array will store references of those student objects. From the above code, ‘arr[i]’ will return the reference of i’th employee.

Popular Exceptions of Arrays

It’s pretty common for programmers to make mistakes and luckily Java will let you know of your mistakes right away with exceptions. Here are some of the popular Array related exceptions that I personally came across during my initial stages of my Software Developer journey

ArrayIndexOutOfBoundsException – This type of error is generated when an array has been accessed with an illegal index. In other words when an array is accessed by a negative index or more than the size of the array.

Look at this code

int[] arrayName = {10000, 20000, 150003, 20000};

Now if you ask for arrayName[3], it would return ‘20000’. But if you do either arrayName[-10] or arrayName[5] will result in ArrayIndexOutOfBoundsException.

When I take coding interviews, a lot of people aren’t careful of how they use array indexing. I ask them to grab a piece of paper and write a program to solve a given problem. Most often their code result in this exception and so I had to reject them.

Note: Sometimes you may see “IndexOutOfBoundsException” this is the parent class of both “ArrayIndexOutOfBoundsException” and “StringIndexOutOfBoundsException”

ArrayStoreException – This type of exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. Example,

int[] array = new int[8];

//Results in Exception
array [0] = "I am a great programmer!";

NegativeArraySizeException  This error is thrown when anyone wants create an array with a negative size.

Arrays as Arguments & Anonymous Arrays

Just as with any object, you can also send Arrays as method arguments. Example code below

//Declaring and initializing an Array
int[] salaries = {10000, 20000, 150003, 20000};

//Sending Array as a method argument
findMinSalary(salaries);

//Method to print the min salary in a given Array of int salaries
static void findMinSalary(int arr[]){ 

   int min=arr[0]; 

     for(int i=1;i<arr.length;i++) {

     if(min>arr[i]) 
     min=arr[i]; 

}

System.out.println(min); 
}

You can actually send an array without even declaring. They are called Anonymous Arrays

For example, you can replace this code,

//Declaring and initializing an Array
int[] salaries = {10000, 20000, 150003, 20000};

//Sending Array as a method argument
findMinSalary(salaries);

With, this code

//Sending Array as a method argument
findMinSalary(new int[] {10000, 20000, 150003, 20000});

Multidimensional Arrays in Java

A Multidimensional Arrays is simple an Array of Array’s. In other words, you create an Array that holds the references of other Arrays.

int[] intArray = new int[10];// 1D Array
int[][] intArray = new int[10][10]; //2D Array or matrix
int[][][] intArray = new int[10][10][10];//3D Array

The following code illustrates how to use a multidimensional array. You will have a nested for loop as follows

class multiDimArrayExample
{ 
    public static void main(String args[]) 
    { 
        // declaring and initializing 2D array 
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; 
  
        // printing 2D array 
        for (int i=0; i< 3 ; i++) 
        { 
            for (int j=0; j < 3 ; j++) 
                System.out.print(arr[i][j] + " "); 
  
            System.out.println(); 
        } 
    } 
}

I will be very honest here. I’ve been contributing to software industry since 2007, but I never ever came across with a situation where I need to use a multi dimensional Array.

Popular Methods of Array

Since Array is essentially a Class, it come with few utility methods. Here are some of the popular ones and this examples

Cloning of arrays

You an clone an array by using clone method(see below code) and now ‘cloneArray’ is same as creating a brand new array with the same value. In this case, there are two memory locations created.

int intArray[] = {1,2,3};
int cloneArray[] = intArray.clone();

//Will result in false as they both reside in two distinct memory locations
System.out.println(intArray == cloneArray);

This is little tricky when it comes to a 2d array though (See below). Here, a copy would be created of the array that holds the references of other arrays (sub-arrays). But, no copy would be created for sub arrays.

Both ‘intArray’ and ‘cloneArray’ would point to the references of same sub-arrays.

int intArray[][] = {{1,2,3},{4,5,6}}; 
          
int cloneArray[][] = intArray.clone();

//Will print false
System.out.println(intArray == cloneArray); 
          
// will print true as shallow copy is created 
// i.e. sub-arrays are shared 
System.out.println(intArray[0] == cloneArray[0]); 
System.out.println(intArray[1] == cloneArray[1]);

Diagram that depicts the above scenario.

Print an Array in the form of a String

You can use the Arrays ‘toString’ method to convert an array to String

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
 
// Trying to print intArray will print weird characters like 'I@a593d0s', that actually reference value
System.out.println(intArray);
 
/Trying to print intArrayStringwill print [1, 2, 3, 4, 5]
System.out.println(intArrayString);

If you have an array with Reference or Object type, and you try to print the array, then each objects ‘toString’ method would be called and what ever the code that resides in toString method of the object would be executed. If that code doesn’t print anything, you will not see anything on the output.

Create an ArrayList from an Array

Very often, you want to create an ArrayList from an Array. You can do so by calling ‘asList’ method. The following code will help for the same

Integer[] intArray = { 1, 2, 3, 4, 5 };
ArrayList<Integer> intArrayList = new ArrayList<Integer>(Arrays.asList(intArray ));

Compare two Arrays

int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 4, 5, 6 };

System.out.println (Arrays. Equals (arr1 , arr2)); //false

Int [] arr3 = {1, 2, 3};

System.out.println (Arrays.equals (arr1 , arr3)); //true

Array Length

Very often when you are asked to solve a given coding problem, you’d need to find out the length of a given array. For that purpose you can use ‘length’ attribute of Array. Look at the code below

String[] nameArray = { "Ben", "Den", "Pen" };

//Prints 3
System.out.println("Length of the array : " + nameArray.length);

Note: If you initialize and array of size 10 but you have added only 5 elements in to that array, the result of array.length would still be ’10’ regardless of number of elements added!

These are some of the methods and attributes of Array class that are popularly used. But, you are not limited to those. You can actually use external libraries to make use of those methods (Ex: Apache Commons Lang library)

Using those libraries you can do things like concatenating arrays, Converting an ArrayList to Array, reversing a given array, etc.

Reverse and Array

int[] intArray = { 1, 2, 3, 4, 5 };

ArrayUtils.reverse(intArray);

//Displays [5, 4, 3, 2, 1]
System.out.println(Arrays.toString(intArray));

Remove an element of an array

//Removes the first occurrence of the specified element from the specified array. Result ['b', 'a']
ArrayUtils.removeElement(['a', 'b', 'a'], 'a')

Popular Interview Questions on Arrays

Note: Read the question and try your best to answer on your own. If you don’t succeed, look at the answer.

Q: Describe one major drawback of an Arrays?

The size of an Array is fixed and we cannot either decrease or increase it. In some circumstances, we do not know ahead of time how many element we are going to add in to an array.

However, you can add a custom code to create a dynamic Array, or use ‘ArrayList’ instead.

Q: Can you declare an array without size?

If we declare an array without size, it will throw compile time error. The below code gives “array dimension missing” error

int[] arrayName = new int[];

Q: When will we get When will we get ArrayStoreException??

“ArrayStoreException” is a runtime exception and will be thrown when we try to insert an element of incompatible type. For example, you cannot insert String in to an Integer Array.

Q: What is the meaning of anonymous array? Explain with an example?

Anonymous array means array without any reference.

findMinSalary(new int[] {10000, 20000, 150003, 20000});

Q: When ArrayIndexOutOfBoundsException occurs?

It will occur when the program tries to access an invalid index of an array. Index higher than the size of the array or negative index.

Q: How do we search a specific element in an array?

We can use Arrays.binarySearch() method. This method uses binary search algorithm.

Q: Where is the memory allocated for arrays in Java?

Heap memory, as Arrays in Java are objects.

Q: We know that Arrays are objects so why cannot we write strArray.length()?

Arrays are object references. We can use the methods like toString () and hashCode () against Array. Length is a data item of an array and so it is not a method. That’s why we are using strArray.length to retrieve the size.

Array Coding Problems and their solutions

Now, lets try to do some coding tasks using Arrays.

Note : Take time and try to write the program by yourself on a piece of paper. If you cannot figure out the solution, you can take a look at the provided solution.

Problem : Find the missing number in a given integer array?

Example:

Input: arr[] = {1, 2, 4, 6, 5, 7, 8}
Output: 3
Explanation: The missing number from 1 to 8 is 3

Input: arr[] = {1, 2, 4, 5}
Output: 3
Explanation: The missing number from 1 to 5 is 3

Clue:

  1. create a variable sum = 1 to which will store the missing number and a counter c = 2.
  2. Traverse the array from start to end.
  3. Update the value of sum as sum = sum – array[i] + c and update c as c++.
  4. print the missing number as sum.

Java Program (Solution):

// Java implementation  
class ArrayExample 
{ 
  
    // a represents the Array 
    // n : Number of elements in the array a 
    static int getMissingNumber(int a[], int n)  
    { 
        int total = 1; 
        for (int i = 2; i <= (n + 1); i++) 
        { 
            total += i; 
            total -= a[i - 2]; 
        } 
        return total; 
    } 
  
    public static void main(String[] args) 
    { 
        int[] arr = { 1, 2, 3, 5 }; 
        System.out.println(getMissingNumber(arr, arr.length)); 
    } 
}

 

Problem : You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers.

Example:

Array = {4, 2, 4, 5, 2, 3, 1} and n = 5

The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2.

Clue:

Traverse the array once. While traversing, keep track of count of all the elements in the array using a temporary array ‘count[]’ of size n, when you see an element whose count is already set, print it as duplicate.

Java Program (Solution):

class ArrayRepElement 
{ 
    void printRepeating(int arr[], int size)  
    { 
        int count[] = new int[size]; 
        int i; 
  
        System.out.println("Repeated elements are : "); 
        for (i = 0; i < size; i++)  
        { 
            if (count[arr[i]] == 1) 
                System.out.print(arr[i] + " "); 
            else
                count[arr[i]]++; 
        } 
    } 
  
    public static void main(String[] args) 
    { 
        ArrayRepElement repeat = new ArrayRepElement (); 
        int arr[] = {4, 2, 4, 5, 2, 3, 1}; 
        int arr_size = arr.length; 
        repeat.printRepeating(arr, arr_size); 
    } 
}

Hope you enjoyed learning, I wish you a great future!

Course Recommendation : 

If you are learning Java, I highly recommend you to check out this course. One of the best Java courses online..

Complete Java Programming Masterclass – Beginner to Expert!

 

Top 5 Golden Tips to Get a Job at Google, Microsoft (From existing employees!)

You don’t have to be a Genius to get a job in Google, Microsoft, Amazon. You just need to know the right learning strategy!

Ever imagined yourself getting a paycheck from top MNC’s like Google, Microsoft, Amazon? But, you feel like it’s too hard to crack their interview?

Let me tell you something. “IT IS INDEED HARD!”.

But, I will share with you a few golden tips, that we’ve learnt over the years of experience in mentoring individuals.

Tip 1 : Emphasize more on Algorithms and Data Structures and..

It really hurts to say, but if you want to make it to these top MNC’s, then your technical knowledge is least preferred.

Yes! That’s true.

You must have a good grip on “Algorithms and Data Structures”, and be able to solve the giving problem, using the programming language of your choice.

Basically, they test “How smart you solve a given problem” than your technical knowledge.

That’s why, if you are taking training on “Alg & DS”, do make sure that the training is more of practice than just theory and you get help from instructor when required.

We always do that when we train individuals. Because, guess what! You are the one who will give the interview.

Tip 2 : You don’t have to be perfect and you don’t have to know everything!

If you are giving interviews in these top MNC’s, it’s not about “Perfection”. It’s about “How you deal with imperfections”!

It’s not expected that you answer each and every question in the interview. But, they consider how you deal with the given task, and how you approach to solve a given problem with your existing knowledge.

For example, if you are learning “Alg & DS”, there are endless concepts to learn. Do you need to learn everything that ever existed? No!

Let’s be honest. No one is perfect, including the interviewer. I mean, do you think the CEO of Google/Microsoft know everything? “Never!”

Tip 3 : Invest in Proper Training / Mentorship, or else..

A lot of people learn online for months or even years, yet they don’t make it to these top MNC’s. Why? They don’t know what they are doing!

Instead why not invest in good training from someone who has made it to these top MNC’s? So that you can get results much faster, without having to make those countless mistakes?

Even if you get 50% hike from your previous employer, it will easily payoff.

It’s also crucial who is teaching! For example, our instructors are from Microsoft, Google. Because, only if they can make it, they can guide you how.

Not to brag or something, but you can attend a free demo of our training here : Free Live demo

Tip 4 : Plan your learning!

When it comes to preparing for interview in these top MNC’s, you must plan your learning.

Failing to plan, is planning to fail!

Take a look at existing interview questions. Go through the interview experiences of other individuals and plan your learning.

But it’s always better to have someone to guide/mentor you through the process. Because, there’s just too much information out there and it’s easy to get frustrated.

Tip 5 : Never give up

It may be a bit tiresome process, but don’t lose hope. Getting a job in these MNC’s is very rewarding and you will have a better life with better income. Not you mention, you can market yourself for the rest of you life that you worked for these top MNC’s

It’s worth every effort to learn what it takes to get you there. Just imagine getting a luxury Free lunch everyday at Google 😛 !

If you are planning for an interview in tier 1 MNC’s, you can attend free demo of our training here : Free Live demo

Free Live Demo Registration!

How about a training, that is designed to deliver you results?

 

I am,

What do you look for in training?

I would prefer,

* We respect your privacy. Your contact details will never be shared or misused in any way.

Name
E-Mail
Phone
Comments (If Any)

Singleton Design Pattern in Java and Spring With Example – Easy Explanation Guaranteed!

This tutorial is intended for people who want understand everything about singleton design pattern in Java and Spring with easy example. After you finish watching this tutorial, you will not only be confident with the concept, but you can use the same example in your next interview and impress the interviewer! 😎

Also, don’t forget to add this skill in your resume! Singleton is one of the most popular design patterns in the world, or even in universe or even in the galaxy! (Hope it’s not too bad of a joke 😕)

Note : In order to keep this tutorial ‘short’ and ‘to the point’. I prefer not to show full examples initially, but only some key aspects to explain you the concept. However, in the end we will go step by step on how everything is done along with source code. Just sit back and enjoy for now. Sounds good?

Goal(s) of this tutorial..

  • Familiarize you with  Singleton design pattern in Java and Spring with examples
  • Make you feel confident with interviews
  • Help you add this new skill in your resume

Why learn Singleton Design Pattern?

  • Crucial for interviews
  • Singleton design pattern has certain advantages (You will learn them in this tutorial)
  • Understanding of Singleton design pattern is necessary to understand Spring Framework

Before you proceed, make sure you have..

  1. Some knowledge on Java Programming
  2. Willingness to go though this tutorial completely without distractions
  3. Good to have : Some understanding on Spring Framework

Recommended course(s) : Java Programming , Spring Core Framework , Spring MVC with Spring Boot

[the_ad id=”2285″]

Topics that you will understand finally..

This tutorial on singleton design pattern in Java and Spring will cover the following topics,

  • What is singleton design pattern?
  • Why use singleton design pattern & it’s advantages?
  • When not to use single design pattern?
  • Singleton in Java with code example
  • Singleton on in Spring with code example
  • Eager vs Lazy loading in spring

Video version : If you are a fan of video tutorials like me, then you can watch the video version of this tutorial which is more elaborated. Or better yet, read the article and then watch this video!

Setup requirements

You just need to have JDK installed. If you are able to run Java programs, you are good to go!

For spring example though, It’s recommended that you have some idea on Maven dependencies. Hence, we will talk about it real quick in next section (Feel free to skip the next section, if you already know maven)

A little bit about maven

This section is dedicated to familiarize you with couple of features that maven has to offer.

JDK doesn’t come with all the libraries that you’d ever need right? Chances are that, your project depends on another project or external libraries. If you are talking about large scale enterprise applications, we are talking about some big numbers.

It’s hard and unreliable to manually search the dependencies over the internet, download them, store them in local machine and then import them in to your project.

Wouldn’t it be nice if you had a tool, where all you have to do is to add an XML tag in one special file (pom.xml) , and that tool will do all the heavy lifting? I mean, the tool will download and store the libraries in the classpath on your behalf. That is exactly what is Maven.

The xml tag that you add in pom.xml may look something like this

<dependency>
     <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
     <version>4.1.0</version>
</dependency>

By specifying the above tag, we are asking maven to download Apache-POI library of version ‘4.1.0’ in to our class path. Maven will not only download the dependent library, but also the libraries that the dependent library depends on! (Sounds like a tongue twist, but it’s true!)

I found that tag with a quick google search (Surely better than me manually downloading bunch of .jar file and storing them in the classpath!)

Well actually, maven is much more than that. But, this is the feature of it, which is very relevant for this tutorial.

Forget about what is ‘groupid’,’version’ etc. That will take us to maven world. Just remember, that if we need to use another library, we’d add an xml tag in pom.xml.

If you are still disparate to learn Maven, I recommend this Maven course.

 

What’s a Singleton Design Pattern

Singleton Design Pattern ensures that you will be able to create only one Instance of a class and you will use the same instance across your application.

I am sure your sub-cautious mind is wondering ‘Why?’,’What?’,’How?’. That’s what we will discuss in the rest of the tutorial.

Creating a singleton class

Take a look at the following code..

public class SingletonExample {

	private static SingletonExample instance;

	private SingletonExample() {
	}

	public static SingletonExample getInstance() {
		if (null == instance) {
				instance = new SingletonExample();
		}
		return instance;
	}

	public void businessLogic(String message) {
		System.out.println("Executing Business logic..." + message);
	}
}

And tell me if you can create more than one instance of it? No, you can’t! Let me explain..

From the above code, you see a Private constructor. Since the constructor is not public, you can’t construct/create objects from outside the class. But, only from within the class.

With this we blocked creation of new instances. But, that’s not what we wanted. We want to be able to create an instance (Even from outside of the class) and the same instance must be used every time. Well, that’s what ‘getInstance()’ method does.

At first we are checking to see if the ‘Instance’ is null (It would be null, the first time we call it). If it is ‘null’ we will go ahead and create the instance of the same class. For all the subsequent calls, the condition won’t be met and the same instance will be returned every time.

If you want to test this, just create another class and call this method multiple times. Each time you call, try to print the Hash code of the returned instance. You’d notice that the same hash code would be printed every time.

But, we have one serious flaw in the above code. Can you guess what it is?

Well, the above class will generate multiple instances if multiple threads request for the instance at the same time. There by destroying the very purpose of singleton pattern. I mean, lets say thread t1 entered first by meeting the condition “null == instance”. Now, there is a possibility that another thread (Say t2) can enter meeting the same condition “null == instance” as it may be the case that ‘instance’ is still not created and assigned!

I mean, think about it (Again, watch video for more elaborated explanation)

So the solution is to implement ‘lock’ mechanism by using ‘synchronized’ block (This is all core java! Out of the scope of this tutorial). Code below..

	public static SingletonExample getInstance() {
		if (null == instance) {
			synchronized(SingletonExample.class) {
				if (null == instance)
				instance = new SingletonExample();
			}
		}
		return instance;
	}

 

Why Singleton Design Pattern?

Take a minute and guess why..

If you notice, we don’t have any properties in the above example. That means, the instances that we create from that class will not have a ‘State’. When an object doesn’t hold a state, they are thread safe! No matter how many threads would need an instance of the above class, they are all one and the same.

Now, here’s the thing! When you are creating the same exact instance all the time, with no possibility to change the state,  there is no reason to create multiple instances and waste memory. Instead, it’s more efficient to return the same instance (Like we are doing above)

A good example of where singleton design pattern can be used, is when you are trying to create a database connection. You don’t want to create a brand new database connection every time you fire a query. That would be very inefficient and would cost the performance.

However, if you use singleton pattern, you’d use the same connection object for every database request. There by, you will not only save the time it takes to create the instance or to creating the connection, but also precious runtime memory.

Another example of where singleton design pattern can be used is when you implement ‘logging’ mechanism in your application. You’d create one instance of logger and you’d use the same instance throughout your application to log messages.

Convinced? Sounds good?

 

When not to use Singleton Design Pattern?

As you might have guessed by now, we should not use singlton design pattern if you object holds a state. But, have you ever though why?? Think about it!

Imagine (Just for the sake of this example) that we have 3 databases d1,d2,d3 and there are 3 threads, t1, t2, t3. Lets say

t1 want’s to connect to d1

t2 want’s to connect to d2

t3 want’s to connect to d3

Also imagine that we have singleton class (Like in our previous section) that connects to a database. But this time, we will have a property that says ‘serverIP’. Each thread has to pass the server IP as the constructor argument while creating the instance of this class. So that a connection would be established using that IP.

Here’s the problem. Let’s say t1 sent the IP ‘2.2.2.2’, but before the connection logic is executed, thread t2 enters and changes the IP of say ‘3.3.3.3’..

What just happened? DISASTER!! Now both the threads will connect to ‘3.3.3.3’ ip!! Which is clearly not what we intend to do.

So, the solution in this case is simple to not use singleton design pattern and use a regular class.

An example was demonstrated in the above video.

 

Understanding Lazy vs Eager loading

So far, we are creating the singleton instances ‘On Demand’. I.e.. when you call the ‘getInstance()’ method. Not before it. This is called Lazy loading.

It’s kind of similar to you not waking up in the morning, unless someone wake you up! Or you not doing the work, unless you are asked to do.

But the opposite of Lazy loading is Eager loading. Where the instance would be created up front (Before even requesting for it) and is up for grabs.

Kind of similar to you preparing the dish before customer placed the order. Because you already knew, somebody is going to need it, and save preparation time when ordered (Nice example 😇. I deserve your ‘like’ and ‘share’ of this article 😕).

Here is the tweaked version of our singleton example, that loads the instance in Eager manner. We moved he instance creation part to a static block (Core java concept! Seriously, core java is the basis for everything. If you want to learn core java, I recommended a course above at the start of the page)

public class EagerExample {

	private static EagerExample instance;

	private EagerExample() {

	}

	static {
		instance = new EagerExample();
	}

	public static EagerExample getInstance() {
		return instance;
	}
	
	public void businessLogic(String message) {
		System.out.println("Executing Business logic..." + message);
	}
}

 

Singleton Beans in Spring Framework

By default all the beans in Spring that you define in config files are Sington in nature.

But, you have to be careful to not introduce any properties in that spring beans. In case ff you do, you must at least know what you are doing.

Alternatively, if you can configure a ‘Prototype’ bean (The opposite of Singeton). In which case, there would be multiple instances of same bean.

This is demonstrated well in the video tutorial above.

Also, all the beans are by default loaded in Eager manner. That means, all the singleton instances are created, right when the container loads. This is good for our database connection example we considered earlier.

If you want them to load in ‘Lazy’ manner, you can configure that while configuring beans. You can even go ahead and make Lazy loading the default behavior.

For example, if you are using XML configuration to define beans,  you can add the following attribute in the main tag ‘default-lazy-init=”true”‘ and you are good to go! You can also use annotation ‘@Lazy’ if you wish.

 

Source Code

Below is the example code for singleton in spring (Only includes some key files). If you want to download complete project, GitHub link is provided in the end and you check the video tutorial for detailed walk through!

package org.company;

public class SampleBean {

	private AnotherBean anotherBean;

	public SampleBean() {
	}

	public SampleBean(AnotherBean anotherBean) {

		System.out.println("Constructor of SampleBean Called!");
		this.anotherBean = anotherBean;
	}

	public void sampleMethod(String message) {
		anotherBean.displayMessage(message);
	}
}

 

package org.company;

import java.io.IOException;

import org.company.config.JavaConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyApp {

	public static void main(String[] args) throws IOException {

		// Bean config using XML
		//ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");

		// Bean config using Java
		ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
		System.out.println("Requesting for a Bean..");

		System.out.println("Hashcodes..");
		new Thread(() -> System.out.println(((SampleBean) context.getBean("sampleBean")).hashCode())).start();
		new Thread(() -> System.out.println(((SampleBean) context.getBean("sampleBean")).hashCode())).start();
		new Thread(() -> System.out.println(((SampleBean) context.getBean("sampleBean")).hashCode())).start();
		new Thread(() -> System.out.println(((SampleBean) context.getBean("sampleBean")).hashCode())).start();
		
		System.out.println("Executing behaviour..");
		new Thread(() -> ((SampleBean) context.getBean("sampleBean")).sampleMethod("Message from T1")).start();
		new Thread(() -> ((SampleBean) context.getBean("sampleBean")).sampleMethod("Message from T2")).start();
		new Thread(() -> ((SampleBean) context.getBean("sampleBean")).sampleMethod("Message from T3")).start();
		new Thread(() -> ((SampleBean) context.getBean("sampleBean")).sampleMethod("Message from T4")).start();
	}

}

 

package org.company.config;

import org.company.AnotherBean;
import org.company.SampleBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Lazy
@Configuration
public class JavaConfig {

	@Lazy(false)
	@Bean
	public AnotherBean anotherBean() {
		return new AnotherBean();
	}
	

	@Bean
	public SampleBean sampleBean(AnotherBean anotherBean) {
		return new SampleBean(anotherBean);
	}
}

Good luck!

Spring Boot Tutorial With Example – Easy Explanation Guarantee!

Spring boot tutorial is intended for beginners who are having hard time understanding what is spring boot! This tutorial on Spring Boot is made in beginner friendly way that even a caveman (or women!) should not have any problem understanding.

What’s more? After you go through this tutorial, you can add this new skill in your resume and somehow make it look appealing 🤩

Note : In order to keep this tutorial ‘short’ and ‘to the point’. I prefer not to show full examples initially, but only some key aspects to explain you the concept. However, in the end we will go step by step on how everything is done along with source code. Just sit back and enjoy for now. Sounds good?

Goal(s) of this tutorial..

  • Familiarize you with  ‘Spring Boot’ and it’s core features
  • Make you comfortable creating ‘Spring Boot’  projects
  • Help you add this new skill in your resume

Why learn spring boot?

  • It’s a must learn technology especially for building Microservices
  • Spring boot makes your life easy by eliminating the need to write boilerplate code (You will know how, in this tutorial)

Before you proceed, make sure you have..

  1. Some knowledge on Java Programming
  2. Willingness to go though this tutorial completely without distractions
  3. Good to have : Some understanding on Spring Framework & Spring MVC

Recommended course(s) : Java Programming , Spring Core Framework , Spring MVC with Spring Boot

[the_ad id=”2285″]

Topics that you will understand finally..

This spring boot tutorial will briefly cover the following concepts,

  • What is spring boot?
  • What does spring boot do?
  • Spring boot starter dependencies
  • Auto-configuration
  • Spring boot initializer
  • Using Spring tool suite
  • spring boot in eclipse
  • Spring boot example
  • Embedded servers
  • Fat Jar, Self contained jar, Runnable jar
  • Understanding Maven Dependencies

Note: Each of the above topic, deserve an article of their own.  Hence, I will only brief about them and give you a sense of understanding on why they exist. I mean, you don’t want to read a 100000 line article right?

With that in mind, let’s begin our journey to the center of the spring boot..

Video version : If you are a fan of video tutorials like me, then you can watch the video version of this tutorial which is more elaborated. Or better yet, read the article and then watch this video!

Setup requirements

You need JDK and Maven installed. If you’ve reached to a point, where you want to learn Spring Boot, then the least I’d expect is that you know how to run Java programs. Which also mean, i’d expect you to know how to install JDK.

‘Maven’ however, could be new to you. For now, you don’t have to know what it is, as we will discuss a bit about it in next section. You can install Maven just as you would install JDK by setting the environment variables (Demonstrated in spring boot video tutorial)

You’d also need an IDE. I am using the latest version of ‘Eclipse’ for the same..

 

A little bit about maven

Although this is a spring boot tutorial, you need to have some knowledge on Maven. Don’t worry, this section is dedicated to familiarize you with couple of features that maven has to offer.

JDK doesn’t come with all the libraries that you’d ever need right? Chances are that, your project depends on another project or external libraries. If you are talking about large scale enterprise applications, we are talking about some big numbers.

It’s hard and unreliable to manually search the dependencies over the internet, download them, store them in local machine and then import them in to your project.

Wouldn’t it be nice if you had a tool, where all you have to do is to add an XML tag in one special file (pom.xml) , and that tool will do all the heavy lifting? I mean, the tool will download and store the libraries in the classpath on your behalf. That is exactly what is Maven.

The xml tag that you add in pom.xml may look something like this

<dependency>
     <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
     <version>4.1.0</version>
</dependency>

By specifying the above tag, we are asking maven to download Apache-POI library of version ‘4.1.0’ in to our class path. Maven will not only download the dependent library, but also the libraries that the dependent library depends on! (Sounds like a tongue twist, but it’s true!)

I found that tag with a quick google search (Surely better than me manually downloading bunch of .jar file and storing them in the classpath!)

Well actually, maven is much more than that. But, this is the feature of it, which is very relevant for this tutorial.

Forget about what is ‘groupid’,’version’ etc. That will take us to maven world. Just remember, that if we need to use another library, we’d add an xml tag in pom.xml.

If you are still disparate to learn Maven, I recommend this Maven course.

 

What is spring boot? The first obvious question..

“Spring Boot makes it easy to create production-grade stand-alone Spring based Applications that you can ‘just run'”.

But wait!! What does that even mean?

I don’t want to explain what it means now. You will understand that definition by yourself, once you finish reading this article. But, lets us talk about some of the problems you may have to face if you are not using spring boot.

Let’s assume you are about to create a brand new application. Here are the typical steps you need to take as a developer,

  1. Create a Maven/Gradle Project in eclipse
  2. Find the required dependencies and add those tags in POM.xml
  3. Download the Tomcat Server, install it and configure in IDE (To run/test the application)
  4. Download and install Database Software and run it (If your application is Database driven)
  5. Code your application
  6. Create a config file(s). In case of spring, you’d need to define all the beans (Dispatcher servlet, View Resolver, etc)
  7. If there is a DB, you need to configure database parameters, Datasource, Entity Manager (Or for any other service)
  8. Build the project, Deploy the artifact on to the  server and run it

Can you guess what is the problem with the above procedure? It’s okay, take your time and think about it.. (I’ve already given clue!)

Well the problem here is, as a developer, you must be focused on writing your application (Step no ‘5’). But you are also forced to pay attention to the infrastructure that will help you write/run your application (The other steps).

If it’s a “Hello World!” application, we don’t have to worry much. But, imagine the time/effort/money it takes to create/manage large scale enterprise applications with millions of lines of code!

Wouldn’t it be cool if there is some tool, that will take care of all the steps mentioned above and let the developer focus on writing the application (Step no ‘5’). That is the very purpose of ‘Spring Boot’. It may sound like ‘2050’ feature, but spring boot is already doing it!

‘Spring Boot’ will allow rapid development and organizations can promise their clients faster deliveries and reach their expectations. Now you know why employers are willing to shell out some extra money to hire individuals with Spring Boot expertise.

 

Creating Spring Boot Project

There are basically 3 ways you can create a spring boot project

  1. Using Spring Tool Suite Eclipse plugin (Recommended!)
  2. Using Spring Initializr
  3. Through command processor

Whichever way you follow, ultimately it would end up in your IDE. We will talk about all of them in this section.

Creating Spring boot project using spring tool suite Eclipse plugin

Open Eclipse and then go to Help > Eclipse Marketplace, search for ‘Spring Tool Suite’ plugin. Install the one from ‘pivotal’

Once installed, go to File > New > Other > Spring Boot > Spring Starter Project. Choose it and click ‘Next’. Then you will see a prompt that looks something like this.

 

In this prompt, you will provide all the details to let ‘Spring Initializr’ (Discussed in next section) know, the kind of project it needs to create.

Server URL : URL of Sprig Initializr, we will talk about it in next section
Name : You will let Sprig Initializr know what name you want it give to your project
Type : Project management tool you are using. Maven or Gradle. In our case we are using Maven. ‘Sprig Initializr’ will create the project accordingly.
Packaging type : Defines what is the resuliting artifact that you want to create. It must be ‘war’ if you want to deploy your application on Tomcat server or it must be ‘jar’ if you want to create a self contained ‘Fat Jar’.

“Wait what!!? A FAT Jar?” 😱

I am sure you are wondering what is ‘Fat Jar’. We will talk about it in coming sections.

Group/Artifact/Version : Maven stuff!
Description/Package : You must be knowing what it is!

Click ‘Next’, and then you see something really cool!

 

Typically in maven projects, if you want to use a technology (Ex: AWS, PostgreSQL) you need to search on the internet all the list of dependencies required and then add them in to your project POM.xml.

But, Spring Boot gives you convenience. Here you simply chose the technologies that you need in your project. For example, if you use ‘PostgreSQL’ as your Database, just search for it and add it in the list, and spring will take care of downloading all the libraries that you ever need to use PostgreSQL. In our case though, we are going to keep it simple and create

The underlying concept is called ‘Spring starter dependencies’, which will be discussed on coming sections.

Note : You can hover your mouse over each of the items above and see what they offer.

Creating Spring boot project using spring initializr

I was yelling about ‘Spring Initializr’ for quite some time. Let’s get some clarity on that..

Visit : start.spring.io (Remember? This was the same URL we’ve seen while creating the project using the plugin). You will see a screen like this.

 

If you relax and observe carefully, you notice that the fields in here are the exact same fields that we’ve seen while creating the project using Spring Tool Suite plugin.

Once you enter the values here, you can click on ‘Generate the project’ button, which will download a project in .zip file.

You can import that project in to your eclipse and it is as good as creating a project using the plugin! In other words, spring tool suite plugin is doing the same job, what you’d other wise need to do without it.

Creating Spring boot project using spring boot CLI

This is by far the weirdest way to create a spring boot project. IGNORE!! Just ignore this by all means!

You need to know Groovy in order to leverage this functionality. More over, almost you will never get to create projects this way. Even more, this is going to take up a lot of real estate in this tutorial.

 

Spring Boot Starter Dependencies

The resulting project structure may look something like this..

We will explore about auto-generated SpringbootApplication.java file in a bit, but lets explore what’s happening in pom.xml file (This is where the magic happens!). In this section we will talk about ‘Spring starter dependencies’

If you open the pom.xml file, you’d notice one dependency..

 

All the dependencies that has the word ‘starter’ are spring dependencies. But before that, remember what I said about Maven transitive dependencies? It means, if you added one maven dependency,  maven will not only download that dependency, but also the dependencies that, that dependency depends on!

Look what spring initializr has added (Look above pic!) ‘Spring-boot-starter-web’. This dependency will help maven find all the dependencies that you’d ever need to start creating web applications. Because ‘Spring-boot-starter-web’ depends on all those required libraries.

This is the dependency which we’ve chosen while creating the project. If we had chosen some other starter dependency like this (Say AWS, MongoDB, etc) spring will add their corresponding start dependencies too and ask maven to download all the libraries.

Makes sense?

Spring Boot Version Management

To complement the starter dependencies, you also don’t have to specify the version of the starter dependency (I mean, there is no ‘version’ tag, like you’d normally do with maven dependencies). The magic happens with the ‘parent’ project inheritance (Feature of maven. Again, if you are disparate to learn maven, I recommend this maven course)

I mean, look at this tag in pom.xml

 <parent>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-parent</artifactId>
               <version>2.1.7.RELEASE</version>
                <relativePath /> <!-- lookup parent from repository -->
</parent>

All spring boot projects are children of a parent called “Spring-boot-starter-parent”. If you look at the pom.xml file of this parent project, it will have all the started dependencies that spring boot ever offers, “ALONG WITH THEIR VERSIONS!”.

One of the features of maven is, if you specify one dependency (Say ‘A’) and the same dependency is also present in parent project, then maven will inherit all the properties of it. In our case, all the starter dependencies will inherit versions from the parent project. So that you don’t have to worry about it.

Without spring boot, there is a chance that you come across with incompatible libraries or version mismatch issues. Spring boot solves that problem like a super man (or women!)

But! You do have to specify that parent project version though (Like above).

Makes sense my friend? We are good to go to next section?

 

Spring boot maven plugin

Another tag of significance is this

 <plugins>
               <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
               </plugin>
</plugins>

This again is a feature of maven! (Please take this damn course on Maven 🙏 Maven is common is all projects!)

But, in simple words, this plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place” (We will see how, in coming sections)

 

Writing a ‘Hello world’ Spring boot application

It’s time to buckle up and write a very miniature application logic with some basic functionality.

Note : At the end of this chapter, I will put a link to download this project.

The functionality is as follows

  • First we create a Form where the user will enter some text and click ‘Submit’ Button
  • We will have a controller to handle that request and return the same entered value along with a view
  • We will display the message on another view

Ultimately, the user will enter some text and click on ‘submit’ and then the same text will be displayed back 😛

For our purpose we are going to be using apache Freemarker for view. You could use JSP, Thymeleaf, etc as well. The first thing we need to do, is to add starter dependency of Freemarker in pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

Next is to introduce a form that the user will see when they visit our application on the browser.

This will go inside “Springboot\src\main\resources\templates”

<!DOCTYPE html>
<html>
  <body>
    <form action="/Springboot/hello" method="get">

      <input type="text" name="name" /> <input type="submit" />

    </form>
  </body>
</html>

Next we are going to introduce the controller logic that will handle the request.

This will go inside “Springboot\src\main\java\com\company\Controllers”

@Controller
public class HelloWorldController {

@RequestMapping("/hello")
public ModelAndView showMessage(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {

   ModelAndView mv = new ModelAndView("hello");
   mv.addObject("name", name);
   return mv;

}
}

Talking about this is more of a Spring MVC concept and will need tutorial of it own. Hence, I won’t go too much in tot it. But, at a high level, when the request URL has the string ‘hello’, that request would end up in this method.

Here we are trying to read the form data entered by the user and returning ModelAndView object. Model will have the user entered data and the view will take that data to display. The view that we are trying to use is with the name “hello”.

If you want to learn spring MVC, here is a nice course on the same Spring MVC with Sprig Boot

Finally, let’s also introduce the ‘hello’ view. This will go under “Springboot\src\main\resources\templates\hello.ftl”

<!DOCTYPE html>
<html>
<body>
<h3> ${name}</h3>
</body>
</html>

The above code just displays the model data. The code looks cute though 😚

 

Running our application!!! Yes, that’s true!

We are good to go and run our application and of course, see it working! You don’t have to do anything, that’s why spring boot came in to existence.

What’s even more cool is, you don’t even have to build the application and then deploy the artifact on tot he tomcat server. Everything will be taken care by Spring Boot!

Note : We will talk about the internals and how it works, but let’s launch our application and get a sense of satisfaction.

All you need to do is to run the file SprinbootApplication.java (It has main() method in it!), just as you’d run any other java program. Once you do, you will the following result on the console

You see the Tomcat server started at port 8080. Spring had initialized web application context & root application context (Basically, just check the output above and see if sounds familiar)

Visit : localhost:8080, you will see a user form

 

Enter something and click ‘Submit Query’ and you will see the same message getting displayed.

 

@SpringBootApplication annotation that does the magic!

If you open the file SpringbootApplication.java that was auto-generated, you’d notice an annotation “@SpringBootApplication”. This annotation is actually combination of multiple other annotation,

 

@springBootConfiguration – Is equivalent to @configuration annotation in spring MVC. Where you’d define all your beans.

@EnableAutoConfiguratoin – This annotation does some stuff that sounds futuristic. “IT WILL AUTO CONFIGURE COMPONENTS BASED ON THE STARTER DEPENDENCIES”

Look! Have we configured Dispatcher Servlet? Have we configured a View resolver? No! Because, Spring boot is aware of the starter dependencies and based on that it made a guess on what are the components required and created them for us!

Even if you were to add another starter dependency, may be an ORM framework like Hibernate, you don’t have to configure the DataSource, etc. In some instances, you don’t even have to configure Database parameters!

Note : If you wish you can override the auto-configurations. But, we won’t discuss now.

@ComponentScan – This annotation will enable Spring boot to automatically discover and configure all the beans that are annotated with spring component annotations like @Controller, @Service, @Component, @Repository, Etc.. (These are all Spring MVC concepts)

Ignore other annotations, they are not so important at the moment.

You also notice an instruction in the class that says SpringApplication.run(..). It is this statement, that will kick start everything.

 

Creating a Fat A** jar (Finally!)

A** -> APP

Usually in production environment, you don’t tend to run a java program. You’d build a jar/war archive and run it.

Right click on the project > Run As > Maven build > Type the goal as ‘Package’ and run.

Under ‘target’ directory, you will see a jar file.

Run the command : java -jar <Path to jar file location>/filename.jar

It would launch our application and you can access it from your browser. Internally, it would call the ‘main()’ method.

Unlike typical .jar files, this jar files has many things in it. It has Embedded servers, Libraries, Database (If we had one!), etc. Literally everything to run your application. Hence, making it a ‘Fat Jar’ or a ‘Runnable Jar’ or ‘Standalone application’.

 

Understanding what is Spring Boot now..

 

Look! These are the steps we had to take care of, without spring boot..

  1. Create a Maven/Gradle Project in eclipse
  2. Find the required dependencies and add those tags in POM.xml
  3. Download the Tomcat Server, install it and configure in IDE (To run/test the application)
  4. Download and install Database Software and run it (If your application is Database driven)
  5. Code your application
  6. Create a config file(s). In case of spring, you’d need to define all the beans (Dispatcher servlet, View Resolver, etc)
  7. If there is a DB, you need to configure database parameters, Datasource, Entity Manager (Or for any other service)
  8. Build the project, Deploy the artifact on to the  server and run it

And, these are the steps we had to take care of, with spring boot..

  1. Create a Maven/Gradle Project in eclipse
  2. Code your application

Be happy that Spring boot allowed us to take care of steps ‘1’ & ‘5’. Otherwise, we would not have jobs today.

Now, let’s me put the definition of Spring Boot, and you’d understand what it means, by yourself..

“Spring Boot makes it easy to create production-grade stand-alone Spring based Applications that you can ‘just run'”.

This Spring boot tutorial has now helped you familiarize with these concepts..

  • What is spring boot?
  • What does spring boot do?
  • Spring boot starter dependencies
  • Auto-configuration
  • Spring boot initializer
  • Spring tool suite plugin
  • Hello world with spring boot
  • Embedded servers
  • Fat Jar, Self contained jar, Runnable jar

 

Congrats! Wish you good luck, and hope to see you soon!