Showing posts with label Java/J2EE. Show all posts
Showing posts with label Java/J2EE. Show all posts

in Java, what are the ways to create an object?

Hi Folks,

After a long time I am back with the new post to discuss about the ways of creating a new object in java.

Basically there are multiple ways in which you can create an object instance in java and those are as below:

1. Using new keyword

2. Using class.newInstance()

3. Using class.getConstructors()

4. Using clone()

5. Using Object de-serialization
Make sure the employee class implements Serializable interface

So these are some of the ways in which we create objects in java. Let me know what did you felt about this blog in comments section.

In java how does HasSet enures unique values?

Let us discuss on how the HashSet in java prevents adding the duplicate values. First let us understand how to create a HashSet and add some values to it.

public class HashSetTest{
    public static void main(String[] args)
        HashSet<String> hashset = new HashSet>();
        System.out.println("Set is "+hashset);

Output would be : Hubli, Bangalore,Mysore

What about the insertion order in the above output? Does the insertion order not maintained? Yes in a HashSet the insertion order is not maintained also the values in a HashSet are not sorted.

Now to the above code let us try to add some duplicates as below:

public class HashSetTest{
    public static void main(String[] args)
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add("Hubli");          // duplicate elements
        hashset.add("Bangalore");      // duplicate elements
        System.out.println("Set is "+hashset);

Now the output would be: Bangalore, Mysore, Hubli
Did you notice add() method of HashSet ignored the duplicates? Now the question is how?
When you pass duplicate elements in the  add() method of the Set object, It will return false and do not add to the HashSet, as the element is already present.

Let us go into further deep:

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable,

    private transient HashMap<E,Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    public HashSet() {
        map = new HashMap<>();
    // SOME CODE ,i.e Other methods in Hash Set
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    // SOME CODE ,i.e Other methods in Hash Set

So , we are achieving uniqueness in Set internally in java through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

Learning OpenJPA step by step

 Hi Folks,

Java persistence framework is high on demand now days. If you mention JPA in your resume, it will catch hold of the interviewer and can influence in fetching you the job. (Ha ha I am not joking here! though some of you might be thinking :)-)

Ok lets come back to our topic JPA i.e. Java Persistence API.The Java Persistence API provides an object/relational mapping for managing relational data in enterprise beans, web components, and application clients. It can also be used in Java SE applications, outside of the Java EE environment.

Now we will try to understand practically how this will work.

1> Download and install latest eclipse IDE. In my case I have used Eclipse Indigo.
2> Download the latest apache tomcat. I have tomcat7.0
3> Once you have downloaded the tomcat extract it and keep it in a folder.
4> Now in eclipse IDE, select File > New > other and pick Server from the list.  

Click Next and select Tomcat v6.0 Server for the server definition. You'll need to
select a run time.

 Click on Add link and you will be prompted for the next window to add server runtime configurations.
Click on Browse button to add the location of tomcat directory where you have extracted the tomcat. Then click finish. Upon clicking finish it will take back you to previous window. In that also you click on Finish button.
Now you are done with server configurations. Now let’s start building a dynamic web project to learn JPA.
5> Click on File->New->Dynamic Web Project
Name your project and click on Next button.
No need to do anything, just click Next button.
Check generate web.xml checkbox and click on Finish.
Now you are done with creating dynamic web application! Congratulations! Now let’s add the required library files to the build path. Below are the required jar files.
ü      mysql-connector-java-5.1.21-bin.jar (Off course I am using MySQL as my DB!)

To add these libraries to the build path of your project (off course you should download them before from the links provided and add them into you WEB-INF/lib location.) just right click on your project->Properties->Java Build Path.
Then click on add Add JARs button and then click on your project->Web Content->WEB-INF->lib then select the jars and click OK button.
Next go to Order and Export tab click on Select All button and then click on OK button.
6> Now let’s create our first entity. Note that we have used Java Annotations in this class.
Right click on the project->New->Class
Give the package name as com and class name as User and click on Finish button.

Now the contents of the class User is as below.

package com;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Author              : Sanjeev Kulkarni
@Created on          : 05-Oct-201212:25:13 PM
@Project             : a
@Package             :
@File                :
@Comments            :

Revision History     :
Sl No. | Revision Date      | Changed By               | Reasons           

public class User implements Serializable{
       private static final long serialVersionUID = 975983410088693889L;
       public User(){


       private int id;
       private String name;

       public int getId() {
              return id;

       public void setId(int id) {
     = id;

       public String getName() {
              return name;

       public void setName(String name) {
     = name;

Now lets create a JSP page to print list of users from the database using openjpa.

Right click on project->New->Other->Web->JSP File and then click on Next button. Give the name of the file as NewFile.jsp and click Finish button.

Now copy and paste the content of NewFile.jsp as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@ page import="com.User" %>
<%@page import="javax.persistence.Persistence"%>
<%@page import= "javax.persistence.Query"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

 final EntityManagerFactory emf;
 final EntityManager em;
 final String PERSISTENCE_UNIT_NAME = "projectjpa";

 emf = Persistence.createEntityManagerFactory("projectjpa");
 em = emf.createEntityManager();


 User user = new User();
 Query query = em.createQuery("select x from User x ");

 out.println("Query returned: " + query.getResultList().size());
catch(Exception e){


Modify the web.xml descriptor file. Mention NewFile.jsp as a welcome file.

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">

In the src folder create a folder called META-INF and inside that create a file called persistence.xml.
Copy and paste the below content into the persistence.xml file.

xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns=""

       <persistence-unit name="projectjpa">

                     <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
                     <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
                     <property name="openjpa.ConnectionUserName" value="root"/>
                     <property name="openjpa.ConnectionPassword" value="root"/>
                     <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
                      <property name="openjpa.DynamicEnhancementAgent" value="false"/>
                     <property name="openjpa.RuntimeUnenhancedClasses" value="supported"/> 

7> Now open MySQL command prompt and create a database called test.
Mysql> create database test;
Mysql>use test;
Mysql>create table user (id int not null primary key, name varchar(200));
Mysql> insert into user vales(1,’ABC’);
Mysql> insert into user vales(2,’XYZ’);
8> Now right click on the project->Run As->Run on Server
9> You should be able to open the eclipse internal web browser and should be showed the result as below:
Query returned: 2