Java 8 language features in Nutshell - Part 1


Hello Friends,

It has been quite long when Java 8 was released and now it is getting used more and more. In this post, we will discuss following topics of Java 8.

1.Functional Interface
2.Lambda expression
3.Default Methods




1. Functional Interface


What is Functional Interface?

Interface with one and only one abstract method is a Functional Interface, as it is representing exactly one functionality. However, a functional Interface can have n number of default as well as static methods.

The syntax for Functional Interface


 It is just like any other interface. The only difference is that it should have
@FunctionalInterface annotation at the top.

 @FunctionalInterface
  interface fly {

  }

Also, we need to understand that, even if we don't use @FunctionalInterface annotation, but an interface has only one abstract method, then by default that interface will be treated as Functional Interface, but it is always recommended to use @FunctionalInterface annotation for a functional interface.

The advantage with putting @FunctionalInterface annotation is that today you might define an interface as Functional Interface by having only one abstract method in it without using @FucntionalInterface annotation and keeping in mind that lambdas can be written for this Functional interface,but if you have big project with lots of developers working on that project, then there are great chances that later someone can add another method to your Functional Interface which then will  not actually remain Functional Interface as it will have more than one abstract method and at the same time, it will break all the already written lambda expressions as well.

So if your intention is to write an interface using which lambdas can be written, better mark it with @FunctionalInterface.

Main Purpose of Functional Interface

The main purpose of introducing Functional interface in Java 8 is to allow writing a lambda expression against the Functional Interface as lambda expression method signature is validated against the Functional Interface's method.

Example of Functional Interface


@FunctionalInterface
public interface Calculator {
   int add(int a,int b);

}

public class Test {
  public static void main(String[] args){
      Calculator calculator = (a,b) -> a + b;
      System.out.println("Sum is:"+calculator.add(4,6));
  }

}

There are many inbuilt Functional Interface which has been added in JDK 1.8 in the java.util.function package, which can be used to write a lambda expression.

Predicate
Consumer
Supplier
Function

2. Lambda expression

What is Lambda expression?

Lambda expression in simple words is the implementation of the Functional Interface method. Normally we write implementations in the methods, but in case of lambda's, there is no method in which it is written so we can think of lambda expression as an anonymous function i.e. a function with implementation but without any name.

The syntax of Lambda expression?


(Comma separated parameters )  + arrow symbol + single  expression or block of statements;

Main Purpose of Lambda Expression

The main reason to introduce Lambda expression in Java 8 was to enable Functional Programming in Java. Before Java 8, If we wanted to have some functionality which we wanted to execute inline, like on click of a button and this code did not make sense to be put in a separate class, we were doing that by creating an anonymous class. In these cases, we are usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. The problem with anonymous class is that even if we are having a very small implementation, code written using anonymous class is very verbose and unclear. With lambda expression, we can write code in more readable and concise manner.

Example of Lambda expression

Let us see how to write a lambda expression.
From above example, we have following interface

@FunctionalInterface
public interface Calculator {
   int add(int a,int b);

}

Lambda expression derives it's signature from the method of the Functional interface, so using add method's signature we will write our first lambda expression. Left side within the parenthesis we will have parameters, then arrow symbol and then a block of statement.

(int a,int b) ->{ 

   return a + b;
};

if you look at it closely, it is method definition without any method name. Say it would have a name, then it would have looked like as below after removing arrow symbol :

add(int a,int b) { 
   return a + b;
};

Now to convert it into Lambda, Java designers removed name i.e. add and put an arrow symbol after parameters, such that it became as below :

(int a, int b) ->{ 
   return a + b;
};

Now because compiler checks for the signature of the lambda expression by matching it with the signature of the Functional Interface method, so the compiler can guess the type of the parameters passed in the lambda expression by checking against the Functional Interface method. So we can remove types from parameters, such that our modified lambda expression will look like as below :


(a,b) -> { 
   return a + b;
};

Apart from guessing the type of the parameters, the compiler will also get to know that this lambda expression is going to return int value by looking at the return type of method declared in the Functional Interface, so we can remove return keyword as well.

(a,b) -> { 
   a + b;
};

Now because in above lambda expression we have only one statement in the block, we can get rid of the braces as well, so modified lambda will look like as below :

(a,b) -> a + b;

3. Default Methods in Interface

What is Default Method?

Default methods are the methods with some default implementation which can be defined in an interface.

Before Java8, we could not have methods with definitions in the interface, however with Java8, we can have methods with the definition as well in an interface, but these are special kind of method, in the sense that they have default keyword in their signature.

The main purpose of introducing Default Methods

The main reason for adding default method in Java is to make code backward compatible, even when new method(s) are introduced in the already existing interfaces because if default methods do not exist and we try to add a new method in an already existing interface, it will break all the implementation classes, as those existing implementation classes have to implement the newly introduced method(s) in the interface.

The syntax for Default Method

public interface InterfaceTest{
   default public void testDefault(){

   }
}

Example of Default Method

The iterable interface which is there since JDK 1.5 has got following new default method in it in JDK 1.8 release. Now as Collection interface extends this iterable interface and collections like List, Set extends Collection interface, this method is available to these collections by default to iterate over the elements of these collections.


public interface Iterable<T> {
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }

    }
}

if this method would not have been default, and it would have been added to Iterable interface, it would have forced all the classes which are implementing this interface (via Collection interface) to implement this method and hence, would have broken all those classes. So to make code like forEach method work without breaking the existing code, default methods are introduced in JDK 1.8.

Thanks for reading Java 8 language features. Please share it, if you think it was useful so that others can also benefit from it.

How to Create Spring Boot Project With Spring initializer

Hello Friends,

If you have used Spring framework previously, you must be aware that it takes some genuine effort to even get started with basic Spring functionality.With Spring Boot, that initial hassle is gone and you can get started in minutes.

Welcome to the world of Spring Boot!!!



In this tutorial, we will see various ways in which we can create a Spring Boot Project.

Basically, there are following four ways in which we can create Spring Boot Project :

1. Using Spring.io initializer 
2. Using Eclipse or any similar IDE and Maven simple project
3. Using Spring Tool Suite
4. Using CLI

This tutorial will focus on creating Spring Boot project using Spring.io initializer.

1. Spring Boot Project using Spring.io initializer


Steps :

Step 1:

Open URL: http://start.spring.io/



As we can see in above screenshot(you can refer extracted part below) screenshot that by default, it says that Generate a <Maven Project> With <Java> and Spring Boot <1.5.0>


But there are options to Generate a <Gradle Project> with <Kotlin>/<Groovy> and Sprig Boot<Lower versions> as well as per our requirements.

In this tutorial, we will focus on Maven with Java and Spring Boot 1.5.10.

Step 2:

As we are creating a Maven project and we know that every Maven project has group and artifact id, so this interface provides us with placeholders where we can enter group and artifact id.

We will enter the following as group and artifact id :

group       : nl.blogspot.javasolutionsguide.springboot
artifact Id : springBootApp


  Step 3:

  Click on the "switch to the full version" hyperlink, which is just below Generate Project button.

 Step 4:

You will notice following additional fields :

Description: This is simply the description of the project.You can change it as suitable but it does not make difference from the technical front.

Package Name: This is a name of the package that will be created by Spring by default when Spring boot project will be created using this GUI of start.spring.io.

Packaging: This represents how the project will be bundled as a deliverable.Here we have two options :

Jar   - Java Archive
War - Web Archive

We are going with Jar option.

Java Version :

As of writing this tutorial, we have three options 7,8 and 9.I will go with the default which is Java 8.


Step 5:

Scroll down on the start.spring.io web page and you will find below a list of dependencies which you can add in your application depending upon the requirements.Here we will add only Web dependency.For that, you just need to tick that dependency and once you will click on Generate Project, this dependency will be added to the generated project.


Step 6:

Click on Generate Project and you will see that project will be downloaded and Zip on your hard drive with the name which you would have given in Artifact text box.



Step 7:


Extract project using WinZip and import in Eclipse as Maven Project by right clicking in Package Explorer and then select import... -> Existing Maven project ->Next -> Chose extracted project from the hard drive -> Click Finish.


Step 8:

You will see a java project as per Maven standard is there in eclipse.And with this, you have already set up a Spring Boot project in Eclipse.Easy.... right.




Step 9:

Let's explore the project that has been created.

- Open Pom.xml and you will find that Pom is created with the following project co-ordinates as we       defined in GUI

 <groupId>nl.blogspot.javasolutionsguide.springboot</groupId>
 <artifactId>springBootApp</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <packaging>jar</packaging>

 <name>springBootApp</name>

 <description>Demo project for Spring Boot</description>

- Following parent has also been added automagically(note the word, it is Spring Boot's magic :)).

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

</parent>

It will make sure that following Maven dependencies are added to the project.You can try removing spring-boot-starter-parent from pom.xml and save the project and you will notice that all your following dependencies will be gone.




- In above list of dependencies, you must have noticed that spring boot has also added dependencies for embedded Tomcat so that you need not to install or configure tomcat in your eclipse explicitly.


- Also, you will find following properties, dependencies and plugin added automagically.Remember that as we selected Web in start.spring.io GUI,dependency spring-boot-starter-web has been added in POM file.

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
 </properties>

  <dependencies>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
  </dependencies>

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

- If you open src/main/java, you will see that package which we mentioned in start.spring.io GUI has been created, which is "nl.blogspot.javasolutionsguide.springboot.springBootApp"

- Within the above-mentioned package, you will find a class SpringBootAppApplication.So basically a class with the name as  <Name of your Project> with "Application" word appended to it is created in the specified package.

@SpringBootApplication
public class SpringBootAppApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootAppApplication.class, args);
}

}

- The @SpringBootApplication annotation used at the class level above is basically equivalent to combined following three annotations :

@Configuration
@EnableAutoConfiguration
@ComponentScan

We will discuss more on these annotations in subsequent tutorials.

- From the main method of SpringBootAppApplication ,SpringApplicaiton class's run method is called. This method makes sure that Spring application's applicationContext(the Spring Container) is initialized. Spring boot uses AnnotaionConfigApplicationContext.

 public static void main(String[] args) {
     SpringApplication.run(SpringBootAppApplication.class, args);

 }

Step 10:

Run the main method of SpringBootAppApplication and you will notice that jar is automatically deployed to embedded Tomcat server and Tomcat server has been started at port 8080.

Check Console log of eclipse:

Step 11:

Now as our code is deployed on Tomcat and Tomcat is up and running, Let us try to hit 8080.

oh...Error Page and it says that "This application has no explicit mapping for /error, so you are seeing this as a fallback."




Step 12:


Let us go ahead and add mapping for /error by creating ErrorHandlerController under new package
nl.blogspot.javasolutionsguide.springboot.controller.

@RestController
public class ErrorHandlerController implements ErrorController{
private static final String PATH = "/error";
@RequestMapping(value=PATH)
public String error() {
return "Error Handling";
}

@Override
public String getErrorPath() {
return PATH;
}


}





















Please note that this controller needs to implement ErrorController interface which is provided by Spring Boot and we need to implement it's getErrorPath() method.


Also as I told earlier @SpringBootApplication already include @EnableAutoConfiguration, that means that we don't need to do all configurations which otherwise we would have to do to handle request via Rest controller like configuring DispatcherServlet.

Also note that ,as we have created this controller in new Package and by default Spring is going to check only nl.blogspot.javasolutionsguide.springboot.springbootapp package,we need to tell spring that this new package should also be scanned.For that we need to add following in the SpriingBootAppApplication class at the class level:


@ComponentScan({"nl.blogspot.javasolutionsguide.springboot.springBootApp","nl.blogspot.javasolutionsguide.springboot.controller"})

So SpringBootAppApplicaiton class will look like below now :

@ComponentScan({"nl.blogspot.javasolutionsguide.springboot.springBootApp","nl.blogspot.javasolutionsguide.springboot.controller"})
@SpringBootApplication
public class SpringBootAppApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootAppApplication.class, args);
}

}

Step 13:

Now run the SpringBootApplication class again  and now if we hit 8080, we will get "Error Handling" on Web page as below :

Similarly, we can have n number of controllers as per our requirements in our project and can handle the request and send valid responses back to a web page.

That's all Friends on How to create Spring Boot project with Spring Initializer. In subsequent tutorials, we will go through other ways to create Spring boot project. Subscribe for getting next tutorials right in your mailbox.

Thanks for reading. If you liked it , support me by liking our Facebook page and sharing this post.

Why We Should override hashCode method when we override equals method

Hello Friends,

In one of my previous post, I wrote about Why Should we override equals method in Java.In this article, let us try to find out Why overriding hashcode method is important and must when we override equals method.


Top 25 Unix Commands With Examples

Hello Friends,

In this tutorial, we will learn top Unix commands which are handy in day to day work, especially from Java developer point of view.



1. How to create a new file in Unix

    touch <fileName>
 
    Example :
    touch abc.txt

2. How to see content of file in Unix(without able to edit)

    cat <FileName>

    Example :
    cat abc.txt

3. How to open file in editor mode

    vi <File Name>

    Example :
    vi abc.txt

4. How to edit File and add content in File in Unix

    a) Open file with following command
        vi abc.txt
    b)   Press I ,it will bring file in edit mode.
    c)   Type whatever you enter in file.
    d)   Type :wq! and enter.This will save content you entered in file.

5. How to find a File/Directory with name starting with particular character in Unix

   ls -ltr | grep <character>*

   Example : Find file/directory starting with name "ab"
   ls -lrt | grep ab*  

6. How to give/change permissions of File or Directory

   File permissions in numeric format and their meaning :
   0 – no permissions
   1 – execute only
   2 – write only
   3 – write and execute
   4 – read only
   5 – read and execute
   6 – read and write
   7 – read, write and execute

  By default, when we create a File in Unix ,it is created with permission 666(read/write).
  By default, when we create a Directory in Unix, it is created with permission  777(read/write/execute).
Along with numeric notation, Unix permissions can also be represented by following characters:

Reference       Class      Description

u                     user        the owner of the file
g                     group     users who are members of the file's group
o                     others     users who are not the owner of the file or members of the group
a                     all           all three of the above, is the same as ugo
r                     read         read a file or list a directory's contents
w                   write        write to a file or directory
x                    execute    execute a file

6.1. How to make File read only in Unix

    chmod  <permission> <fileName>
  
    Example :
    chmod 444 abc.txt

6.2. How to give File Read/Write/Execute Permissions in Unix

    chmod <Permission> <FileName>
 
     Example :
    chmod 777 abc.txt

7. How to find list of all the links in a directory in Unix

    ls -lrt | grep "^l"
    ^ - This signifies start of each line
    l  - Each symbolic link has "l'' in the beginning of line like below :
    lrwxrwxrwx  1 gg99a weblog 3 Dec  9 22:20 latest -> 1.3
   So this command prints all lines from result of ls -lrt,which starts with "l" and all symolic link's lines      start with "l", hence the result.

8. How to see content of current directory

   ls

   This will not give details about Files or directories.

9. How to see content of current directory with details such as
   - the exact size of the file
   - who owns the file
   - who has the right to look at it
   - when it was last modified.
 
   ls -lrt

10. How to see all files  including the ones whose filenames begin in a dot
  
      ls -a
 
     This however does not give details as mentioned in point 9.

11. How to see List of all background process
 
     Jobs

12. How to bring a background process to foreground
 
     Fg

13. How to kill a process

      kill <ProcessId>

14. How to see current date in Unix

      date

15. How to see History of commands executed
 
      history
 
      Using only "history" will give you all the commands executed in current session.
      If you want to see specific type of command, use grep along with history as below :
   
      For example ,if you have executed command to create directory multiple times, you can  execute       history command as below. It will list mkdir command all the times you have executed previously  in current session.

     history | grep  mk

16. How to clear the console in Unix
 
     clear

17. How to check ,how much space is left on the current drive in Unix

     df -h

18. How to see which process is taking how much time in Unix

    top
  
    Press shift + O to get all options by which you can sort.For example ,to sort by PID,press 'a' and          then  press any key.It will sort all the processes by PID.

19. How to copy File from one host to another in Unix
   
19.1 When you are sending files from current machine to remote machine
  
        scp <current machine path to file,which we want to send to remote machine> user@remote                  machine:/remote path
  
    Example : scp /var/log/was/abc.txt GA99@test.com:/var/log/remoteDirectory

19.2 When you want to retrieve file(s) from remote machine
  
        scp user@remote machine:/remote path to file  <current machine path where we want to                      download the file>
     
        Example :

        scp user@remote machine:/var/log/remoteDirectory/abc.txt  /var/log/was

20. How to find ,how many times a word is there in File

    grep -c  <word to find> <FileName>
    Example :
    grep -c Hi abc.txt
    Above command will give count of word Hi in File abc.txt.

21. How to execute previously executed command in Unix

      !<Previous Command>
     This is really handy when your command includes lots of parameters and options.You need not            type all those parameters and options again with this shorthand.
 
     Example : Say I executed following command:
 
     ls -lrt | grep abc

    Now I want to execute this command again, I just have to type following to execute above                  command again :

   !ls
22. How to find all the files with certain content in Unix

      find . –name <type of files to be searched> | xargs grep <content to be matched>
  
      Example :
    
      find . -name "*.txt" | xargs grep "Hi"

23. How to find file(s) which have been modified since last day, today or more than 1 day

  23.1 Find all files in current directory and sub directories which has been modified exactly 1 day                back.

         find . -mtime 1

23.2  Find all files in current directory and sub directories which has been modified more than 1 day before.
   
        find . -mtime +1

23.3) Find all files in current directory and sub directories which has been modified less than 1 day before.

       find . -mtime -1

24. How to create Soft link in Unix

     ln -s <Directory which soft link will point to> <Soft link name>
 
     Example :

     ln -s 1.0 latest
  
    So here you are pointing latest soft link to directory 1.0.

24. How to update Soft link in Unix
 
      ln -nsf <New directory> <Soft link>
 
      Example : Say you want to point latest now to new directory 1.1,then you will execute following                         command :

    ln -nsf 1.1 latest

25.How to remove Soft link in Unix

    rm <Soft link name>


Thanks for reading.Share it with someone for whom you think it will be helpful.

How to see maven dependency hierarchy of an artifact in Eclipse

Hello Friends,

In this post,we will learn that how to see maven dependency hierarchy of an artifact in Eclipse.

How to Setup Maven on Mac

Hello Friends,

In this post,we will learn how to setup maven on Mac machine.

How to create new Git Repository and host it in Bitbucket


What is Git ?




While working in a team which involves multiple developers,it is very much necessary to use a Version Control System.

How to create Soap Web Service in Java with Example

Hello Friends,

In this tutorial,we will learn how to create Soap based Web Services in Java language.



Before we deep dive into that,let us understand what Web Service is actually.

                  Web Service = Web + Service

Web Service as its name implies is service provided over web.

How to migrate from Jersey 1 to Jersey 2 on Websphere

Hello Friends,

In this tutorial,we will see how to migrate from Jersey 1 to Jersey 2.

Here I am taking example of Jersey 1 version 1.18.3 and Jersey 2 version 2.23.2.

Why Should we override equals method in Java

In this tutorial,we will try to understand need for overriding equals method in Java.