Saturday, 21 April 2018

Check NullPointerException in jdk 8 - Use Optional



How to handle NullPointerException or null check in jdk 8 ? Checking null in jdk 8 using Optional<T>.

NullPointerException is most common exception which each developer need to handle. Its very common while you are playing around many object. Before JDK 8 , it was a tedious task and lots of boilerplate code you need to write to handle this NullPointerException. But, after JDK 8 it Make your code more readable and protect it against null pointer exceptions. This API will help to write cleaner and more readable code , with intelligence to handle null check internally.

Below Example has few demonstration , how to use the Optional<T> api to avoid NullPointerException. You can handle Null check for your object.


Employee.java


package com.javadevelopersguide.tutorial.jdk8;
/**
 * Employee Object
 *
 * @author manoj.bardhan
 *
 */
public class Employee {
private String empName;
private int age;
private Address empAddress;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}


Address.java

package com.javadevelopersguide.tutorial.jdk8;
/**
 * Address Object
 *
 * @author manoj.bardhan
 *
 */
public class Address {
private String homeUnitNo;
private String streetNo;
private String city;
public String getHomeUnitNo() {
return homeUnitNo;
}
public void setHomeUnitNo(String homeUnitNo) {
this.homeUnitNo = homeUnitNo;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}



NullPointerCheck.java


package com.javadevelopersguide.tutorial.jdk8;
import java.util.Optional;
/**
 * This Example demonstrate how to use JDK 8 Optional<T> Api
 *
 * @author manoj.bardhan
 *
 */
public class NullPointerCheck {
public static void main(String[] args) {
String empName = null;
/**
* Before jdk 8, This will print "Print null"
*/
if (null != empName) {
System.out.println("Print not null");
} else {
System.out.println("Print null");
}
/**
* Before jdk 8, throws NullPointerException
*/
try {
if (empName.equals("SomeThing")) {
System.out.println("Print SomeThing");
}
} catch (Exception e) {
e.printStackTrace();
}
/**
* So Now , jdk 8 provides easy and clean API i.e Optional<T> for
* handling this type of scenario.
*/
Optional<String> optionalString = Optional.ofNullable(empName);
if (optionalString.isPresent()) {
System.out.println("Employee Name ::" + empName);
}
/**
* How to work with your own objects.
*/
Employee employee = new Employee();
employee.setEmpName("Peter");
Optional<Employee> optionalEmployee = Optional.ofNullable(employee);
if (optionalEmployee.map(Employee::getEmpAddress).isPresent()) {
System.out.println(employee.getEmpName() + "-  Address is registered");
} else {
System.out.println(employee.getEmpName() + "-  Address is  null");
}
Employee employee1 = new Employee();
employee1.setEmpName("Mark Garret");
Address address = new Address();
address.setCity("Sydney");
employee1.setEmpAddress(address);
Optional<Employee> optionalEmployeeWithAddress = Optional.ofNullable(employee1);
if (optionalEmployeeWithAddress.map(Employee::getEmpAddress).isPresent()) {
System.out.println(employee1.getEmpName() + "-  Address is " + address.getCity());
} else {
System.out.println(employee1.getEmpName() + "-  Address is  null");
}
/**
* Use Optional.empty() for set the default value for an object.
*/
Employee empObject = new Employee();
System.out.println("Returns Optional empty Value ::" + Optional.empty());
/*
* Optional.of() method doesn't handle NullPointer, be careful of this
* method while using.Always use the ofNullable() before null check.
*/
System.out.println(
"Returns Optional empty Value ::" + Optional.of(empObject).map(Employee::getEmpAddress).isPresent());
}
}

Out Put:-

Print null
java.lang.NullPointerException
at com.javadevelopersguide.tutorial.jdk8.NullPointerCheck.main(NullPointerCheck.java:48)
Peter-  Address is  null
Mark Garret-  Address is Sydney
Returns Optional empty Value ::Optional.empty
Returns Optional empty Value ::false



I have used below methods from Optional<T> :-

empty() - Returns an empty Optional instance


of() - Returns an Optional with the specified present non-null value.


isPresent() - If a value is present, invoke the specified consumer with the value, otherwise do nothing.


map() - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.


ofNullable() - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.


There are few more methods are there, you can give a try. Below link will give you a complete information. Read more about the Optional<T> by JDK 8.

Hope it will help you.

Thursday, 15 March 2018

Spring Boot Hello World Program

Developing your first Spring Boot application is quite easy. As we know Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". Its basically to minimize the configuration. 

In this example I have used below frameworks and tools for this example.

1. Maven 3.3.9 
2. JDK 1.8
3. Eclipse IDE
4. spring-boot dependency 



First step - In eclipse create a maven project  "hello-world-spring-boot" as below .


Then add the dependency for spring-boot and plug-in in the pom.xml file.


Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javadevelopersguide.www</groupId>
<artifactId>hello-world-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>This is a hello world example with Spring Boot.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

</plugins>
</build>
</project>
Then create a controller class "HelloWorldController" with a rest api method sayHello()

HelloWorldController.java
package com.javadevelopersguide.springboot.example;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 *
 * @author manoj.bardhan
 *
 */
@Controller
@EnableAutoConfiguration
public class HelloWorldController {
@RequestMapping("/hello")
@ResponseBody
public String sayHello() {
return "Hello World Developer!!!";
}
}
I have use below annotations in my controller. Here in this example the uri path is /hello

@Controller - This is used to specify the controller , as its spring framework basic.
@EnableAutoConfiguration - This enable auto configuration for Application Context. 
@RequestMapping - This is used to map to spring mvc controller method.
@ResponseBody - Used to bind http response body with a domain object in return type.Its behind the scenes. 

Now , my controller is ready.Just I need a luncher , who can lunch my spring boot application. I have created a "SpringBootApplicationLuncher".

SpringBootApplicationLuncher.java


package com.javadevelopersguide.springboot.example;
import org.springframework.boot.SpringApplication;
/**
 * This Luncher for my spring boot application.
 * @author manoj.bardhan
 *
 */
public class SpringBootApplicationLuncher {
public static void main(String[] args) {
SpringApplication.run(HelloWorldController.class, args);
}
}

Now you can run this luncher to start the spring boot application.Then, you can see the below screenshot showing the tomcat is started. As you know spring-boot is embedded with tomcat feature.



Now , your application is up and running . I have highlighted above that the tomcat is started on default port 8080

Try this tomcat URL, which is running now :- http://localhost:8080/hello




Alternatively , Also you can also start your spring-boot application on command line (Terminal). I have used windows OS.

You can use the below Maven Command  to build and run this spring-boot application :- 


1. Build the application :- mvn clean install



2. Run the application :- mvn spring-boot:run




 Now the service is running on tomcat port 8080 .Use the below URL to access the sayHello() api.

http://localhost:8080/hello


Hope it will help you.

Sunday, 11 March 2018

Write a program to reverse a string using recursive method


The below example is to reverse string in java using recursive method.



package com.javadevelopersguide.www;
/**
 *
 * This Program will help you to reverse the string using recursive manner.
 *
 * @author manojkumar.bardhan
 *
 */
public class ReverseStringRecursive {
String resultString = "";
public static void main(String[] args) {
ReverseStringRecursive rec = new ReverseStringRecursive();
String inputString = "javadevelopersguide";
System.out.println("Input String::" + inputString);
String stringRev = rec.callReverse(inputString);
System.out.println("New Result String::" + stringRev);
}
private String callReverse(final String str) {
if (str.length() == 1) {
return str;
} else {
resultString += str.charAt(str.length() - 1)
+ callReverse(str.substring(0, str.length() - 1));
return resultString;
}
}
}

How can I edit / fix the last git commit's message?

How can I edit / fix the last git commit's message?

Amending any message to your git or bit-bucket is quite easy. Normally sometime, a developer need to modify the last committed message in git/bit-bucket. Git command is providing easy commands to achieve this. Follow the below steps with attached screen shot and you can do this.

Just pull your working branch , where  you want to modify the last commit. But, make sure you want to modify your last commit for the working branch.I have bit-bucket in this example post.

Command Syntax:-


git commit --amend -m "Your Amend Message"
Then use the below command to push your changes.
git push -f  origin master

Example , as per the attached screenshot. I have used the command prompt for this example. In the below example , I have updated the new message "Amending new message". Then, push  (used -means --force) the message to git/bit-bucket. Use the below screenshot as reference. 


bit-bucket command - Java Developers Guide
Bit-Bucket amend


Now, you can see in bit-bucket the last committed message. The last message I have modified , its reflecting.


bit bucket amend
Bit-Bucket web view


Hope it will help you.



Follow for more details on Google+ and @Facebook!!!

Find More :-

Monday, 26 February 2018

Wells Fargo Java interview questions for 4-8 years experience

Java/J2ee interview questions asked by Wells Fargo for 4-8 years of experience. These interview questions had asked in the 1st round of technical interview.


1. About your current project.
2. What is Abstract class and interface, when we need to use them.
3. What is the significance of concurrency api ? What are the api you have used ?
4. What is difference between Hashmap and Hashset.
5. What is use of Linked list over ArrayList
6. What is Concurrent Hashmap? Give me the internal implementation of Concurrent HashMap.
7. Can we declare final inside abstract class and interface both.
8. Tell some critical situation in your current project or solution,you have handled. 
9. Give a design level understanding on abstract class and interface implementation.While design, you need consider the system scalability, robustness , few software designing principle.

10. Write a utility using some design pattern ?
11. Write your own hibernate dao and impl for persist and update the record.
12. Which Jar we need for spring annotation.
13. What is importance of @RestControllor ?
14. What is the underlined design pattern implemented in hibernate ?


Monday, 12 February 2018

How to add copyright to Eclipse

How to add @copyright to your code in eclipse ?

As a developer , we mostly want to reduce few development or coding effort while working on a project. Adding @copyright to your java file or your project file is quite easy. There are few ways you can achieve these. 

First Solution :- You can use 3rd party plugin to generate the @copyright. Follow the steps to install the plugin and add copyright for your project.

 1. Go to => Help => Eclipse MarketPlace => Search for copyright generator



2. Click on => Install and proceed further for finishing the installation. After the plugin installed successfully.
3. Go to menu => Project => Apply Copyright 


4. Now , Select custom copyright and paste your copyright header text in the text area. I have used the below sample header for my blogging.


/*******************************************************************************
 * Java Developers Guide Blogging - Confidential
 * ____________________
 *
 * [2018] - [2019]  Java Developers Guide Incorporated
 * All Rights Reserved.
 * 
 * NOTICE:  All information contained herein is, and remains
 * the property of  Java Developers Guide Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to  Java Developers Guide Incorporated
 * and its posts and articles are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Java Developers Guide Blogging.
 *
 * Generated on Feb 12, 2018
 ******************************************************************************/

Then , apply the included or excluded as per your need. I have added the included in this example. That means here I want to add copyright header text for all java file (i.e. *.java).  This expression will to add all .java files. Sample image below.



 5. Next => select the project you want to apply => Then select the java files you want to apply 


6. Now you can see the java files with your header copyright text as below.




Second Solution :-


You can directly add the header copyright text into the {template} in eclipse IDE. Follow the steps below.

1. Go to => Windows => Preferences => Java => Code Style = > Code Templates => Code

Then select "New Java files" , then add your copyrights in the first line as mentioned in the image below. Then Apply and finish.




2. Now create a new file ( Go to = File => New => Java Class)



Now you can see the copyrights has been added to your java classes. Hope it will help you to improve the coding practice and coding standards.


Hope it will help you.