Showing posts with label Java Interview Questions. Show all posts
Showing posts with label Java Interview Questions. Show all posts

Monday, 23 December 2013

what is the difference between interface and abstract class?


what is the difference between interface and abstract class?

interface:
1.any specification requirement service is called interface.for example sun people develop a jdbc API and the implementation is given by vendors.
2.If we don't know anything about the implementation and we should know only specific requirements then we should go for interface.
3.we are defining every method in a interface as public and abstract.whether we are declaring or not a method in a interface.
4.In interface only contain declaration but it does not contain any implementation.
5.In interface we can use a keyword implements.
6.In interface we are declaring any variable as public static final
7.we cannot declare the interface methods with modifiers private,protected,final,static.
8.inside interface we cannot take constructor
9.inside interface we cannot take static and instance blocks.

abstract class:
1.An abstract  class contain abstract methods and non abstract methods.
2.If we know about the implementation but not purely and we specific requirements then we should go for abstract class.
3.In abstract class declaring of every method need not be a public and static.
4.In abstract class we can use the keyword extends
5.In the abstract class we can take constructor.
6.Inside of the abstract class we can take static and instance blocks.
7.By using abstract class we can extends only one class.
8.It is not require to perform the initialization of the variable.
Read More

Monday, 9 December 2013

Spring Framework concepts



Spring Framework concepts 
Spring framework is a light weight component for creating a java ee applications.Spring framework  is an abstraction layer on top of the existing technologies. A spring framework will provide common functionalities for the projects as ready made,and the developer will build the remaining code for the projects.

In this Spring framework have mainly 3 injunctions are there.There are
  1.setter injection
  2.construction injection
  3.interface injection

Setter Injection: In a spring framework if the dependencies  are injected by calling the setter method of an object at run time  then is called a setter injection.
Constructor Injection: if the dependencies are injected by calling the constructor of an object at run time then it is called constructor injection.
Interface Injection: if the dependencies are injected by the calling a method provided by a interface  then it is calling interface injection.

Spring framework supports all the three types of dependency injections.The interface injection is supported only at particular time,that is in a bean life cycle process.

setter injection example:
   
 public class TravelService
 {
     private Vehicle vehicle
     {
     public void setVehicle(Vehicle vehicle)
      {
          this.vehicle=vehicle;
       }
    }

constructor injection example:
   
 public class TravelService
 {
     private Vehicle vehicle
     {
     public  TravelService(Vehicle vehicle)
      {
          this.vehicle=vehicle;
       }
    }

interface injection example:
   
 public class Demo implements BeanFactoryAware
 {
     private BeanFactory fact;
     {
     public void set BeanFactory(Beanfactory fact)
      {
          this.fact=fact;
       }
    }
-->here interface provided  method is used for injecting the dependency.So it is a interface injection.

Spring Bean: Spring bean is a pojo class. And a spring bean may or may not contain the default constructor.
The difference between the spring bean and the java bean is java bean may contain a default constructor,in spring bean mayor may not contain the default constructor.

To create a spring application required files are
-->Bean class
-->web.xml
-->client class


Steps for creating a spring bean object in a client application:

step-1: create a resource object
        Resource r=new ClassPathResource("beans.xml");
step-2: create spring container object
            BeanFactory factory=new XmlBeanFactory(r);
step-3: get the bean object from the container by using id  with calling getBean()method
            Object o=factory.getBean("id");
step-4:Type cast the Object class to our spring bean object.the it calls our business method.
          DemoBean db=new DemoBean();
            db.showMessage();

Read More

Monday, 28 October 2013

Importance of the hashCode() method in java:


 Importance of the hashCode() method in java:
More frequently used in hashCode() method in design patterns.In interview point of view mostly asked question is hashCode() method and its importance.Now we will see the hashCode() method and its working.

hashCode() method:
--->If we want to use a class object as a key in a hashing collection of java then that class must be override hashCode() method and equals() method.
--->hashCode() method belongs to java.lang.Object class
--->if we don't override a hashCode() method in a class then Object class hashCode() method will be called.It will returns the memory address of an object in the form of an integer.
--->wrapper classes and string classes of java are already overriden a hashCode() method and equals() method. So we can use these class object as key in collections.
Some important points to remember with respect to hashCode() method
i)If two references are referring same object then always their hash Code's are equal.---->true
example:
    String s1="Aa";
    String s2=s1;
     s1==s2 ------>true
     s1.hashCode()=2112
     s2 .hashCode()=2112
So if two references are refer same object then their hash Codes are equal.
we can find the hashCode of a  string by using the fallowing formula.
     String=number format 1st character*31 pow(n-1)+number format of 2nd character *31 pow(n-2)
     Aa=65*31 pow(2-1)+97*31 pow(2-2)
          =65*31+97*1  
          =2015+97
          =2112

ii)If two hash Codes are equal then they are referring one Object                              ----->false.
example: 
     String s1="Aa"
     String s2="Aa"
   s1==s2     ---false
    s1.hashCode()=2112
    s2.hashCode()=2112
above example hasCodes are equal but they are referring two different objects.

iii)If two objects are meaningfully equal then they are hash Code's are equal(by force)----->true
    
-->when we are creating  user defined class the it is our responsibility  to override hashCode() method and equals() method.

example:
     class Demo
      {
           private int x;
            public Demo(int x)
             {
                this.x=x;
               }
            @Override
               public boolean equals(Object o)
                {
                 if(o instanceof Demo&&(((Demo).x)==this.x))
                 {
                    return true;
                      }
                  else
                   {
                       return false;
                       }
                   }
            @Override
                   public int hashCode()
                    {
                      return x+50;
                     }
                }
               class Main
                {
                  public static void main(String args[])
                   {
                      Demo d1=new Demo(20);
                      Demo d2=new Demo(20);
                          if(d1==d2)
                           {
                             System.out.println("d1 and d2 are identically equal");
                            }
                            if(d1.equals(d2))
                            {
                           System.out.println("d1 and d2 are meaningfully equal");
                            }
                        System.out.println("d1.hashCode()");
                         System.out.println("d2.hashCode()");
                      }
                   }
output:
    d1 and d2 are meaningfully equal
    70
    70

Difference between the hashCode()  method and equals() method?
ans:
---> both methods are overriden ,when an object of a class wants to be used as a key in a collection.
--->To store the data in a hash bucket hashCode() method will be called.But to read the data from a hash bucket first  hashCode() method will be called and the equals()method is called.

             
Read More

Sunday, 27 October 2013

In interview point of view important questions in java:



In interview point of view important questions in java:
In java mostly asked questions are based on the some methods in java.Some important methods are like toString()method,equals()method and hashCode()methods and their differences.Now we are going to see these methods and their importance.

1.toString() method:
ans:
-->generally toString() method is overriden in a class,to read an object's in a text format.
--->when we pass a java class object as parameter to the System.out.println statement internally toString() method of the object will be called.
--->if class doesn't override a toString() method then toString() method of the java.lang.Object class will be called.
--->toString() method of java.lang.Object class will return like the fallowing
       Class name@unsigned hexadecimal format of the object's hashCode.
for example:
     public class Demo
     {
        private  int x;
        public Demo(int x)
         {
           this.x=x;
          }

        public static void main(String args[])
         {
             Demo  d=new Demo(10);
              System.out.println(d):
           }
      }
-->in this above example we can not override the toString() method.So Object class toString() method will be called.we are getting the output as like the fallowing
output:
Demo@3e25a25
-->But we are override the toString()method in our program we can get the correct result.
example:
public class Demo
{
   private int x;
   public void Demo()
    {
      this.x=x;
     }
      public String toString()
      {
        return x="+x;
       }
   public static void main(String args[])
    {
       Demo d=new Demo(10);
     System.out.println(d);
    }
}
output: x=10

2.equals() method:
ans:
---->In java to compare two Objects like the fallowing.
     i) == operator for identical comparison
     ii)equals() method for meaningfully comparison.
--->The operator == returns true then two objects references are referring same object.Other wise it referring two different objects.
--->The operator equals() method returns true ,if the values are meaningfully equal other wise they are not equal.
--->if equals() method is not overriden in a class then the java.lang. Object class equals() method will be called.
-->equals()method  of object class internally calls == operator for comparing two objects.So there is no difference between the ==operator and equals() method of Object class.
example:
Note:For the wrapper classes Boolean,Integer,Short,Byte,Character.if the values of the objects are same then jvm creates only one Object.
example:
Integer i1=120;
Integer i2=120;
 i1==i2 ------>true
i1.equals(i2) ----->true

Integer i1=250;
Integer i2=250;
i1==i2 ---->false
i1.equals(i2) --->true

--->if the wrapper class range is exceeded then  two objects are created other wise it one object is created.
example:
class Main
{
  public static void main(String args[])
   {
     Integer i1=120;
     Integer i2=120;
    if(i1==i2)
   {
     System.out.println("i1 and i2 are identically equal");
    }
    if(i1.equals(i2))
    {
      System.out.println("i1 and i2 are meaningfully equal");
     }
     Integer i3=250;
     Integer i4=250;
     if(i3==i4)
     {
       System.out.println("i3 and i4are identically equal");
       }
      if(i3.equals(i4))
      {
         System.out.println("i3 and i4 are meaning fully equal");
      }
  }
}
out put: 
  i1 and i2 are identically equal
  i1 and i2 are meaning fully equal
 i1 and i2 are meaning fully equal
   

Read More

Thursday, 17 October 2013

Important Questions in Hibernate



Important Questions in Hibernate

In real time Hibernate is  called as DAO(Data Access Object).Because Hibernate Only Provide the Persistence Logic.DAO Pattern suggested that to separate the Business logic and Persistent logic.So in this process loose coupling between the business logic and persistent logic.And also reusable the persistent logic.

1.In Hibernate what happens when the same object is loaded for two times with  in a session?
ans:

  • A session of hibernate maintain a cache for storing the objects used in a session.With the help of the cache to reduce the no of round trips between the java application and database.
  • For the first time hibernate load the object from the database and it will be stored in a session cached .
  • Second time the object is loaded from the session cache but not from the database.

 We can understand  how many times the object is loaded from the database,using select command printed on the console.

2.what is the difference  between the save( ) method and persist( )method in hibernate?
ans:

  • save( ) method  return type is serializable  and persist( ) method return type is void.
  •  save ( ) method will save the object in session cache and returns the id of the object in  serialized format. 
  • persist( ) method will save the object in session cache and doesn't return any id of session object.
  • If the generator class is assigned the the programmer need to assign the id explicitly.In this case persist( ) method is used.
  • If the generator class is other than assign then hibernate will assign id of the object.In this case save( ) method is used.

3.What is the difference between save( ) and saveOrUpdate() methods?
ans:

  • save( ) method will perform only save operation.but saveOrUpdate( ) will perform save and update operations.
  • saveOrUpdate( ) method performs save operation if the id is new.If the id is persist then it perform update  operation.

4.In properties of pojo class,primitives or wrapper  is better type?
ans:

  • wrapper type is better than primitives .Because if we don't assign  a primitive  property value then it will save the property value is zero.It will miss understanding of the data.
  • To over come this problem we use wrapper type property  in this we don;t assign a primitive value then it will save the property value null is stored in database.So there will be no misunderstanding of the data.
5.why hibernate is recommended  to implement a pojo class java.io.Serializable interface?
ans:
  • If a database server is running on local machine then the object of pojo class may or may not be implement a serializable  interface
  • If a database server  is running on a remote machine in a network then only serializable objects are transfer in to the network.So we can must implement our pojo class object with serializable interface.
6.Can you create a hibernate application without creating a configuration file or not?
ans: Yes.we can create a hibernate application without configuration file.By using we can create a properties file or we can add a configuration pro-grammatically.

  • Before hibernate 3.x,Configuration file can be done either using properties file or pro grammatically .In hibernate 3.x we can use configuration xml file.
  • In properties file we can configured only connection properties and  hibernate properties.mapping resources can not be configured.
  • we can add the mapping resource to configuration explicitly by calling add Resource()method.
example:
hibernate.properties
     connection.driver_class=oracle.jdbc.OracleDriver
     connection url =jdbc:oracle:thin:@localhost:1521:XE
     connection username=system
     connection password=tiger
    dialect=org.hibernate.dialect.OracleDialect
    show_sql property tag
    
      In this above properties file we can configure only hibernate properties and connection properties.
      Next we can call the mapping resource through calling addResource() method in client application.
example:
         Configuration conf=new Configuration();
           conf.addResource("product.hbm.xml");
7 What is difference between the pool and cache?
ans: In hibernate mainly two difference are there in pool and cache.
  • pool  is a group of equal objects.we call them as stateless objects.But a cache is a group of unequal objects.we call them as state full objects.
  • In a pool a client has to wait until one of the object is free,when a pool is busy.where as in cache a client has to wait until any one of the object is free when cache is busy..
Read More

Tuesday, 15 October 2013

Interview Point of view Mostly Asked Questions in Hibernate:



 Interview Point of view Mostly Asked Questions in Hibernate:

In Interview point view most important questions are given bellow.These are all questions in Hibernate. In real time hibernate place a very important role in applications.By using Hibernate we can connect the application with database better than the jdbc and more features are  available in hibernate.
1.what is the nee d of the Dialect in Configuration file of the Hibernate?
ans: To generate the database related sql queries internally Dialect is used.

2.what is the benefit of Configuration file name as hibernate.cfg.xml?
 ans:--> if the file name is hibernate.cfg.xml then it is optional to pass the file name as parameter to            Configure().
      -->if the file name is some other say krishna.cfg.xml the we need to pass the  configuration file name to Configure() as mandatory.
for example:
       i) if the file name is hibernate.cfg.xml
            conf.configure( );                     ----->correct
            conf.configure("hibernate.cfg.xml");---->correct
       ii)if the file name is krishna.cfg.xml then
           conf.configure( );                      ----->wrong
           conf.configure("krishna.cfg.xml");----->correct

3.what is the difference between load( ) method and get( ) method?
 ans: load( ) method
      --> if the given id is doesn't exits in the database then load( ) method throws Object     NotFoundException.
     --->load( ) method reads an object from the database when is accessed in the code ,but not immediately load( ) method called.This is called "lazy loading"
    get( )method
     ---> if the given id is doesn't exists in the hibernate then get( )method simply returns null.
    --->get( ) method reads an object from the database when accessed in the code,immediately get( ) method called .This is called "early loading".

4.In hibernate application how many states are contain a pojo class object?
ans: In hibernate application a pojo class can contain 3 states.They are
       1.Transient State
       2.Persist State
       3.Detached State
Transient State:
    --->if the object is not entered into the session then the object is in Transient State.So it is not associated with database.
    ---->if any changes are done on a Transient state object it is not effected on the database.
Persistent State:
      ---> if the object is entered into the session then the object is in Persistent State.So it is associated with database.
     ---->if any changes are done on a Persist state object is effected on the database.
Detached State:
    ---->if the object is come out of the session then the object is in Detached State.So it is not associated with database.
  ---->if any changes are done on the database object is not effected on the database.

5.what is the difference between update() method and merge( )method?
ans:-->update( )method and merge( )method both are used to convert the object from detached state to persist state
   update( ) method:
     -->we can call the update( ) method to convert a detached state object into persist state.while converting if already an object exits in a cash with the same id then update( ) method throws org.hibernate.NonUniqueObjectException it means update( ) method fails.
  merge( )method:
    ---->we can call the merge( )method to convert a detached state object to persist state.while converting  if already an object with same id exists in the cash then merge( ) just copies the changes from detached state to object which is already exists in the cash.But it does not throw any Exception.
 
Read More