Why Java ?

Posted on Updated on

Why Java

 

Today Java became a fundamental programming language that is used to develop application,web ,plugin and mobile application. Simple reason is cross platform,multi-threading capability,object oriented,security,robustness,distributed programming and more.

Why Java ?

We are quite sure that you have heard of Java programming language but there are also many programming language as well such that python,Ruby and C++ to name few. However Java is still one of favorite choice for developer for many reasons. As of date, Java is one of most secure programming language that is used in most of Banking domain and other security base application due to security in nature. Java use own ‘sandbox’ to run untrusted code obtained from open Network.

In addition to that, many enterprise solutions also make use of Java due to the possible types of integrations associated with it. For example, through Java, it is possible to integrate the
application or product with various web services such as payment gateways, crud applications as well as health domain applications. Suffice to say that the possibility through Java can easily be endless but it doesn’t mean that everything should be developed with Java.

Java has been the solution to various platforms that are both developing and stable. In fact, there are many noteworthy companies and projects that use Java for their day-to-day jobs. Some of the ones that you might have heard include Google Maps, Blu-ray discs, Kindle and a few other devices. In addition to that, laptops, supercomputers, and cell phones are also supported by Java making it a very versatile language as compared with others.

In statistical terms, there are roughly 1.1 billion desktops that run Java, 3 billion smartphones running Java, 1.4 billion Java Cards manufactured and is also being used in GPS systems, parking payment stations, lottery terminals, ATMs and many more. That is the power of Java not found in any other platform in the market.

Following are some Java development technologies, tools, and frameworks used to design complex architectures and built applications:

  • Struts, Spring, Hibernate and JPA
  • JAXB and Apache Axis 2/Java
  • JSP, Servlets, JDBC, EJB, JMS, JTA and JUnit
  • Apache Tomcat, JBoss and GlassFish
  • JavaScript, JSF, GWT,AngularJS and jQuery
  • Eclipse, Netbeans and JBoss tools
  • TestNG
  • jBPM and Drools
  • JCR

Why do Programmer choose Java ?

In short, Java is a solution to build a stable, reliable and secure application that run on cross-platform due to platform independent nature. It’s fast and high the performance of application due to atomically handle garbage collector i.e robustness. In fact today most of web site wouldn’t run unless your install JDK in your machine.

Key feature of Java :-

Simple
  • Looks familiar to existing programmers: related to C and C++:
  • Omits many rarely used, poorly understood, confusing features of C++, like operator overloading, multiple inheritance, automatic coercions, etc.
  • Contains no goto statement, but break and continue
  • Has no header files and eliminated C preprocessor
  • Eliminates much redundancy (e.g. no structs, unions, or functions)
  • has no pointers

Added features to simplify:

  • Garbage collection, so the programmer won’t have to worry about storage management, which leads to fewer bugs.
  • A rich predefined class library
Object-Oriented

Java is an object-oriented language, which means that you focus on the data in your application and methods that manipulate that data, rather than thinking strictly in terms of procedures.
In an object-oriented system, a class is a collection of data and methods that operate on that data. Taken together, the data and methods describe the state and behavior of an object. Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass.

Java comes with an extensive set of classes, arranged in packages, that you can use in your programs.

Distributed
  • It has a spring-like transparent RPC ( Remote Procedure call ) system
  • Now uses mostly TCP/IP based protocols like ftp & http

Java supports various levels of network connectivity through classes in the java.net package (e.g. the URL class allows a Java application to open and access remote objects on the internet).

Interpreted

The Java compiler generates byte-codes, rather than native machine code. To actually run a Java program, you use the Java interpreter to execute the compiled byte-codes. Java byte-codes provide an architecture-neutral object file format. The code is designed to transport programs efficiently to multiple platforms.

  • rapid turn-around development
  • Software author is protected, since binary byte streams are downloaded and not the source code
Robust

Java has been designed for writing highly reliable or robust software:

  • language restrictions (e.g. no pointer arithmetic and real arrays) to make it impossible for applications to smash memory (e.g overwriting memory and corrupting data)
  • Java does automatic garbage collection, which prevents memory leaks
  • extensive compile-time checking so bugs can be found early; this is repeated at runtime for flexibility and to check consistency
Secure

Security is an important concern, since Java is meant to be used in networked environments. Without some assurance of security, you certainly wouldn’t want to download an applet from a random site on the net and let it run on your computer. Java’s memory allocation model is one of its main defenses against malicious code (e.g can’t cast integers to pointers, so can’t forge access). Furthermore:

  • access restrictions are enforced (public, private)
  • byte codes are verified, which copes with the threat of a hostile compiler
Architecture-Neutral
  • Compiler generates byte codes, which have nothing to do with a particular computer architecture
  • Easy to interpret on any machine
Portable

Java goes further than just being architecture-neutral:

  • No “implementation dependent” notes in the spec (arithmetic and evaluation order)
  • standard libraries hide system differences
  • the Java environment itself is also portable: the portability boundary is POSIX compliant
High-Performance

Java is an interpreted language, so it will never be as fast as a compiled language as C or C++. In fact, it is about 20 times as slow as C. However, this speed is more than enough to run interactive, GUI and network-based applications, where the application is often idle, waiting for the user to do something, or waiting for data from the network.

Multi-threaded

Java allows multiple concurrent threads of execution to be active at once. This means that you could be listening to an audio clip while scrolling the page and in the background downloading an image. Java contains sophisticated synchronization primitives (monitors and condition variables), that are integrated into the language to make them easy to use and robust. The java.lang package provides a Thread class that supports methods to start, run, and stop a thread, and check on its status.

Dynamic
Java was designed to adapt to an evolving environment:
  • Even after binaries have been released, they can adapt to a changing environment
  • Java loads in classes as they are needed, even from across the network
  • It defers many decisions (like object layout) to runtime, which solves many of the version problems that C++ has
  • Dynamic linking

Thanks.

In this article we try to explore about Java and it’s feature which may be help you to choose a better and powerful language to develop an application. Please follow me at social network as well.

 

Difference between TreeMap and TreeSet in Java

Posted on Updated on

Today it’s going to vital in Java interview asked question about difference between Map implementation and Set implementation  like TreeSet vs TreeMap, HashSet vs HashMap and Hashtable vs HashMap. If your preparing for Java Interview question/Answer then must go though all these points. It helps you to get a credit in Interview.

Key Points :-

  • Both internally used Red-Black tree.
  • Object which is said to be unequal using compareTo() is return false even if it is equals using equals() method. so compareTo() and equals() does not work in consistent way.
  • Both guaranteed log(n) time cost for operation like get,put,containKey and remove.
  • Both guaranteed that Objects or Key Objects will be sorted order according to object comparable or custom comparator given in constructor argument. In case object is not  implemented comparable interface and to be added into TreeSet then an exception would thrown like “Exception in thread “main” java.lang.ClassCastException: User cannot be cast to java.lang.Comparable”
  • Both are not synchronized means it’s not used in concurrent application.
  • Both Iterator are “fail-fast” means it will throw ConcurrentModificationException when TreeMap or TreeSet is modified structurally once Iterator is created.
  • Null value is not permitted neither in TreeSet nor TreeMap.

Difference between TreeMap and TreeSet in Java .

Now see the difference between these two type:-

  1. Main difference between TreeMap implemented NavigableMap interface underlying Map interface and TreeSet implemented NavigableSet interface underlying Set.
  2.  Second difference between TreeMap and TreeSet is the way they store objects. TreeSet stores one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.
  3. TreeSet does not allowed to store duplicate Object while duplicates value are allowed to TreeMap.

Example code here :-


import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;

public class TreeSetAndMapExample {

public static void main(String args[]) {
User user1 = new User("Ajay", "10001");
User user2 = new User("Santosh", "10002");

TreeSet empTree = new TreeSet();
empTree.add(user1);
empTree.add(user2);
empTree.add(user1);
// empTree.add(null); //Exception in thread "main"
// java.lang.NullPointerException
System.out.println("Size of TreeSet " + empTree.size());
Iterator it = empTree.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

System.out.println(" TreeMap implementation here -");
TreeMap<User, User> empTreeMap = new TreeMap<User, User>();
empTreeMap.put(user1, user1);
empTreeMap.put(user2, user2);
empTreeMap.put(user1, user1);
// empTreeMap.put(null,user1); // Exception in thread "main"
// java.lang.NullPointerException

System.out.println("Size of TreeMap " + empTreeMap.size());
Iterator itMap = empTreeMap.keySet().iterator();
while (itMap.hasNext()) {
System.out.println(itMap.next());
}
}

}

output here :-

Size of TreeSet 2
User [name=Ajay, emp_id=10001]
User [name=Santosh, emp_id=10002]
TreeMap implementation here –
Size of TreeMap 2
User [name=Ajay, emp_id=10001]
User [name=Santosh, emp_id=10002]

User.java


class User implements Comparable {
private String name;
private String emp_id;

public User(String name, String emp_id) {
this.name = name;
this.emp_id = emp_id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmp_id() {
return emp_id;
}

public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}

@Override
public int compareTo(User o) {
// TODO Auto-generated method stub
return this.name.compareTo(o.name);
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", emp_id=")
.append(emp_id).append("]");
return builder.toString();
}

}

What is Singleton pattern and it’s uses ?

Posted on Updated on

What is Singleton pattern and it’s uses ?

This is most frequently asked question in Java interview for freshers, their uses in developement. In this article we will discuss following topics :-

  • What is Singleton Pattern ?
  • How to implement in coding ?
  • How many possible way to create a Singleton object in Java.
  • What is double check in Singleton Pattern and advantage of it.

Singleton is a creation Design pattern, it’s used to control the initialization of Object and ensure that only one instance of Object will be created in the Java Virtual Machine.In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects

Key Points :-

  • Global access point, a scope of Singleton object is Global or an application level.

How to implement in coding ?

There are various way to implement singleton class in Java.

  1. Class-loader static initialization or Eager Loading
  2. synchronized or Lazy Loading
  3. Using Enum

Implementation with Class-loader static initialization or Eager Loading :-

In this case class loader initialized the Object instance at the time of loading and subsequently calling this method get same object reference. It slow the application start-up performance.

public class MyFactory {
  private static final MyFactory instance = new MyFactory();

  public static MyFactory getInstance() {
    return instance;
  }

  private MyFactory() {}
}

Implementation with Synchronized i.e Lazy loading:-

In this case, a thread calling this method getInstance() an Object will be created and second time onward all subsequently calling this method point to same reference.  This is also call on demand object creation.

public class MyFactory {
  private static MyFactory instance;

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

  private MyFactory() {}
}

Implementation with Enum example:-

Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment

public Enum MyFactory {
  INSTANCE;
  private static final ConnectionFactory factory = new ConnectionFactory();

  public Connection getConnection() {
    return factory.getConnection();
  }
}

Question: Why can’t we use a static class instead of singleton?
Answer:

  • One of the key advantages of singleton over static class is that it supports inheritance.while the static class cannot
  • Another difference is that static class will have all its member as static only unlike Singleton.
  • Another advantage of Singleton is that it can be lazily loaded whereas static will be initialized whenever it is first loaded.
  • Singleton object stores in Heap but, static object stores in stack.
  • We can clone the object of Singleton but, we can not clone the static class object.
  • Singleton can use the Object Oriented feature of polymorphism but static class cannot.

Question: Can the singleton class be subclassed?

Answer: Frankly speaking singleton is just a design pattern and it can be subclassed. However it is worth to understand the logic or requirement behind subclassing a singleton class as the child class might not inherit the singleton pattern objective by extending the Singleton class. However the subclassing can be prevented by using the final keyword in the class declaration.

Question: Can there be multiple instance of singleton using cloning?
Answer: That was a good catch! What do we do now? To prevent the another instance to be created of the singleton instance we can throw exception from inside the clone() method.

Question: What is the impact if we are creating another instance of singleton using serialization and deserialization?
Answer: When we serialize a class and deserialize it then it creates another instance of the singleton class. Basically as many times as you deserialize the singleton instance it will create multiple instance. Well in this case the best way is to make the singleton as enum. In that way the underlying Java implementation takes care of all the details. If this is not possible then we will need to override the readobject() method to return the same singleton instance.

Question: Which other pattern works with Singleton?
Answer:There are several other pattern like Factory method, builder and prototype pattern which uses Singleton pattern during the implementation.

Question: Which classes in JDK uses singleton pattern?
Answer: java.lang.Runtime : In every Java application there is only one Runtime instance that allows the application to interface with the environment it is running. The getRuntime is equivalent to the getInstance() method of the singleton class.

 

Uses of Singleton design pattern:

Various usages of Singleton Patterns:

  • Hardware interface access: The use of singleton depends on the requirements. However practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.
  • Logger : Similarly singleton is a good potential candidate for using in the log files generation. Imagine an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference.
  • Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file at the first time and there after from second call onwards the client applications read the data from in-memory objects.
  • Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.

RESTful example with Tomcat and maven

Posted on Updated on

RESTful example with Tomcat and Maven

This is a Simple example of RESTful using jersey service in eclipse which is intended to explore how to implement RESTful services in our project. In web.xml file, Full qualified package is given to scan all services class under this package it will automatically happened at deployment time also servlet-mapping defined services mapping pattern in this case /rest/* means all RESTful container will be treated all services as RESTful service that start with /rest/*. example :-

  • /rest/user
  • /rest/user/{user_id}

Create and configure a pom.xml which contains all required dependencies for RESTful.

pom.xml file under root directory in your project:-


<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/maven-v4_0_0.xsd">

<groupId>com.rest</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>RESTfulExample1</artifactId>
<name>RESTfulExample1</name>
<version>1.1-SNAPSHOT</version>
<packaging>war</packaging>

<description>
RESTful Example1
</description>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>

</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>/web</warSourceDirectory>
<warName>RESTfulExample1</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>ITCM</finalName>
</build>
</project>


Project explorer in Eclipse : –

project-explorer

Project src files :-

com.rest.service

UserInfoService.Java :- Intended of this class is to produce and consume resources using RESTful service.


package com.rest.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.rest.model.User;
import com.rest.repository.UserRepository;

@Path("/user")
public class UserInfoService {
private UserRepository userRepo = new UserRepository();

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(){
return Response.ok().entity(userRepo.getAllUsers()).build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{user_id}")
public Response getUser(@PathParam("user_id") int user_id){
return Response.ok().entity(userRepo.getUser(user_id)).build();
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response postUser(User user){
userRepo.insert(user);
return Response.ok().status(Status.OK).build();
}

@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response putUser(User user){
userRepo.update(user);
return Response.ok().build();
}

@DELETE
@Path("/{user_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("user_id") int user_id){
userRepo.deleteUser(user_id);
return Response.ok().build();
}


}

 com.rest.reporitory

UserRepository.Java :- Intended of repository class to perform CRUD operation over user data.


package com.rest.repository;

import java.util.Collection;

import com.rest.factory.UserRepositoryFactory;
import com.rest.model.User;

public class UserRepository {
private UserRepositoryFactory userFactory = UserRepositoryFactory.getInstance();

public User getUser(int id){
return userFactory.getUser(id);
}

public Collection<User> getAllUsers(){
return userFactory.getListOfUsers().values();
}

public User deleteUser(int id){
return userFactory.deleteUser(id);
}

public void insert(User user){
userFactory.getUpdate(user);
}

public void update(User user){
userFactory.getUpdate(user);;
}
}

 com.rest.model

User.java :- this is a pojo/model java class this is used to wrap the User properties either user response or request parameters.


package com.rest.model;

import java.io.Serializable;

public class User implements Serializable{

/**
*
*/
private static final long serialVersionUID = 3228632501659659215L;
private int id;
private String name;
private String address;
public User(){

}

public User(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}

 com.rest.factory

UserRepositoryFactory.java:- intended of this factory class to provide User data.


package com.rest.factory;

import java.util.HashMap;
import java.util.Map;

import com.rest.model.User;

public class UserRepositoryFactory {

private static Map<Integer, User> users = new HashMap<Integer, User>();

public Map<Integer, User> getListOfUsers() {
User u1 = new User(101, "Ajay Kumar", "New Delhi");
User u2 = new User(102, "Rahul Kumar", "Goa");
User u3 = new User(103, "Santosh Kumar", "Delhi");
users.put(u1.getId(), u1);
users.put(u2.getId(), u2);
users.put(u3.getId(), u3);
return users;
}

public User getUser(Integer id) {
return users.get(id);
}

public User deleteUser(Integer id) {
return users.remove(id);
}

public void getUpdate(User user) {
if (users.containsKey(user.getId())) {
// update user here
users.put(user.getId(), user);
} else {
// add user
users.put(user.getId(), user);
}
}

private UserRepositoryFactory() {
}

private static UserRepositoryFactory userRepository = new UserRepositoryFactory();

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

Web-description file ( web.xml ):-


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTfulExample1</display-name>

<servlet>
<servlet-name>REST</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.jersey.jaxb,com.fasterxml.jackson.jaxrs.json,com.rest.service
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

GET method:-

  • /rest/user : – Fetch all users
  • /rest/user/101 – Fetch User which id is 101

GET-User

POST method :-

  • /rest/user :- Add User
    • Method:Post
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Rahul Kumar”, “address”: “Goa” }
    • Return Response : Response Status OK

POST-User

PUT method :-

  • /rest/user :- Update User
    • Method:PUT
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Any name”, “address”: “Any City” }
    • Return Response : Response Status OK

PUT-User

DELETE method :-

  • /rest/user/101 :- Delete User which user id is 101
    • Method:DELETE
    • Return Response : Response Status OK

DELETE-User-BY-ID

Below step’s are done using RESTful tools to fire rest services

 Download Complete source code from here

 

RESTful Service in Java

Posted on Updated on

RESTful Service in Java.

Table of Contents:-

  1. What is RESTful service in Java ?
  2. How to implement it in Web Application ?

 

What is RESTful service in Java ?

Representation state transfer(REST) is architecture style that specifies constraints i.e Uniform resource identifier(URI). REST architecture style represents data,functionality as resources that are accessed by URI. REST create a bridge between Client/Server architecture and communicate over stateless HTTP protocol and Client/Server exchange representation  resources by using standardized interface and protocol.

URL ( Uniform Resource Locator ) formation :-

URL : <Protocol> ://< Hostname> :< port>/<Context-name>/<URL>

http://localhost:8080/RESTfulExample1/rest/user/102

RESTful ( JAX-RS) annotation summary :-

  • @path : – It’s used to represents an URI path template which the resource response it.
  • @consume :- It’s used to specify MIME media type representation of a resource can consume that were sent by client.
  • @produce :- it’s used to specify MIME media type representation of a resource can produce that send back to client like “application/json”,”application/text”.
  • @ParamPath :- The @PathParam annotation is a type of parameter that you can extract for use in your resource class.URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
  • @QueryParam :- The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
  • @Context :- @Context can be used to obtain contextual Java types related to the request or response.

How to convert an Object into Response Type (“JSON/Text/Xml”):-

Using javax.ws.rs.core.Response , contract between a returned instance and the runtime when an application needs to provide metadata to the runtime.

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
 return Response.ok().entity(userRepo.getAllUsers()).build();
 }

HTTP methods :-

  • GET : – it’s used to read a specified resource.
  • POST :- it’s used to create a specified resource.
  • PUT :-  it’s used to update a specified resources
  • DELETE :-it’s used to delete a specified resources
  • HEAD :- Same as GET but returns only HTTP headers and no document body

Key Points :-

  • It’s not a protocol.
  • It’s a architecture style that represent a resources that are accessed by URI.
  • Communication over HTTP is stateless.
  • It’s scalable,reliable and portable by nature.

Example with source code below :

  1. RESTful example with Tomcat and Maven.

Importants of hashcode and equals method in Java

Posted on Updated on

Importants of hashcode and equals method in Java

These two is core part of Collection in Java and most frequently asked question in interview. In this article we will discuss all related points.

hashcode and equals methods are two fundamental topics from java.lang.Object class which is used to compare two Object using equality and calculate the memory address of Object using hashcode function.  primarily uses of these two function in Collection in java like HashMap,Hashtable,etc.

Default implementation of these two methods in java.lang.Object class :-

hashcode method :- it’s a native method means implemented directly in ‘native code’ in JVM that return distinct integer value for distinct Objects. Typically it’s converted internal memory address of Object into integer. Ideally a hashcode method represent an Object so distinct Object having distict hashcode values.

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

public native int hashCode();

equals method:- Default implementation is comparing two Object by reference and return true if Objects reference are same otherwise false.

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used inequals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.
public boolean equals(Object obj) {
return (this == obj);
}

 Contract Implementation of these methods and their uses:-

In general, contract of overridden implementation of these methods give us a consistent behaviours of same Object every time.It is not mandatory to implement but recommended to implement these methods when Object to be used in Collection part.

Key Points :-

    • Two objects are equals according to equals() must return same hashcode for each of Object but in opposite two Objects having same hashcode may not be equals by equals().
    • Invalid or unimplemented of these two overridden methods of Object class may cause serious issues in our application.
    • If hashcode() return same hash value for Objects then internally a LinkedList chain would be created against that key and maintains Key/Value Pairs in Entry Object.

Internal implementation of static class Entry.Java in HashMap

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

Internal implementation of put() in HashMap

 
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

Example :-

import java.util.HashMap;
import java.util.Map;

class Employee {
	private long id;
	private String name;
	private String address;
	public Employee(long id,String name,String address){
		this.id=id;
		this.name = name;
		this.address = address;
	}
        /**
         * Getter/Setter ....
         */ 
 
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + (int) (id ^ (id >>> 32));
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
}

Here, Three distinct Employee Object is created, each of them has different properties and stored into HashMap. During this discussion we will see what will happen if hashcode() is not implemented.
Main Class here :-


public static void main(String args[]){
Map<Employee,Employee> map = new HashMap<Employee,Employee>();
Employee e1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3 = new Employee(1003, "Wasim Akram","Delhi");

map.put(e1, e1);
map.put(e2, e2);
map.put(e3, e3);
}

case 1 : if hashcode() is not override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// false
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // false
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // false
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 2 : if hashcode() is override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// true
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // true
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // true
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 3 : if equals() is not override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 4 : if equals() is override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // true
System.out.println(e2.equals(e2_2)); // true
System.out.println(e3.equals(e3_3)); // true

case 5 : if hashcode() is override but equals() is not in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 6 : if hashcode() returns fixed value but equals() is not override in Employee class then

@Override
 public int hashCode() {
 return 31;
}
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // null
System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

case 7 : if hashcode() returns fixed value and equals() is override in Employee class then

@Override

//Employee.Java 
public int hashCode() {
 return 31;
}
@Override
public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
}

//Main.Java Class	
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // // Employee [id=1003, name=Wasim Akram, address=Delhi]

System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

 

Interview Question :-

What is hashcode and equals methods ?
hashcode() is a native method of java.lang.Object class this is a technique to calculate the memory address of object into integer value. Ideally, hashcode assign each Object as key to unique bucket in Map.

equals method is used to compare between two Objects and it return true if Objects are equals according to their implementation otherwise return false. It is used to search an Object into bucket of Map implementation.

Why it’s important to override these methods.

As we discussed below, each object has their hashcode which represent Object identity. Also it guarantee then same hash value will be generated consistently every time for same Object by override this method.so it’s important to implemented in our Bean class. Whenever we use this object as Key in Map implementation then a bucket is assigned to Entry<Key,Value> object by calculated hash code of key Object otherwise default implementation of native hashcode() from java.lang.Object Class will be applied which produce inconsistent behaviours in Java compiler.

In the same way, default implementation of equals() methods return false every time for every mutable Object by equality, just because it’s compare objects reference by default not by Object content.

What is hashing technique ?

It’s a technique to compute hash value of Object, Once the hash value is computed then we can insert into hashtable at designated position or bucket. In Java using hashcode() map each Object into unique slot.

What happened if hashcode() is not overridden ?

If we don’t implement hashcode method then default implementation of Object class is used to store and retrieve Object value from Hashtable,HashMap and HashSet, subsequently result would be incorrect. Hence it’s recommended to override these two method.

Two Objects which are equals according to equals() then what their hash value ?

if two Objects are equals according to equals() then hashcode() produce same hash value.

What is hash Collision?

Often it’s not possible if implemented hashcode() is perfect but when two objects hash point to same slot or bucket then it will happen therefore internally a linked list chain will be created that store the Entry Object.

Difference between ‘==’ and equals() method.

‘==’ is a Java operator which is used to compare two operands reference or values.
equals() is a method from java.lang.Object class with check object content.

Difference between equals() and compareTo() ?

  • equals() methods came from java.lang.Object class while compareTo() came from java.lang.comparable interface.
  • equals() return false if it’s compare with Null reference while compareTo return NullPointerException.
System.out.println(e1.equals(null)); // false
System.out.println("Say Hello".compareTo(null)); // Exception in thread "main" //java.lang.NullPointerException
//at java.lang.String.compareTo(Unknown Source)
  • compareTo() only work on those Object that implements Comparable interface.
  • equals() method returns boolean value while compareTo() return integer value.

 

 

What is transient variable in Java

Posted on Updated on

What is transient variable in Java

transient is a keyword in Java, which means variable is marked transient to indicate that they are not part of persistent state while Object is being saved into File system or DB.

Today we are moving toward annotation base programming rather than manual configuration and sometime we declared properties in Pojo class in which we marked few of perperties as transient then that properties only useful at application level not DB or File System.Hence we can control fields being saved during Serialization process using transient keywork.

Below example of Weather.Java indicate that temperature field value is not saved into File System or dB. Only city field value would be saved.


public class Weather {
private String city;
private transient String temperature;
--------
--------
}

Similarly, if you are familiar with MondoDB or Hibernate Annotation base Pojo class, Same way we can control the fields from being persistence state.

LoginModel.Java :- Mongodb pojo Java Class

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Login")
public class LoginModel {
 
 @Id
 private String id;
 private String userName;
 private String password;
@Transient
private String sessionId;
-------------
-------------
 Below are complete code of transient-

Weather.Java is a Serialized Java class.

import java.io.Serializable;

public class Weather implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = 2983365916512327738L;
 private String city;
 private transient String temperature;

 public Weather(String city, String temperature) {
 this.city = city;
 this.temperature = temperature;
 }

 public String getCity() {
 return city;
 }

 public void setCity(String city) {
 this.city = city;
 }

 public String getTemperature() {
 return temperature;
 }

 public void setTemperature(String temperature) {
 this.temperature = temperature;
 }

 @Override
 public String toString() {
 StringBuilder builder = new StringBuilder();
 builder.append("Weather [city=").append(city).append(", temperature=")
 .append(temperature).append("]");
 return builder.toString();
 }

}

 WeatherSerializationService .java : read or write Object as serialization form


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;


public class WeatherSerializationService {
	
	private static final String FILE_NAME="weather.sar";
	
	public static void main(String args[]){
		Weather weather = new Weather("Delhi","42'C");
		WeatherSerializationService weatherService = new WeatherSerializationService();
		System.out.println("Save Serializated Object "+weather);
		weatherService.save(weather);
		
		Weather readWeather = weatherService.retrive();
                if( null == readWeather ){
                    System.out.println(" Unable to read Serialization Object - Weather ");
                }
		System.out.println("Read Serializated Object "+readWeather);
		
	}
	public void save(Weather weather){
		FileOutputStream fileOutputStream = null;
		ObjectOutput objectOut = null;
		try {
			fileOutputStream = new FileOutputStream(FILE_NAME);
			objectOut = new ObjectOutputStream(fileOutputStream);
			objectOut.writeObject(weather);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectOut ) return;
                                if(null == fileOutputStream ) return;
				objectOut.close();
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	public Weather retrive(){
		ObjectInput objectInput = null;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(FILE_NAME);
			objectInput = new ObjectInputStream(inputStream);
			return (Weather)objectInput.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectInput ) return null;
				if(null == inputStream ) return null;
				
				objectInput.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}

Output here :-

Save Serializated Object Weather [city=Delhi, temperature=42’C]
Read Serializated Object Weather [city=Delhi, temperature=null]