Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Thursday, 14 August 2014

Spring 4 Restful Web Services With Hibernate 4 Example using Maven – Server Application

Spring 4 Restful Web Services With Hibernate 4 Example using Maven – Server Application In our previous discussions we came across several Spring related topics. In this particular blog we will see how to create Spring Restful Web Services With Hibernate using Maven. We will create and build the project with Maven and hibernate 4 will be used in data layer.

To get started simply create a simple web application with maven and import it in Eclipse. If you are new to Maven please go through the Link below.

More Details on : Dynamic Web Project with Maven and Import it in eclipse

Now we have a skeleton Maven project imported to eclipse, lets add all required Java and Configuration files to it as shown in the rest part of the tutorial.

Database Setup
Here us MySql script to create a simple database and table structure to be used in our application, simply paste the script in query editor and run to make a DB skeleton.
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;

-- Dumping database structure for employee_db
CREATE DATABASE IF NOT EXISTS `employee_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `employee_db`;


-- Dumping structure for table employee_db.employee
CREATE TABLE IF NOT EXISTS `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- Dumping data for table employee_db.employee: ~1 rows (approximately)
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` (`id`, `first_name`, `last_name`, `email`, `phone`) VALUES
 (2, 'Hoston', 'lindey', 'hl@gmail.com', '90908989899');
/*!40000 ALTER TABLE `employee` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;



Dependencies required to make Spring Restful Web Services with Hibernate

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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.beingjavaguys.sample</groupId>
 <artifactId>SpringRestCrud</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SpringRestCrud Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
  <spring.version>4.0.5.RELEASE</spring.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <log4j.version>1.2.17</log4j.version>
  <jdk.version>1.7</jdk.version>
  <context.path>SpringRestCrud</context.path>
 </properties>
 <build>
  <finalName>${pom.artifactId}</finalName>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>${log4j.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.2.2</version>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.6</version>
  </dependency>
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.10</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>
 </dependencies>
</project>



\src\main\webapp\WEB-INF\web.xml
We need to make an Spring entry to web.xml, this will tell the container that all upcoming requests will be served by Spring Framework itself as per the configuration.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">

 <display-name>Sample Spring Maven Project</display-name>

 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


\src\main\webapp\WEB-INF\spring-config.xml
This is simple spring configuration file, we have added entry for base-package her to search and find Controller classes with annotations. We defined two beans here for Service and Dao layer that we will see in details shortly. Rest is hibernate configurations and a datasource bean to connect with database. More details on : Spring Hibernate Integration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

 <context:component-scan base-package="com.beingjavaguys.controller" />
 <mvc:annotation-driven />

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/employee_db" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.beingjavaguys.model.Employee</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   </props>
  </property>
 </bean>

 <bean id="txManager"
  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <bean id="dataDao" class="com.beingjavaguys.dao.DataDaoImpl"></bean>
 <bean id="dataServices" class="com.beingjavaguys.services.DataServicesImpl"></bean>
</beans>

\src\main\java\com\beingjavaguys\controller\RestController.java
This is simple Spring MVC controller with annotations, we have added all general purpose methods here those method will accept a rest request in Json form and will return a JSON response. The methods are self explanatory we have used @Controller annotation to point incoming requests to this class, and @RequestMapping annotation to point incoming requests to appropriate Methods. @RequestBody annotation is used to accept data with request in Json form and @ResponseBody is used to return JSON as response to incoming request.
package com.beingjavaguys.controller;

import java.util.List;

import org.apache.log4j.Logger;
import com.beingjavaguys.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beingjavaguys.model.Employee;
import com.beingjavaguys.services.DataServices;

@Controller
@RequestMapping("/employee")
public class RestController {

 @Autowired
 DataServices dataServices;

 static final Logger logger = Logger.getLogger(RestController.class);

 /* Submit form in Spring Restful Services */
 @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
 public @ResponseBody
 Status addEmployee(@RequestBody Employee employee) {
  try {
   dataServices.addEntity(employee);
   return new Status(1, "Employee added Successfully !");
  } catch (Exception e) {
   // e.printStackTrace();
   return new Status(0, e.toString());
  }

 }

 /* Ger a single objct in Json form in Spring Rest Services */
 @RequestMapping(value = "/{id}", method = RequestMethod.GET)
 public @ResponseBody
 Employee getEmployee(@PathVariable("id") long id) {
  Employee employee = null;
  try {
   employee = dataServices.getEntityById(id);

  } catch (Exception e) {
   e.printStackTrace();
  }
  return employee;
 }

 /* Getting List of objects in Json format in Spring Restful Services */
 @RequestMapping(value = "/list", method = RequestMethod.GET)
 public @ResponseBody
 List getEmployee() {

  List employeeList = null;
  try {
   employeeList = dataServices.getEntityList();

  } catch (Exception e) {
   e.printStackTrace();
  }

  return employeeList;
 }

 /* Delete an object from DB in Spring Restful Services */
 @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
 public @ResponseBody
 Status deleteEmployee(@PathVariable("id") long id) {

  try {
   dataServices.deleteEntity(id);
   return new Status(1, "Employee deleted Successfully !");
  } catch (Exception e) {
   return new Status(0, e.toString());
  }

 }
}


More details on : Spring JSON – Output Json in Spring application

Model Classes

\SpringRestCrud\src\main\java\com\beingjavaguys\model\Employee.java
This is simple POJO to represent Employee entity in our application, we will be dealing with Employee entity to save, retrieve and delete data using Spring Restful Web Services. We have annotated the class with Hibernate annotations to make hibernate aware of the entity.
package com.beingjavaguys.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@Entity
@Table(name = "employee")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Employee implements Serializable {

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue
 @Column(name = "id")
 private long id;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String lastName;

 @Column(name = "email")
 private String email;

 @Column(name = "phone")
 private String phone;

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }
}



Don’t forget to add @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) annotation to class, this is used to resolve Hibernate and Json conflict.

\src\main\java\com\beingjavaguys\model\Status.java
This is another POJO to represent conditional Status and Error messages in form of Json, this comes handy in case of sending status response to requests if needed.
package com.beingjavaguys.model;

public class Status {

 private int code;
 private String message;

 public Status() {
 }

 public Status(int code, String message) {
  this.code = code;
  this.message = message;
 }

 public int getCode() {
  return code;
 }

 public void setCode(int code) {
  this.code = code;
 }

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }
}



Data layer with spring and hibernate

Below are simple Service and Dao classes and Interfaces to make a two tier data layer between Spring and Hibernate.

More details on : Spring Hibernate Integration

\src\main\java\com\beingjavaguys\dao\DataDao.java
package com.beingjavaguys.dao;

import java.util.List;

import com.beingjavaguys.model.Employee;

public interface DataDao {

 public boolean addEntity(Employee employee) throws Exception;
 public Employee getEntityById(long id) throws Exception;
 public List getEntityList() throws Exception;
 public boolean deleteEntity(long id) throws Exception;
}



\src\main\java\com\beingjavaguys\dao\DataDaoImpl.java
package com.beingjavaguys.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.beingjavaguys.model.Employee;

public class DataDaoImpl implements DataDao {

 @Autowired
 SessionFactory sessionFactory;

 Session session = null;
 Transaction tx = null;

 @Override
 public boolean addEntity(Employee employee) throws Exception {

  session = sessionFactory.openSession();
  tx = session.beginTransaction();
  session.save(employee);
  tx.commit();
  session.close();

  return false;
 }

 @Override
 public Employee getEntityById(long id) throws Exception {
  session = sessionFactory.openSession();
  Employee employee = (Employee) session.load(Employee.class,
    new Long(id));
  tx = session.getTransaction();
  session.beginTransaction();
  tx.commit();
  return employee;
 }

 @SuppressWarnings("unchecked")
 @Override
 public List getEntityList() throws Exception {
  session = sessionFactory.openSession();
  tx = session.beginTransaction();
  List employeeList = session.createCriteria(Employee.class)
    .list();
  tx.commit();
  session.close();
  return employeeList;
 }
 
 @Override
 public boolean deleteEntity(long id)
   throws Exception {
  session = sessionFactory.openSession();
  Object o = session.load(Employee.class, id);
  tx = session.getTransaction();
  session.beginTransaction();
  session.delete(o);
  tx.commit();
  return false;
 }

}



\src\main\java\com\beingjavaguys\services\DataServices.java
package com.beingjavaguys.services;

import java.util.List;

import com.beingjavaguys.model.Employee;

public interface DataServices {
 public boolean addEntity(Employee employee) throws Exception;
 public Employee getEntityById(long id) throws Exception;
 public List getEntityList() throws Exception;
 public boolean deleteEntity(long id) throws Exception;
}



\src\main\java\com\beingjavaguys\services\DataServicesImpl.java
package com.beingjavaguys.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.beingjavaguys.dao.DataDao;
import com.beingjavaguys.model.Employee;

public class DataServicesImpl implements DataServices {

 @Autowired
 DataDao dataDao;
 
 @Override
 public boolean addEntity(Employee employee) throws Exception {
  return dataDao.addEntity(employee);
 }

 @Override
 public Employee getEntityById(long id) throws Exception {
  return dataDao.getEntityById(id);
 }

 @Override
 public List getEntityList() throws Exception {
  return dataDao.getEntityList();
 }

 @Override
 public boolean deleteEntity(long id) throws Exception {
  return dataDao.deleteEntity(id);
 }

}

In this particular article we came across "Spring 4 Restful Web Services With Hibernate 4 Example using Maven", in our next discussion we will see how to create a Client Application in Spring to consume Spring Restful Services.
Download complete Project : Download Link
NOTE : In case you want to test the application with some dummy data and without using any client application, you can do that using Chrome's Postman - REST Client. Make sure to set content-type: application/json when sending form data in JSON format to the service.










Thanks for reading !
Being Java Guys Team

Download "Spring 4 Restful Web Services With Hibernate 4 Example" from "SkyDrive"



Thursday, 24 July 2014

Integrate Neo4j (Graph DB) with Java – Neo4J with Java (Neo4J + Java)

In this article we will see, what is Neo4J and graph db and how to use Neo4J with Java, adding nodes, relationships, properties and much more, stay tight and go forward :)

In computer science a graph database is a database that uses graph structure to store data, with help of graph nodes, nodes properties and relationships in between nodes. Nodes represents entities like employee, person, item, salary .. etc. Properties holds information about the node, as in case of employee node properties are id, name, department etc.. The graph can be traversed using any graph traversal algorithm.

Relationships are represented by edges those connects different nodes to nodes or nodes to properties. Relationships can also have properties. Like a relationships “friend” between two person nodes with type “knows” can have relationship properties like “are-true-friend”, “fiends-since” etc.. and their values like “yes”, “1787” etc..

There are a number of different graph db projects, some of them are AllegroGraph, ArangoDB, Bitsy, DEX/Sparksee, GraphBase and Neo4j.


Neo4j graph db

Neo4j is a open source database implemented in Java, Neo4j is the most popular graph database of today. Neo4j is fully transactional Java persistent engine that stores data in graph node rather than tables. Installing Neo4j database in windows 7

Neo4j db can be used as embedded db to be used in your code, but it’s always a better practice to store full db server to learn it. Follow the steps below to download and install Neo4j db in your local machine and get it up:
1) Download an updated and appropriate release from http://www.neo4j.org/download.
2) Double click the setup and install db server as simple as other windows application.
3) Visit http://localhost:7474 to verify that the server instance is started and running correctly.


Integrating Neo4j with Java

Neo4j exposes all required API’s to integrate with Java applications, Neo4j accepts request and return response in Json format only. In the rest part of the application we will see how to create a node, add properties and relationships to db using Java code.

We need to add a Neo4j driver dependency to the project

  <dependency>
   <groupId>org.neo4j</groupId>
   <artifactId>neo4j</artifactId>
   <version>2.1.2</version>
  </dependency>
Neo4j exposes its functions using REST API’s in Json format, so we have to use any REST API client to interact with. I am using HttpCient libraries, but you are free to use any API as per your convenient.
  
<dependency>
   <groupId>commons-httpclient</groupId>
   <artifactId>commons-httpclient</artifactId>
   <version>3.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.1.3</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpmime</artifactId>
   <version>4.1.3</version>
   <scope>compile</scope>
  </dependency>


Checking if Neo4j DB server is up and running.

To check the server status we need to send a get request to server in the required format, if got 200 status code, it means everything is fine and server is running peacefully.

For rest of the blog we have referring server root with “SERVER_ROOT_URI” as:
final String SERVER_ROOT_URI = "http://localhost:7474";
        /*
  * checks if neo4j server is up and running, returns 200 if succeeded and
  * 500 otherwise
  */
 public int getNeo4jServerStatus(String SERVER_ROOT_URI) {
  int statusCode = 500;
  try {

   String url = SERVER_ROOT_URI;
   HttpClient client = new HttpClient();
   GetMethod getMethod = new GetMethod(url);
   statusCode = client.executeMethod(getMethod);
   getMethod.releaseConnection();
  } catch (Exception e) {
   System.out.println("Exception in connecting to neo4j DB : " + e);
  }

  return statusCode;
 }


Adding a node to Neo4j DB server using Java

We have to send a post request to server URI //db/data/node to make a node in Neo4j DB. In accepts POST request and returns JSON data.

Create node Request format
• POST http://localhost:7474/db/data/node
• Accept: application/json; charset=UTF-8

Create node Response format
• 201: Created
• Content-Type: application/json; charset=UTF-8
• Location: http://localhost:7474/db/data/node/89
        /*
  * adding a node to server root
  */
 public String addNode(String SERVER_ROOT_URI) {
  String serverResponse = null;
  String nodeLocation = null;
  try {
   String nodePointUrl = SERVER_ROOT_URI + "/db/data/node";
   HttpClient client = new HttpClient();
   PostMethod postMethod = new PostMethod(nodePointUrl);

   /**
    * set header information to post request
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   postMethod.addRequestHeader(header);

   /**
    * set json payload to post request
    */
   // empty node in json format
   StringRequestEntity stringRequestEntity = new StringRequestEntity(
     "{}", "application/json", "UTF-8");
   postMethod.setRequestEntity(stringRequestEntity);
   int requestStatus = client.executeMethod(postMethod);
   serverResponse = postMethod.getResponseBodyAsString();
   Header locationHeader = postMethod.getResponseHeader("location");
   nodeLocation = locationHeader.getValue();
   postMethod.releaseConnection();
   System.out.println("Request Status : " + requestStatus);
   System.out.println("Node Location : " + nodeLocation);
   System.out.println("Server Response Json : " + serverResponse);
  } catch (Exception e) {
   System.out.println("Exception in adding a node to neo4j graph : "
     + e);
  }

  return nodeLocation;
 }
The code above is self explained, all we have done is make a POST request and send a empty JSON object. We can that verify the node by browsing to URL printed in “Node Location” in console. It would be in form of http://localhost:7474/db/data/node/1.


Adding properties to a Neo4J node using Java

Till now we have added a empty node to Neo4J server, lets add some properties to the node. The properties service is a PUT service and upon successful completion it returns “204 No Content” response. Like it’s create pear this service also accepts and sends Json data format.

Properties node Request format
• PUT http://localhost:7474/db/data/node/80/properties/foo
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Properties node Response format
• 204: No Content
        /*
  * adding properties to nodes
  */
 public void addProperty(String SERVER_ROOT_URI, String nodeLocationPath,
   String propertyName, String propertyValue) {

  try {
   String nodePointUrl = nodeLocationPath + "/properties/"
     + propertyName;
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(nodePointUrl);

   /**
    * set headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set json payload
    */
   String jsonString = "\"" + propertyValue + "\"";
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out.println("Exception in adding propery to node : " + e);
  }

 }
In the code above we have passed the node URI to which we need to add properties, once added the node you can check it using browser console of Neo4J.


Creating a relationship in Neo4J using Java

To create a relationship we uses URI /relationships, here nodeurl is the location of source node to which relationship is being created.

The web service accepts a POST request in json format and returns response in Json format. After successful completion of request you will get a 201 status code. The API also returns the relationship node location.

Relationship node Request format
• PUT http://localhost:7474/db/data/node/80/properties/foo
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Relationship node Response format
• 204: No Content
        /*
  * adding relationship between two nodes
  */
 public String addRelationship(String firstNodeLocation,
   String secondNodeLocation, String relationship,
   String relationAttributes) {
  String relationOutputJson = null;
  String relationLocation = null;
  try {
   String fromUrl = firstNodeLocation + "/relationships";

   String relationshipJson = generateJsonRelationship(
     secondNodeLocation, relationship, relationAttributes);

   System.out.println("Relationship Json : " + relationshipJson);

   HttpClient httpClient = new HttpClient();
   PostMethod mPost = new PostMethod(fromUrl);

   /**
    * set request headers
    */
   Header mtHeader = new Header();
   mtHeader.setName("content-type");
   mtHeader.setValue("application/json");
   mtHeader.setName("accept");
   mtHeader.setValue("application/json");
   mPost.addRequestHeader(mtHeader);

   /**
    * set request json payload
    */
   StringRequestEntity requestEntity = new StringRequestEntity(
     relationshipJson, "application/json", "UTF-8");
   mPost.setRequestEntity(requestEntity);
   int nodesatus = httpClient.executeMethod(mPost);
   relationOutputJson = mPost.getResponseBodyAsString();
   Header locationHeader = mPost.getResponseHeader("location");
   relationLocation = locationHeader.getValue();
   mPost.releaseConnection();
   System.out.println("Node Satus : " + nodesatus);
   System.out.println("Relation node Location : " + relationLocation);
   System.out.println("output : " + relationOutputJson);
  } catch (Exception e) {
   System.out.println("Exception in adding relationship node in neo4j : " + e);
  }

  return relationLocation;

 }

 /*
  * used to create relationship json in required format
  */
 private String generateJsonRelationship(String secondNodeLocation,
   String relationship, String relationAttributes) {

  StringBuilder sb = new StringBuilder();
  sb.append("{ \"to\" : \"");
  sb.append(secondNodeLocation);
  sb.append("\", ");

  sb.append("\"type\" : \"");
  sb.append(relationship);
  if (relationAttributes == null || relationAttributes.length() < 1) {
   sb.append("\"");
  } else {
   sb.append("\", \"data\" : " + relationAttributes);

  }

  sb.append(" }");
  return sb.toString();
 }


Adding properties to a relationship in Neo4J using Java

Here we are done with adding nodes and a relationship in between nodes, now we can add properties to relationships as well. Properties can be added to a relationship making a put request to /properties where relationshiplocation is the location of relationship in db server.

Relationship node Request format
• PUT http://localhost:7474/db/data/relationship/113/properties
• Accept: application/json; charset=UTF-8
• Content-Type: application/json

Relationship node Response format
• 204: No Content
public void addPropertyToRelations(String relationshipLocationPath,
   String propertyName, String propertyValue) {

  try {
   String relPropUrl = relationshipLocationPath + "/properties";
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(relPropUrl);

   /**
    * set request headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set request json payload
    */
   String jsonString = convertToNameValueJson(propertyName,
     propertyValue);
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out
     .println("Exception in addding properties to a relation in neo4j : "
       + e);
  }

 }

 private String convertToNameValueJson(String name, String value) {
  return String.format("{ \"%s\" : \"%s\" }", name, value);
 }
Done, till now we have seen, how to install and setup Neo4J in Windows and integrate Neo4j with Java. Lets see the folks running now, here are two complete files used in this project one is consists of operations and other file is having main() to perform them.

\src\main\java\com\beingjavaguys\graphdb\ServerUtils.java
package com.beingjavaguys.graphdb;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
 * @author Nagesh.Chauhan
 * 
 */
public class ServerUtils {
 /*
  * checks if neo4j server is up and running, returns 200 if succeeded and
  * 500 otherwise
  */
 public int getNeo4jServerStatus(String SERVER_ROOT_URI) {
  int statusCode = 500;
  try {

   String url = SERVER_ROOT_URI;
   HttpClient client = new HttpClient();
   GetMethod getMethod = new GetMethod(url);
   statusCode = client.executeMethod(getMethod);
   getMethod.releaseConnection();
  } catch (Exception e) {
   System.out.println("Exception in connecting to neo4j DB : " + e);
  }

  return statusCode;
 }

 /*
  * adding a node to server root
  */
 public String addNode(String SERVER_ROOT_URI) {
  String serverResponse = null;
  String nodeLocation = null;
  try {
   String nodePointUrl = SERVER_ROOT_URI + "/db/data/node";
   HttpClient client = new HttpClient();
   PostMethod postMethod = new PostMethod(nodePointUrl);

   /**
    * set header information to post request
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   postMethod.addRequestHeader(header);

   /**
    * set json payload to post request
    */
   // empty node in json format
   StringRequestEntity stringRequestEntity = new StringRequestEntity(
     "{}", "application/json", "UTF-8");
   postMethod.setRequestEntity(stringRequestEntity);
   int requestStatus = client.executeMethod(postMethod);
   serverResponse = postMethod.getResponseBodyAsString();
   Header locationHeader = postMethod.getResponseHeader("location");
   nodeLocation = locationHeader.getValue();
   postMethod.releaseConnection();
   System.out.println("Request Status : " + requestStatus);
   System.out.println("Node Location : " + nodeLocation);
   System.out.println("Server Response Json : " + serverResponse);
  } catch (Exception e) {
   System.out.println("Exception in adding a node to neo4j graph : "
     + e);
  }

  return nodeLocation;
 }

 /*
  * adding properties to nodes
  */
 public void addProperty(String SERVER_ROOT_URI, String nodeLocationPath,
   String propertyName, String propertyValue) {

  try {
   String nodePointUrl = nodeLocationPath + "/properties/"
     + propertyName;
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(nodePointUrl);

   /**
    * set headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set json payload
    */
   String jsonString = "\"" + propertyValue + "\"";
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out.println("Exception in adding propery to node : " + e);
  }

 }

 /*
  * adding relationship between two nodes
  */
 public String addRelationship(String firstNodeLocation,
   String secondNodeLocation, String relationship,
   String relationAttributes) {
  String relationOutputJson = null;
  String relationLocation = null;
  try {
   String fromUrl = firstNodeLocation + "/relationships";

   String relationshipJson = generateJsonRelationship(
     secondNodeLocation, relationship, relationAttributes);

   System.out.println("Relationship Json : " + relationshipJson);

   HttpClient httpClient = new HttpClient();
   PostMethod mPost = new PostMethod(fromUrl);

   /**
    * set request headers
    */
   Header mtHeader = new Header();
   mtHeader.setName("content-type");
   mtHeader.setValue("application/json");
   mtHeader.setName("accept");
   mtHeader.setValue("application/json");
   mPost.addRequestHeader(mtHeader);

   /**
    * set request json payload
    */
   StringRequestEntity requestEntity = new StringRequestEntity(
     relationshipJson, "application/json", "UTF-8");
   mPost.setRequestEntity(requestEntity);
   int nodesatus = httpClient.executeMethod(mPost);
   relationOutputJson = mPost.getResponseBodyAsString();
   Header locationHeader = mPost.getResponseHeader("location");
   relationLocation = locationHeader.getValue();
   mPost.releaseConnection();
   System.out.println("Node Satus : " + nodesatus);
   System.out.println("Relation node Location : " + relationLocation);
   System.out.println("output : " + relationOutputJson);
  } catch (Exception e) {
   System.out
     .println("Exception in adding relationship node in neo4j : "
       + e);
  }

  return relationLocation;

 }

 /*
  * used to create relationship json in required format
  */
 private String generateJsonRelationship(String secondNodeLocation,
   String relationship, String relationAttributes) {

  StringBuilder sb = new StringBuilder();
  sb.append("{ \"to\" : \"");
  sb.append(secondNodeLocation);
  sb.append("\", ");

  sb.append("\"type\" : \"");
  sb.append(relationship);
  if (relationAttributes == null || relationAttributes.length() < 1) {
   sb.append("\"");
  } else {
   sb.append("\", \"data\" : " + relationAttributes);

  }

  sb.append(" }");
  return sb.toString();
 }

 public void addPropertyToRelations(String relationshipLocationPath,
   String propertyName, String propertyValue) {

  try {
   String relPropUrl = relationshipLocationPath + "/properties";
   HttpClient httpClient = new HttpClient();
   PutMethod putMethod = new PutMethod(relPropUrl);

   /**
    * set request headers
    */
   Header header = new Header();
   header.setName("content-type");
   header.setValue("application/json");
   header.setName("accept");
   header.setValue("application/json");
   putMethod.addRequestHeader(header);

   /**
    * set request json payload
    */
   String jsonString = convertToNameValueJson(propertyName,
     propertyValue);
   StringRequestEntity requestEntity = new StringRequestEntity(
     jsonString, "application/json", "UTF-8");
   putMethod.setRequestEntity(requestEntity);
   int satusCode = httpClient.executeMethod(putMethod);

   putMethod.releaseConnection();
   System.out.println("Satus Code : " + satusCode);
  } catch (Exception e) {
   System.out
     .println("Exception in addding properties to a relation in neo4j : "
       + e);
  }

 }

 private String convertToNameValueJson(String name, String value) {
  return String.format("{ \"%s\" : \"%s\" }", name, value);
 }
}


\src\main\java\com\beingjavaguys\graphdb\App.java
package com.beingjavaguys.graphdb;

/**
 * @author Nagesh.Chauhan
 * 
 */
public class App {
 public static void main(String[] args) {
  final String SERVER_ROOT_URI = "http://localhost:7474";
  ServerUtils serverUtils = new ServerUtils();

  // getting server status
  int serverStatusCode = serverUtils
    .getNeo4jServerStatus(SERVER_ROOT_URI);

  if (serverStatusCode == 200) {
   // adding a blank node to neo4j db server
   String firstNodeLocation = serverUtils.addNode(SERVER_ROOT_URI);
   System.out.println("First Node Location: " + firstNodeLocation);

   // adding another blank node to neo4j db server
   String secondNodeLocation = serverUtils.addNode(SERVER_ROOT_URI);
   System.out.println("Second Node Location: " + secondNodeLocation);

   // adding properties to first node in server
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation, "name",
     "andrew");
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation,
     "email", "andrew@java.com");
   serverUtils.addProperty(SERVER_ROOT_URI, firstNodeLocation,
     "phone", "7876754346");

   // adding properties to second node in server
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "name", "smith");
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "email", "smith@java.com");
   serverUtils.addProperty(SERVER_ROOT_URI, secondNodeLocation,
     "phone", "8787653454");

   // adding a relationship in between two nodes
   String relationAttributes = "{ \"bestfriends\" : \"yes\",\"since\" : \"2005\" }";
   String relationshipLocation = serverUtils.addRelationship(
     firstNodeLocation, secondNodeLocation, "friend",
     relationAttributes);
   System.out
     .println("Relationship Location: " + relationshipLocation);

   // adding property to existing relation
   serverUtils.addPropertyToRelations(relationshipLocation, "common",
     "behavior");
  }
 }

}


Run Java application, if everything goes right you can browse nodes creted and relationship created using Location URI's(node numbers may be different refer your console to get URI's) like:

Node URI Like: http://localhost:7474/db/data/node/19



Relationship URI Like: http://localhost:7474/db/data/relationship/4



We came to know how to add node, relationships and properties to Neo4J db server using Java. By now you are able to understand the functioning of Neo4J API for Java. Other updating and deleting operations and query database can be performed like this by using appropriate JSON format and request type. There are a number of other useful operations like Updating and Deleting nodes and relationships and their properties. We will see how to query Neo4J db using Java in upcoming blogs.

Download complete Project : Download Link










Thanks for reading !
Being Java Guys Team

Download "Integrate Neo4j (Graph DB) with Java Example Project" from "SkyDrive"



Tuesday, 24 June 2014

100 Core Java Interview Questions and Answers - Part 10

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




91) What is synchronization in Java?

In java synchronization is the ability to control the access of multiple threads to shared resources. Synchronization ensures that only one thread can access a shared resource at a time.

92) What are wrapper classes in Java.

Java provides some equivalent classes to represent primitive types as object these classes are called wrapper classes. There are 8 wrapper classes in java ; Byte, Short, Integer, Long, Float, Double, Character and Boolean.

93) Can we have more than one class declaration in a single java file.

We can have only a single public class declaration per java file, whereas we can have multiple non-public classes in a single java file.

94) Can we declare main() method as private?

No, We cannot declare main() method as private. If we does so the program will compile fine but at runtime it will give “Main Method Not Public” message.

95) Explain System.out.println() briefly?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 9

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




81) What if, we import a class or package more than once in our program?

We can import a class or an package as many times as we want to, neither the compiler or the JVM will complain about it. But internally the class or package will be loaded once no matters how many times we have written the import statement.

82) What is the difference between a checked or unchecked exception in Java?

The classes which extends Throwable class except RuntimeException and Error are known as checked exceptions. These exceptions are thrown at compile time. E.g. IOException, FileNotFoundException etc. The classes which extends RuntimeException class are called unchecked exceptions. These exceptions are thrown at runtime. E.g. ArithmeticException,NullPointerException etc.

83) What is the root class of all Exception and Errors in Java.

Throwable is the base class for all Exceptions and Errors in Java.

84) Can we have a try block without a catch block in Java?

Yes, we can have a try block without having a catch block but a try block must be followed by either a catch or a finaly block or with both.

85) What are nested classes in Java?

A class that is declared inside another class is called nested class, there are four types of a nested class in java : member inner class, local inner class, annonymous inner class and static nested class.

86) What is volatile keyword in Java?

Threads hold their own copy of variables in local memory, if a variable is marked as volatile it means that the variable will be stored in main memory, every time a volatile variable is read it will be read from the main memory similarly every time the volatile variable is written the changes will be written to the main memory only.

87) What is the difference between path and classpath in java?

In context of java path and classpath both are operating system level environment variables. Path says where can the system finds .exe files whereas classpath tells the location of .class files within a system.

88) What do you mean by downcasting in Java?

In java downcasting means casting a general type to a more specific type.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 8

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




71) What are immutable objects in Java?

In java, immutable objects are the objects which can not be changed once created. Any change to the states of these object results in a new object. String objects are the example of immutable objects in java any change to the states of an String object results in a new object and the old object remains unchanged.

72) What is the difference between a StringBuffer and StringBuilder class in Java?

In java both StringBuffer and StringBuilder classes are immutable in nature, the only difference in between them is that StringBuffer class in thread-safe while StringBuilder is not thread safe in nature. StringBuilder class was introduced in Java5 to reduce the overhead of synchronization.

73) How many types of memory areas are allocated by JVM?

JVM allocated memory areas in many forms like:
1. Class(Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack

74) What if I changed the order of public static and void in ‘public static void main(String args[])’?

The program will compile fine and run properly, main() method implementation is regardless of the order of public, static and void keywords.

75) What is the default value for an instance variable in Java?

All instance variables are initialized to “null” by default.

76) What do you mean by composition in Java ?

Holding the reference of one class in another class in known as composition in Java.

77) Can be define an abstract method in an non abstract class ?

No, if a single method is declared as abstract in a class then the class must be declared as abstract itself.

78) Can we declare a class as abstract and final in Java?

No, we cannot declare an abstract method as final, abstract methods does not have body and they are meant to be overridden in another class, if we declare them final than its impossible to override them and hence no use of them.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 7

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




61) What if we does not pass an String array of objects to main() method ?

Program will compile fine, but at runtime it will give an error “NoSuchMethodError”.

62) List all primitive types in Java ?

There are a total of 8 primitive types in java; byte, short, char, int, long, Boolean, float and double. In java String is an object and not a primitive type.

63) Can we have multiple main() methods in the same class?

No, We can have multiple overloaded methods in a same class with name main(), but there must be a single method with signature ‘public static void main(String args[])’. Unless the compiler says main method already defined.

64) What is difference between “String” and “StringBuffer” class in Java?

In java, “String” is an immutable class whereas “StringBuffer” is not immutable in nature. This means that once a String object is created we cannot change its state. Every time an operation is performed on a String object, it results the creation of a new Object and the old object remains unchanged. Whereas in ‘StringBuffer’ because of being a non-immutable class, the changes are reflected to the same object on which the operation is performed.

65) What is transient variable in Java?

If we declare a variable as transient, it prevents that variable from being serialized. If a class is serialized to a stream and one tries to deserialize it again than the variable having transient with it return a null value.

66) Are “true” ,“false” and “null” keywords in Java?

No, Neither of the three true, false or null is a keyword in java.

67) Can we declare an abstract class as final.

No, we cannot declare an abstract class as final because abstract classes are meant to be extended by some other class to make it meaningful. If we declare a class final it cannot be extended by some other class and hence an abstract class cannot be declared as final.

68) What is the default value of a boolean type in Java?

In java a Boolean type variable is initialized to “false” by default.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 6

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




51) What is a List interface in Java? What are its implementation classes?

List interface is a part of Java Collections API, List interface extends Collection interface provides support for ordered collections of Objects. There are three well known implementation classes for List interface i.e. ArrayList, Vector and LinkedList , all these classes provides an ordered collection of objects and support duplicate values.

52) What is a Set interface in Java? What are the implementation classes ?

Like List interface Set is another interface which is a part of Java Collections API and extends Collection interface, it does not permit duplicate values in it. The well known implementation classes for a Set interface are HashSet and TreeSet.

53) What is a Map interface in Java ? What are the implementation classes ?

Like List and Set interfaces, Map is also a part of Java Collections API but it does not extends Collection interface. Map provides a key value pair of Objects and some implementation like HashMap permits null whereas some implementation like HashTable does not allows null. HashMap, TreeMap and HashTable are three well known implementation of a Map interface.

54) What is the advantage of an ArrayList over Arrays in Java ?

ArrayList are resizable arrays, it can grow dynamically. ArrayList provides better implementation of searching, iterating, deleting or inserting an element than arrays.

55) What are well known implementations of a List interface in Java?

List interface have three well known implementations, described below:
1) ArrayList: ArrayList is an growable array with fast iteration and fast random access. It is an ordered by index collection and is not sorted in nature. It can be considered over linkedlist when we need more iteration and random access and less insertion or deletion.
2) Vector: Vector are almost as same as the ArrayList except that, methods of an Vector are synchronized and hence safe to use in a thread environment. One should use arraylist over vector if there is no need of thread safety.
3) LinkedList: Linked list is another implementation of List interface in java, elements in a linked list are ordered by index and are double-linked to each other. Because of this it provides adding or removing elements from both sides and hence it may iterate slow than ArrayList but insertion and deletion is much more fast that ArrayList.

56) What are the well known implementations of Set interface in Java?

There are three well known implementation of a Set interface as described below:
1) HashSet: A HashSet is an unsorted and unordered set, it uses the hash code of the objects being inserted, so the performance all depends on how well the hash code implementation is. This ensures uniqueness of elements and does not allow duplicates.
2) TreeSet: TreeSet is a sorted Set which ensures elements will be in ascending order naturally, it uses a red-black tree structure to store elements. Optionally we can construct a TreeSet with descending ordering of elements.
3) LinkedHashSet: LinkedHashSet is an ordered version of HashSet, when we uses HashSet we cannot predict the order of iteration, while in LinkedHashSet the order of elements remains unchanged.

57) What are the well know implementations of a Mao interface in Java?

There are three well known implementation of a Map interface as described below:
1) HashMap: HashMap provides an unsorted and unordered collection to store key value pairs. It cares about uniqueness of keys, HashMap allows one null key and multiple null values in it.
2) HashTable: HashTable is a synchronized version of HashMap, all the methods in a HashTable are thread safe. HashTable does not allows null keys or null values.
3) TreeMap: Like TreeSet, TreeMap is an ordered Map, which persists elements in ascending order.

58) What do you mean by pass by reference and pass by value in context of Java?

In context of a Java program, pass by value means passing a copy of the value, while pass by reference means passing address of the value rather than the value itself.











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 5

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




41) Can a class extend more than one class in Java?

No, java does not support multiple inheritance. In java a class cannot extends more than one class but it can implement as many interfaces as it wants.

42) Can we declare a class inside an interface and vice verse?

Yes, we can declare an interface inside a class and a class can be declared inside an interface, both statements are true.

43) What do you mean by a marker interface In Java?

An marker interface is an interface which does not contain any variable or method in it, these interfaces are implemented by some classes to provide special instructions to JVM. The example is serializable interface this interface does not contain anything in it, it tell the JVM that the class which implements this interface needs to be serialized.

44) What modifiers are allowed inside an interface in Java?

In java, interfaces can have public and abstract types of variables and methods in them. All the variables and methods are public abstract by default in an interface.

45) What is a constructor in java? Can constructors be overridden?

Constructors are special type of methods that have the same name as the class itself and do not have a return type not even void. Constructors are used to create an object of a class, if we do not declare any constructor in our class than JVM provides a non argument constructor by default. Constructors cannot be overridden, though a subclass can call the constructor of its super class.

46) What access specifies are available in Java?

In java there are four access specifies listed below their scope and usability.
1) public : public classes, methods and variables can be accessed from anywhere in the application, No restriction at all.
2) private: private variables and methods can be accessed in the same class only in which they are declared and not outside that, private variables and methods can not be accessed even in the subclasses.
3) protected: protected variables and methods can be accessed from anywhere in the same package and in the subclasses of same class outside the package.
4) default(no specifies): If a variable or method does not have any specifier than these can be accessed from anywhere within the same package and not outside the package.

47) What are static blocks in Java?

Static blocks are executed exactly once even before the main method is executed, these blocks are executed by jvm at the time of classes loaded in memory.

48) What is an Iterator in Java?

The Iterator is an interface which is used to step through a collection in java, Iterator has its own implementation for difrenet type of collections. Iterator has three methods next(), hashNext() and remove().











Thanks for reading !
Being Java Guys Team



100 Core Java Interview Questions and Answers - Part 4

Here are top selected core java interview questions asked in high level interviews, these questions may be helpful for both freshers or experienced professional going for interview.




31) How to prevent a method from being overridden in Java?

To prevent a method from being overridden in java we have declare the method as final, if a method is declared as final that a subclass cannot override it.

32) What if a class is declared as final in Java?

If we declare a class as final in java, than it cannot be extended by other class. A abstract class cannot be declared as final.

33) What is the difference between final, finally and finalize in Java ?

‘final’ is a modifier which can be applied to a class, variable or a method. A final class can not be subclassed , a final method can not be overridden and a final variable can not be changed once created. finally is a exception handling block which is executed regardless the exception is being raised or not in try catch blocks. finalize() is a method from Object class which is being called by the garbage collector to give a final chance to unused objects to release their activity before removed from the memory.

34) What if a method is declared as static in Java?

We declare a method as static in java, when we need to access that object even before the creation of the object of that class, static methods can be called with the name of class only.

35) What if a variable is declared as static in Java?

If a variable is declared as static, than it is assumed as a class level variable. All the instances of that class will share a common copy of thet variable that means of one instance changed the value of a static variable than the change is being reflected to all other instances of the class.

36) Can we declare a local variable as static in Java?

No, static variables are class level variables we cannot declare a local variable as static. If we do so, it will give a compile time error.

37) What is an Abstract class in Java? And why do we need it?

An abstract class is a declared with abstract modifier, we cannot instantiate an abstract class, so abstract class must be extended by some other class to make sense. Abstract class can have both abstract and concrete methods in it. Abstract class is useful in obtaining abstraction in own program.

38) Can an interface implement another interface in Java ?

No, not possible. In java one interface extends another interface and not implement that.











Thanks for reading !
Being Java Guys Team



Search Tutorials
Like Us on Facebook

Like Us On Google+