Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Saturday, December 21, 2013

Different between session.get() and session.load()


There are two methods that can be used on a Hibernate session (org.hibernate.Session) to retrieve a single instance of persistent object. They are get( ) and load( ).

Note: In hibernate4.x there is one more method to get a single instance called byId(). See more details in below.



If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found.
While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance. On the other hand, get() never returns a proxy. 

1. session.load()
  • Use this method if it is sure that the object exist
  • It always return “proxy” instead of a real persistent instance. A proxy is a placeholder that triggers the loading of the real object when it’s accessed for the first time.
  • If no row found , it will throws an ObjectNotFoundException.

methods:
load(Class clazz, Serializable id)
load(Class clazz, Serializable id, LockMode lockMode)
load(String className, Serializable id)
load(String className, Serializable id, LockMode lockMode)
load(Object object, Serializable id)

2. session.get()

  • Use this method if it is not sure that the object exist.
  • It always hit the database and return the real object, an object that represent the database row, not proxy.
  • If no row found , it return null.
 
methods:
get(Class clazz, Serializable id)
get(Class clazz, Serializable id, LockMode lockMode)
get(String className, Serializable id)
get(String className, Serializable id, LockMode lockMode)

Example:

Person.java
================================
package com.ranga.mapping;
import java.io.Serializable;
public class Person implements Serializable {
   
   private long id;
   private String firstName;
   private String lastName;
   private int age;
   
   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 int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
   @Override
   public String toString() {
       return "Person [id=" + id + ", firstName=" + firstName + ", lastName="
               + lastName + ", age=" + age + "]";
   }    
       
}

Person.hbm.xml
=======================
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ranga.mapping">
   <class name="Person" table="Persons">
       <id name="id">
           <generator class="increment"/>               
       </id>
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />        
   </class>
</hibernate-mapping>

hibernate.cfg.xml
=============================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
       <!-- Database connection settings -->
       <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
       <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
       <property name="connection.username">ranga</property>
       <property name="connection.password">ranga</property>
       <!-- JDBC connection pool (use the built-in) -->
       <property name="connection.pool_size">1</property>
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
       <!-- Enable Hibernate's automatic session context management -->
       <property name="current_session_context_class">thread</property>
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">false</property>
       <!-- Drop and re-create the database schema on startup -->
       <property name="hbm2ddl.auto">create</property>
       <mapping resource="com/ranga/mapping/Person.hbm.xml" />
   </session-factory>
</hibernate-configuration>

App.java
======================
package com.ranga;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ranga.mapping.Person;
import com.ranga.util.HibernateUtil;

public class App {
   public static void main(String[] args) {
       SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
       Session session = sessionFactory.openSession();
       session.beginTransaction();
       Person p1 = new Person();
       p1.setFirstName("ranga");
       p1.setLastName("reddy");
       p1.setAge(25);
       long pId = (Long) session.save(p1);
       session.getTransaction().commit();

       // get() method
       Person person = (Person) session.get(Person.class, pId);
       System.out.println(person);

       // load() method
       person = (Person) session.load(Person.class, pId);
       System.out.println(person);
       
       person = (Person) session.get(Person.class, 100l);
       System.out.println(person);

       // load() method
       person = (Person) session.load(Person.class, 100l);
       System.out.println(person);
       session.close();
   }
}

Output:

Person [id=1, firstName=ranga, lastName=reddy, age=25]
Person [id=1, firstName=ranga, lastName=reddy, age=25]
null
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.ranga.mapping.Person#100]
------------------------------------------------------------------------------------------------------------------------

byId(): Hibernate4.x support one more method to retrieve a single instance i.e byId()

IdentifierLoadAccess byId(String entityName) - Create an IdentifierLoadAccess instance to retrieve the specified entity type by primary key.
IdentifierLoadAccess byId(Class entityClass) - Create an IdentifierLoadAccess instance to retrieve the specified entity by primary key.

Obtaining an entity reference without initializing its data:

Person person = (Person) session.byId(Person.class).getReference(personId);
System.out.println("By using byId() with reference: "+person);

Person person = (Person) session.byId(Person.class).getReference(100l);
System.out.println("By using byId() with reference: "+person);

Output:
By using byId() with reference: Person [id=1, firstName=ranga, lastName=reddy, age=25]
By using byId() with reference: Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.ranga.mapping.Person#100]

Obtaining an entity with its data initialized:

Person person = (Person) session.byId(Person.class).load(orderId);
System.out.println("By using byId() with load(): "+person);
       
Person person = (Person) session.byId(Person.class).load(100l);
System.out.println("By using byId() with load() "+person);

Output:
By using byId() with load(): Person [id=1, firstName=ranga, lastName=reddy, age=25]
By using byId() with load(): null

Wednesday, December 18, 2013

Write a program to print the 3rd fibonaci number in a given range. If the number doesn't fall in the given range then print 0.

Given two number 10 and 150, you should print the 3rd fibonaci number after 10. The fibonaci numbers after 10 are 13, 21, 34, 55, 89, 144. The third fibonaci is 34.

Given input
10
150
Expected output
34
Program:  
package com.ranga;
class FibonacciSeriesDemo
{
    public static void main (String[] args)
    {
        int first = 0, second = 1, fib = first + second, count = 0;
        int start = 10, end = 150;
        boolean found = true;
        while(fib < end && found) {
            fib = first + second;
            if(fib >= start) {
               count = count + 1;
               if(count == 3) {
                    found = false;
               }
            }
            first = second;
            second = fib;
        }
        if(!found) {
          System.out.println("Third Fibonacci Series Value: "+ fib);  
        } else {
          System.out.println("Third Fibonacci Series Value: "+ 0);
        }
      
    }
}
Output:
Third Fibonacci Series Value: 34
 Note: This program is asked one guy in Facebook.

Tuesday, December 10, 2013

Difference between Constructor and Method

Constructor
Method
Constructor is a special method of a class but can’t be invoked directly by method call.
Methods are member of a class.
           It is not a member of a class as it can neither be inherited nor invoked using dot (.) operator.
Dot (.) operator is used to invoke Non static methods via object and static methods via class name.
        It has no explicit return type.
It has explicit return type, if there is nothing to return, the return type must be void.
        It has the same name as its class name.
Can have same name as its class name, but the existence of return type makes it a method.
         It is used to initialize the objects, members of object and then execute statements if any.
Used to execute statements.
         A no-argument, Default constructor is provided by compiler when no explicit constructor is there. In such case instance members are initialized with their default values (numeric data types are set to 0, char to ‘\0’ and reference variable to null).
Local variable must be initialized explicitly.
         If there is no this() as the first statement, super() will be there as first statement in the constructor.
‘this’ is implicitly invoked on all the member in non-static methods, but need explicit invocation in case of name confliction.
Syntax: this.x, this.go()
         The default constructor will call the default constructor of its super class due to presence of super() as its first statement.
‘super’ can be used to explicitly invoke member of super class (specially used either in case of name conflict or to call method of super class when overridden in sub-class )
syntax:
super.member: when name conflict
super.method(args if any) : when overriden
         A constructor can never be abstract or static.
A method is of two types defined (implemented) or undefined (abstract). The method implementation can be further categorized as static or non-static. An abstract method can’t be static or final.
     Can be specified as public, none (default), protected or private.
Access-specifier public, none (default), protected or private are applicable.
     Can’t be final, native, or synchronized. (Constructor can take only access specifier)
Can be final, native, static or synchronized.
     Can be invoked by either
a.       new ClassName()
b.      this(args if any)
c.       super(args if any)
d.      getInstance()
Can be invoked by Class name in case of static method or by object/this in case of non-static method.

Difference between Abstraction and Encapsulation


In Java both Abstraction and Encapsulation are two important OOP (Object Oriented Programming) concepts or principles. Both are completely different from each other.
 
Abstraction(Hiding): Abstraction means hiding.

Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object.

For example, while making JDBC connection, Connection interface refer to an instance of a class which is implemented by any of the third party vendor, so we don't know what is the implementation details of the driver.

Another example is, when we use String.substring() method, we just have to worry about using the substring() method according to its specifications. We should not be bothered about or try to change the way the substring() method is defined in the String class.

Abstraction can be implemented by using Interface, Abstract class, Abstract methods using "abstract" keyword. It hides certain details of the object that are not important and display that are essential.

Abstraction focuses on the outside view of an object (i.e. the interface).

Advantages:
1. Code will be clean and for managing it will be very easy
2. Data can be accessed by member functions of class only and any external function can't manipulate the data. The data is more secure.

Example:

package com.ranga;

abstract class Student {
  private long studentNo;
  private String name;
  public abstract int totalMarks();

  protected Student(long studentNo, String name) {
    this.studentNo = studentNo;
    this.name = name;
  }

  public long getStudentNo() {
    return studentNo;
  }

  public void setStudentNo(long studentNo) {
    this.studentNo = studentNo;
  }

  public String getName() {
    return name;
  }

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

  @Override
  public String toString() {
    return "Student{" +
        "studentNo=" + studentNo +
        ", name='" + name + '\'' +
        '}';
  }
}

class StudentImpl extends Student {
  private int marks1,marks2;
  @Override
  public int totalMarks() {
    return this.marks1+this.marks2;
  }
  StudentImpl(long studentNo, String name, int marks1, int marks2) {
    super(studentNo,name);
    this.marks1 = marks1;
    this.marks2 = marks2;
  }
}

public class AbstractionDemo {
  public static void main(String[] args) {
    Student student = new StudentImpl(100,"Ranga",50,60);
    System.out.println("Student Info: "+student);
    System.out.println("Student Total Marks: "+student.totalMarks());
    System.out.println("----------------------------------------");

    StudentImpl student1 = new StudentImpl(1043,"Ranga Reddy",60,40);
    System.out.println("Student Info: "+student1);
    System.out.println("Student Total Marks: "+student1.totalMarks());

  }
}

Output: 
Student Info: Student{studentNo=100, name='Ranga'}
Student Total Marks: 110
----------------------------------------
Student Info: Student{studentNo=1043, name='Ranga Reddy'}
Student Total Marks: 100

 

Encapsulation(Binds): Encapsulation means binding.

Encapsulation is a process of binding or wrapping the data and its associated members into a single unit. It is also called data hiding.

Class is the best example of encapsulation. 

Another example is Capsule.

Encapsulation can be implemented using private, package-private and protected access modifier.

Encapsulation(information hiding) prevents clients from seeing its inside view.

We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters.
Advantages:
  1. Maintenance will be good.  
  2. Encapsulation allows you to change one part of code without affecting other part of code.
  3. By using Encapsulation we can write immutable classes in Java.
Example:
EncapsulationDemo.java

package com.ranga;

class Student {

  // data members
  private long no;
  private String name;
  private int age;

  // member functions
  public long getNo() {
    return no;
  }

  public void setNo(long no) {
    this.no = no;
  }

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "Student{" +
        "no=" + no +
        ", name='" + name + '\'' +
        ", age=" + age +
        '}';
  }
}

public class EncapsulationDemo
{
    public static void main( String[] args )
    {
      Student student = new Student();
      student.setNo(100);
      student.setName("Ranga");
      student.setAge(25);
      System.out.println(student);
    }
}


Output:
Student{no=100, name='Ranga', age=25}

Note: In the above Student class, we are making data members and it's associated members into a single component or single unit.

Friday, December 6, 2013

Difference Between ClassNotFoundException and NoClassDefFoundError


ClassNotFoundException (java.lang.ClassNotFoundException): 
ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class.
public class ClassNotFoundException extends Exception
}
Note:  java.lang.ClassNotFoundException is an Exception Which is checked. So we need to handle the exception by using either try-catch or finally block.

A ClassNotFoundException is thrown when the ClassLoader could not find the required class in the CLASSPATH.

When an application tries to load in a class through its string name using:
  1. The Class.forName() method
  2. The  ClassLoader.loadClass() method
  3. The ClassLoader.findSystemClass() method
but no definition for the class with the specified name could be found.

Some of the possible reasons to get this exception is
  1. The class is missing from the classpath.
  2. The class in question is trying to be loaded from another class which was loaded by different classloader.
    This is an Exception, so can be handled using Exception handling in Java.
    Example:
    ClassNotFoundExceptionDemo.java
    public class ClassNotFoundExceptionDemo {
    public static void main(String[] args) throws Exception{
    Class myClass = Class.forName("Test");
    }
    }
    [ranga@ranga java]$ javac ClassNotFoundExceptionDemo.java
    [ranga@ranga java]$ java ClassNotFoundExceptionDemo
    Exception in thread "main" java.lang.ClassNotFoundException: Test
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:169)
        at ClassNotFoundExceptionDemo.main(ClassNotFoundExceptionDemo.java:3)
    [ranga@ranga java]$

    To avoid ClassNofFoundException exception, you need to take care of following things.
    1. Make sure that Class is available in the logical class path of the class loader associated with the class.
    2. Make sure that Class Loader API is used properly .ie whether a wrong class Loader is engaged in Class.forName().
    3. Make sure that dependent class of the class being loaded is visible to the class  loader.
    NoClassDefFoundError (java.lang.NoClassDefFoundError): 

    NoClassDefFoundError is an Error derived from LinkageError which extends java.lang.Error class.
    public class NoClassDefFoundError extends LinkageError {
    }  
    Note:  java.lang.NoClassDefFoundError is an Error Which is unchecked. So no need of Error  of try-catch or finally block.

    NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. NoClassDefFoundError can be thrown during linking or loading of class file.

    So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
    This is an Error, means thrown by JVM so can't be recovered and program crashed.
    Some of the possible reasons to get this error is
    1. If a dependent class cannot be located and loaded means the directly referenced class might have been located and loaded, but the dependent class is not available or cannot be loaded.
    2. You are using some library, like hibernate or spring, or Apache commons, and forgot to add this jar to your CLASSPATH.
    3. Bad format of the class
    4. The version number of a class not matching.
    Example :
    NoClassDefFoundErrorDemo.java

    public class NoClassDefFoundErrorDemo {
        public static void main(String ranga[]) throws Exception {
           Test test = new Test();
        }
    }
    class Test {
      Test() {
        System.out.println("Test()");
      }
    }

    Now compile the NoClassDefFoundErrorDemo.java class.

    [ranga@ranga java]$ javac NoClassDefFoundErrorDemo.java

    [ranga@ranga java]$ ls
    NoClassDefFoundErrorDemo.class  NoClassDefFoundErrorDemo.java  Test.class

    After compilation you can see the two .class files(NoClassDefFoundErrorDemo.class and Test.class). Now delete Test.class file (I did in Linux Terminal).

    [ranga@ranga java]$ rm -r Test.class

    Finally run the NoClassDefFoundErrorDemo class file.
    [ranga@ranga java]$ java NoClassDefFoundErrorDemo
    Exception in thread "main" java.lang.NoClassDefFoundError: Test
        at NoClassDefFoundErrorDemo.main(NoClassDefFoundErrorDemo.java:3)
    Caused by: java.lang.ClassNotFoundException: Test
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        ... 1 more
    [ranga@ranga java]$

    Similarities:
    1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
    2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

     
    About ClassLoader:
    A class loader is a Java object responsible for loading classes. Basically a class loader attempts to locate or generate data that constitutes a definition for the class. One of the key points to understand is that Java class loaders by default use a delegation model to search for classes. Each instance of ClassLoader has an associated parent class loader. So let’s say that your application class loader needs to load class A. The first thing that it will attempt to do is to delegate the search for Class A to its parent class loader before attempting to find the Class A itself. You can end up with a large class loader chain with many parent class loaders up to the JVM system classpath bootstrap class loader.