Request Processor is a simple object of org.apache.struts.action.RequestProcessor class which handles the HTTP specific request and response after getting the control from the ActionServlet by calling process().

Steps of Struts Request Processing flow :

1. Clicking on submit button from JSP page, container invokes the doPost() or doGet() method based on the type of action performed. 

2. Control go to the ActionServlet which delegates the request to the Request Processor by invoking process() method.

3.  Request Processor will check for the requested resource. 

4. If request resource in not available then give the error with HTTP Status code : 404 saying  "Requested Resource is not available ".

5. If available then Request Processor checks whether that resource contain any < html : form > tag or not. 

6. If that resource doesn't contain any < html : from > tag then corresponding resource i.e JSP will be displayed .

7. If it contains < html : form > tag with form elements then Request Processor takes the reqested URI mentioned in the action attribute of the < from > tag in JSP.

8. Request Processor checks whether any < action > tag is present in the struts-config file. If present then check for the URI is available in the path attribute of the < action > tag in the struts-config file.  

9. If no matching action is found then error message will be displayed with Http Status code: 500 saying cannot retrieve mapping for the following action . 

10. And if matching action found then Request Processor gets the value of the name attribute of the < action > tag .

11. Request Processor check for the name attribute of the < form-beam > tag contains the same value as the name attribute of the < action > tag.

12. If no matching action is found then error message will be displayed with HTTP Status code: 500 saying " cannot retrieve defination for the following form bean ".

13. If the matching form bean found then Request Processor get the form bean  type and do the following tasks:

       a) Loads the respective class.
       b) Create the object of the form bean class by calling the default constructor.
       c) Store the  object in the default scope i.e session using the setAttribute() .
       d) calls the reset() method.
       e) Collect the data from the form bean object and populate in the JSP field.   

14. Invokes the execute() method with the HTTP specific request and response. 

15. If it fails to execute successfully then Exception may be throw and must be handled by the Request Processor. 

16. If executed successfully then control will get back to the Request Processor by returning ActionForward object which is preformed by calling the findForward() method with the ActionMapping instance.

17. Request Processor identifies the JSP related to the ActionForward object returned by calling the findForward() or exception throws by the execute() method. 

18. And hence identified resource ( JSP ) will be displayed to the client. 


Note : Either returned ActionForward object or Exception any one can be handles by the Request Processor for the same action performed at a time. 




Action class must be configured in the struts-config.xml file so that container must have the information for which action it has to forward to which Action class. That's is why we are configuring the Action classes. For each action from the JSP page we are writing each Action class, previously in servlet we were writing Servlet class for each action performed but in Struts we are writing simple Action class but capable of handling HttpServletRequest and HttpServletResponse because of overriding execute() method.

We are writing each action in < action > tag under the < action-mapping > tag .

struts-config.xml 

<form-beans>

   <form-bean name="loginForm" type="com.def.Struts.LoginForm">
   </form-bean>

<form-beans>

<action-mappings>
  
      <action path="/loginSubmit"
  name="loginForm"
  type="com.def.Struts.LoginAction"
  input="/login.jsp"> 
    
         <forward name="success" path="/home.jsp"></forward> 
         <forward name="failed" path="/login.jsp"></forward>

     </action>
<action-mappings>

Each Action is configured with each < action > tag but under < action-mapping > tag . So we can have multiple action tag in a single < action-mapping > tag , depending upon the action configured.

< action > tag

There are total 12 attributes of < action > tag but we are discussing of only 4 attributes. They are :
1. path
2. name
3. type
4. input

path : It represents the relative-path of the submitted request and it must be unique , must starts with  / . It also must be same as we write in the action attribute under the < from > tag .

name : It is the logical name which is used t identifies the name of the form bean which is coupled with the action performed.

type : It contains the fully qualified name of the Action class which is used to perform the respective action of the relative-path mentioned in the path attribute.

input : It represents the relative-path of the input form to which control must be returned if validation error is encountered.

< form-bean > tag

Form-bean tag has two attribute i.e name and type .

name : Name attribute contains the same name as we write in the name attribute of the action tag so that form bean must be coupled with the action performed.

type : In the type attribute , there must be full qualified name of the form bean.



As ActionServlet is simple Servlet class only but designed using the Front Controller Design Patern so it must be configured in the web.xml file at the container itself only, so that every request must be followed by ActionServlet.

Web.xml file

<servlet>

  <servlet-name>login</servlet-name>

  <servlet-class>
     org.apache.struts.action.ActionServlet
  </servlet-class>
   
  <init-param>

   <param-name>config</param-name>
   <param-value>WEB-INF/struts-config.xml</param-value>

  </init-param>

  <load-on-startup>1</load-on-startup>

</servlet>
  
  <servlet-mapping>

   <servlet-name>login</servlet-name>
   <url-pattern>*.do</url-pattern>
  
  </servlet-mapping>

Here we have configured the ActionServlet class of org.apache.struts.action package under the servlet tag.

Why we are configuring ActionServlet at the container start-up ?

It is because first request handled by this servlet only then control will go to the RequestProcessor and then to our own Action class, so that we need not to design as many Servlet class for as many Actions. In Front Controller Design Pattern all the request get handled by only one servlet and once ActionServlet get initialized it is able to handle all the incoming request from the client machine. 

This is the also reason why we are mentioned load-on-startup value as 1 because it get initialized at the container start-up only. 

Why we hard-coded the "config" in the init-param tag ?

It is because config is also hard-coded in the init() method of the ActionServlet so that it can be able to get the name of the struts-config.xml file and able to parse and load to the main memory.   

Is struts-config.xml is fixed file name ?

No it in not a fixed name, we can have any name but need to configure in the param-value tag in the web.xml file. 

Why we have written *.do in the url-pattern ?

*.do indicate that for all the incoming request there is only servlet class i.e ActionServlet class. But we can have any suffix instead of .do .


We can write our own Action class using Struts framework but need to extends Action class of org.apache.struts.action package and need to override execute() method which return the ActionForward class object and which must be return by calling the findForward() method with ActionMapping reference and hence control will transfer to the caller i.e RequestProcessor.

Description about execute()

public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, 
 HttpServletResponse response)throws Exception { 

    return mapping.findForward(result);

}

Caller of the execute() is RequestProcessor and return will also go the RequestProcessor. So by this we can confirm that after calling process() method by the RequestProcessor , now its the responsibility of the RespectProcessor to handle all the request of the client by calling execute() method.

execute() method is parametrized with ActionMapping , ActionForm , HttpServletRequest, HttpServletResponse reference.

Why ActionMapping ?

It is because findForward() method is implemented in the  ActionMapping class only and return ActionForward object.

Why ActionForm ?

It is because because before control comes to Action class it check the form bean class and hence its object has all the required value of the HTML form elements ( text field, checkboxes, drop down etc ).

Why HttpServletRequest ?

It is because to handle and process the request by the clients.

Why HttpServletResponse ?

It is because to send the response to the client after processing the request.

Note: Each Action class must be mapped in the struts-config file within action-mapping tag and hence need to also configure its from bean class.




All the Request by the client are get processed by the ActionServlet only then get forwarded to the Request Processor.
ActionServlet is a single Servlet designed by the Apache using Front Controller Design Pattern. It follows the life cycle of the Servlet  by calling init() method then doPost() or doGet() and finally destroy().

Internal Implementation of the ActionServlet
  
public class ActionServlet extends HttpServlet {

   RequestProcessor rp = null;

   public void init(ServletConfig sc){

init() method is parameterized with ServletConfig object which is used to collect the data mentioned in the xml file under the init-param tag.

   String file_name= sc.getInitParameter("config");

Hence we hard-code the value " config " in the xml file because it is hard-coded in the ActionServlet class as well. And by this it will get the name of the struts-config xml file.

Start parsing or reading the data from the struts-config xml file by using the SAX Parser and store the information in the main memory.

    rp= new RequestProcessor(); 

}

After initializing the ServletConfig object RequestProcessor get initialized and store the data parsed from the struts-config file into the RequestProcessor object.

public void doPost(HttpServletRequest,HttpServletResponse) {

   rp.process(request,response);

}

or

public void doGet(HttpServletRequest,HttpServletResponse) {

   rp.process(request,response);

}

Then doPost() or doGet() method will be called by passing the request and response object and in this method a process() method will be called by the RequestProcessor object by passing HttpServletRequest and HttpServletResponse so that the request will be processed by the RequestProcessor object only.


public void destroy(){

   }
}

Finally destroy method will be called.

Note: Once the ActionServlet class is initialized then it will be eligible to handle any request with the url-pattern mentioned as *.do or any thing . 

This is the reason why we are writhing like *.do means any request will be handled by the ActionServlet only. This is also called as Front Controller Design Pattern that means a single Servlet is responsible to handle all the incoming request. 





Following task are performed at the Container start-up in Struts based Application.
They are :

1. Container make sure about the web configuration file i.e web.xml whether is available or not.

2. If not available then Container will not be initialized and hence fails to start.

3. If available then Container will parse/read the web.xml file and store the required information in the main memory.

4. Then Container will create the ServletContext Object and initialized with the ServletContext parameter specified in the web.xml.

5.Thread Pool will be created which is responsible for threading the request by the clients. Each request is handled by each thread and after finishing back to the pool.

6. Configured ActionServlet will be initialized at the container start-up only with load-on-startup value as 1.

7. Then all the filters as initialized.

8. Finally all the Listeners will be initialized.



Note : org.apache.struts.action.ActionServlet are initialized at the container start-up only. It is implemented internally using the Front Controller Design Pattern. That means every request must followed through ActionServlet then to the respective designed Action class by the developers.







Steps to follow for developing Struts Application using Eclipse :-

We must have to follow some of the basic steps to develop any struts application using the Eclipse IDE.

1. Create Dynamic Web Project.

2. Copy all the 10 jars provided by the struts vendor to the WEB-INF/lib folder + 1 servlet-api.jar.

3. Copy all the 6 tld files to the WEB-INF folder ( not necessary )
    (Only when if developer want to use some pre-defined tags given by struts vendor in JSP page )

4. Copy struts-config.xml file to WEB-INF Folder. (struts-config is the default name,
                                                                                if we want we can change also ) .

5. Configure web.xml with "ActionServlet" class and init-param-value with " config "  and
     init-param-name with  " /WEB-INF/struts-config.xml " .

6. We need to create a form beam and a action class within a package named as " com.def.Struts ".

7. Now create a package  " com.def.Struts " under which place two java files.
     a) LoginForm.java ( Form bean class)       b) LoginAction.java (Action class )

8. Place one Properties file under " com.def.Struts " package which contain message regarding validation of        the form. ( message.properties  file ) --> Optional ( Only needed if validation is there ).

9. Mapping the struts-config file with action and form bean classes. How ?
    ( We will see in details later )

10. Now deploy the project and run successfully.

Files required for this simple Struts Project.

1. A Login jsp page ( login.jsp )
2. Login Success page ( home.jsp)
3. web.xml
4. struts-config.xml
5. LoginForm.java
6. LoginAction.java

login.jsp

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html> 
<body>

<html:form action="/loginSubmit">

UserName: <html:text property="name"></html:text><br/>
Password: <html:password property="password"></html:password><br/><br/>
<html:submit>Login</html:submit>

</html:form>

</body>
</html>

home.jsp


<html>
<body>

    Logged in successfully and Welcome to your home page..!

</body>
</html>

web.xml

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

  <display-name>Struts1</display-name>
 
<servlet>
  
  <servlet-name>login</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>

</servlet>
  
<servlet-mapping>

 <servlet-name>login</servlet-name>
   <url-pattern>*.do</url-pattern>

</servlet-mapping>
  
</web-app>


struts-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//
DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/
struts/dtds/struts-config_1_1.dtd">

<struts-config>
    <form-beans>
 <form-bean name="loginForm" type="com.def.Struts.LoginForm"/>              </form-beans>
 
<action-mappings>
 <action path="/loginSubmit" 
  name="loginForm" 
  type="com.def.Struts.LoginAction" 
  input="/login.jsp">
    
 <forward name="success" path="/home.jsp"></forward>
 <forward name="failed" path="/login.jsp"></forward>
 </action>
 
</action-mappings>
    
</struts-config>

LoginForm.java

package com.def.Struts;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class LoginForm extends ActionForm{
 
 private String name;
 private String password;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
 
     public void reset(ActionMapping mp, HttpServletRequest req){
  
  this.name="java";
  this.password=null;
  
 }
}

LoginAction.java

package com.def.Struts;

import org.apache.struts.action.*;

import javax.servlet.http.*;

public class LoginAction extends Action{

 
public ActionForward execute(ActionMapping mp, ActionForm af,
  HttpServletRequest req, HttpServletResponse res)
   throws Exception {
  
 LoginForm lf=(LoginForm)af;
 String name=lf.getName();
 String pass=lf.getPassword();
 String result="";
 if(name.equals("sushant") && pass.equals("sushant")){
  result="success";
 }else{
  result="failed";
 }
    return mp.findForward(result);
  
 }
}





Most importantly Struts 1 is a web framework which is internally implemented using Servlet and JSP technologies.

This web framework is designed by Apache Software Foundation in 2001 keeping in view to reduce the task of the developer and maintenance issue which was much in Servlet.

Struts framework is implemented based
     -> MVC Architecture
     -> Front Controller Design Pattern
     -> Servlet & JSP.

Struts cover up the Controller and Presentation layer. In Controller layer internally Servlet is implemented using the Front Controller design pattern and for Presentation layer internally JSP is implemented with some tld files, by which developer can use some pre-implemented tags instead of writing java code in jsp page and hence reduce the java codes in jsp pages at the result enhance the maintenance issues. 

Struts Version

There are two versions released by Apache i.e
1. Struts 1.x  ( x = 0, 1, 2, 3)
2. Struts 2.0

Required jars of Struts 1 

There are 10 jars implemented by the Apache . They are :-

1.  commons-beanutils
2.  commons-collections
3.  commons-digester
4.  commons-fileupload
5.  commons-lang
6.  commons-logging
7.  commons-validator
8.  jakarta-oro
9.  struts
10. struts-legacy

And one more java we need to of servlet-api jar implemented by the web server vendors i.e
servlet-api .

Required Xml Files 

1. web.xml
2. struts-config.xml

Note: In struts-config.xml we are configuring form beans and action classes using form-beans and action-mapping tags respectively. 

In we.xml we are configuring the ActionServlet class which is implemented using the Front-controller design at the start-up of server and configuring struts-config.xml as the inti-param with the fixed inti-param name i.e config. 

* ActionServlet class is implemented by the Apache which is available in the org.apache.struts.action package.
Hibernate Transaction is associated with each operation we are performing within a session. We have to use org.hibernate.Transaction class to perform transaction in hibernate.

How Transaction object get initialized ?

As we know translation is associated with the session , so we can initialize Transaction using the beginTransaction() method which is a abstract method in Session interface and returns the Transaction object. 
After getting session object we need to call beginTransation()--->

Transaction tx = session.beginTransaction();

And after performing the operation using the session object in the database it needs to committed but in hibernate auto-commit is disable so we need to explicity commit the transation by using the following syntax,

tx.commit();

 Note: Transaction commit should be done before closing the session, otherwise it fails to commit. So commit must be done after performing any operation and before closing the session.

Important points regarding Transaction Object

1. It is not thread -safe that means any thread can access this object. So its better to close session after finishing the operation.

2. We can have single commit for multiple operation within a single session. So no need to create multiple Transaction object for each operation within a session. 

3. Must commit the database operation otherwise the operation doesn't reflect the changes in the database table and hence hibernate unable to perform the operation. 
In case of JDBC we the developer are responsible for establishing and terminating the database connection but in case of Hibernate, it is only responsible for establishing and terminating database Connectivity , we only need to indicate by simply calling some pre-defined method by the hibernate session. For ex-

After getting the SessionFactory which holds all the information about the database by reading the hibernate Configuration file, need to call the openSession() of SessionFactory interface which an abstract method and returns the Session instance.

Initializing Session instance creating the database Connection and opening the session which involves the database activity like insert,delete, update etc.

In hibernate
1 . Insert can be performed by calling save() method.
2.  Select can be performed by calling load() method. etc

How to create session In hibernate

1. Creating the SessionFactory instance.

SessionFactory factory=null;

Configuration cfg=new Configuration();

cfg=cfg.Configure();

factory=cfg.buildSessionfactory();

2. After creating Sessionfactory call openSession() method which returns the Session instance. Like this

Session session = factory.openSession();

By calling openSession() a session will be created and a session is responsible for performing a database operation. For multiple database operation we must have that much Session instance.

Note: Session is not a thread -safe that means as long as it is open it is in risk of accessible by other thread also so it must be closed after operation is over.

How to close session?
It can be simply closed by calling close() with Session instance. Like this

session.close(); 

States of Session Instance.

There are three states of instance of Session which behaves according to the persistence object creation. 

1. Transient: It is the initial state which represents that persistent class instance is not associated with any of the Session. That means it doesn't involve with any activity/operation with the database.

2. Persistent: It is the state of Session which represents that persistent class instance is associated with the Session and it has representation in the database and hence will be involved with the database activity/operation.

3. Detached: It is the final state of Session which represents that the Session is closed and hence persistent class instance get detached. 

Note: After Session creation Transaction creation is mandatory because we need to commit every operation/activity we are performing within the session. Otherwise changes will not reflect in the database. And by default auto-commit is disable or de-active so we need to commit explicitly for that we need to create transaction for each database operation. 

For details about Hibernate Transaction click here Hibernate Transaction .




org.hibernate.SessionFactory is an interface implemented by the hibernate vendors whose instance is created by calling the buildSessionFactory() which is implemented in the org.hibernate.cfg.Configuration class and must be called with the Configuration class object.

buildSessionFactory() method is org.hibernate.cfg.Configuration class return the SessionFactory interface instance. Internally it returns the SessionFactoryImpl class instance which implements SessionFactory interface, like this

public SessionFactory buildSessionFactory() throws HibernateException{    return new SessionFactoryImpl(this,this.mapping,settings,listeners); }

How to get SessionFactory Instance

1. Create Configuration class object. like this

Configuration cfg=new Configuration();

2. With the Configuration class instance class the Configure() method by specifying the hibernate Config xml means which configuration file is to be read by SessionFactory object and return the Configure class instance.

cfg=cfg.Configure(); 
 or
cfg=cfg.Configure(String resource); //Name of the xml file in 
                                      string format. 

In the above syntax Configure() method without argument by default takes "hibernate.cfg.xml" name as the hibernate Configuration xml file. Or we have any different name then we need to use Configure(String resource) method and mention the file name in the String format.

3. Now after getting the Configuration class instance with the Configure() method , we need to call buildSessionFactory() which finally returns the SessionFactory instance and need to store in the SessionFacroy reference type.

SesionFactory factory=cfg.build.SessionFactory();

Note: buildSessionFactory() method is responsible to parse/read the hibernate configuration xml file and store all the required information in the SessionFactory object.

Now SessionFactory Instance will have information about the driver_class and all other required information about the database. With this we can conclude that one SessionFactory is responsible for single database.
If we want to have multiple database connectivity then we have to declare as much SessionFactory object. 


Why we need to create SessionFactory instance?

It is because SessionFactory Instance is having all the required information about the database for database Connectivity and are responsible for database connectivity and session creation. To know more about Hibernate Session click here  Hibernate Session. 
Basically there are three way to convert an primitive value to string so that if we have requirement to use that primitive as a string then we can you this concept and way of conversion but now the point is out of these three way which one is the best and take less time and doesn't have any performance issue.

The three ways of converting primitive into string are :

1. Using Empty string
2. Using valueOf() with String class
3. Using toString() with Wrapper class.

Using Empty String

With the use of an empty string we are creating an new string in the constant string pool and if that string literal is already present in the pool then it will create the object in the heap which points to the pool literal object and return the heap memory address to its original object. For ex-

public class prog {

    public static void main(String[] args) {

 String s=""+10;
 String x1="java10";
 String x2="java"+10;
 System.out.println(x1.equals(x2)); // true
 System.out.println(x1==x2);    // false
 System.out.println(x1.hashCode()==x2.hashCode());//true

    }

}

In the above example ( x2== x1 ) will give false that means s2 and s1 both are different object and which proves that x1 literal get stored in string pool first and then while storing s2 literal it will first check the pool, if present then it will create an new object in the heap memory if we are using new operator that means internally  String is created with the use of ' new ' operator. 

Using valueOf() with String class

Another option for making a primitive value to string value is the use of valueOf( int i ) defined static in the String class, which return string value and take integer value from its integer type parameter. Here i have used only int type but valueOf() can be used with any primitive type. For ex- 

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=String.valueOf(x);
 System.out.println(s1); 
 
     }

}

using valueOf() which it self used Integer.toString( int, int ) internally to convert it into string type value.

Using toString() with Wrapper class

Every wrapper class is having overridden toString() method with parameter as any primitive type. So we have one more option to make a primitive data as string type by using toString( int i ) . Here also i have used int type but toString() is available with any primitive type as argument. For ex-

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=Integer.toString(x);
 System.out.println(s1); 
 
     }

}

toString() method internally uses character array concept to create an String. So this is the most efficient way of converting into string value.

So it is recommended to use any of the either valueOf() or toString().

Note: It is not recommended to convert with the use of empty string . 
String is a reference data type and hence string literals are treated as object and get stored in the string constant pool. We must have to define any string within double-quote otherwise it will give compilation error. String can be represented in two form either with using ' new ' operator or without using new operator.

Two way of string representation in java :
1. Without using new operator
2. With using  new operator.

Without using new operator

String can be represented without using new operator that means we are directly assigning string value to its reference. If we are defining like this then first it will search for the string literal whether it is present in the String pool or not. If it is present then simply it returns the reference of the existing object to the current reference. For ex-

public class A {

 public static void main(String[] args) {

    String s = "java";
           String s1= "java";
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 }
}


In the above program with the first statement i.s String s="java", it will search in the string pool whether that string literal is present or not. If it is present in the pool then it will return the reference to the reference variable 's' which also starts pointing to that object.



With the second statement again it will start searching in the string pool , if present then return the reference variable and if not then create the object in the pool and then return the reference. 

Important points regarding Creating string without new operator

1. First search in the string pool whether string literal is present or not.
2. If present in the pool then return the reference.
3. If not present in the pool then crate and object and return the reference of that object.

With using new operator 

With the help of new operator it is definitely going to create an object. First it will search in the string pool that whether that string literal is present or not , if not present then it will create an object in the pool itself and if present then it will create an object in the heap memory and that memory will hold the reference of the already present literal in the pool. So with the above statement its confirm that with the use of new operator it is going to create an object but in heap or in pool it all depends upon the string literal's presence in the pool.
For ex- 

public class A {

 public static void main(String[] args) {

    String s = new String("java");
           String s1= new String("java");
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

In the above for the first statement it will search in the pool whether string literal " java " is present in the pool or not , if not then create the object in the pool itself and if present in the heap memory and return the reference of the already stored object to the reference variable " s ". 

For the second its the string literal " java " is surely present in the pool so JVM will create object in the object in the heap memory and return the reference to that object and that object reference value is returned to the " s1 " reference variable.

Example with and without new operator 

public class A {

 public static void main(String[] args) {

           String s="java";  //without new operator 
           String s1="java";
    String s2 = new String("java"); // with new operator
           String s3= new String("java"); // with new operator
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

From the above example:

String s = "java" ---> Create object in the String pool ( if not present )
String s="java"---> Return the reference of the object present in the pool .
String s1= new String("java") --> Create the String object in the heap.
String s2=new String("java")--> Create the String object in the heap.

Diagram showing how memory is assigned in the heap and string pool.



In the above diagram we can see that s2 and s3 contain the reference of the object created in the heap memory and which itself contains the reference of the string pool object.


But in case of without using new operator, always reference value is returned and it is not going to create any object in the heap memory. This is the major difference between the string object with and without using new operator. 
It is the manually implemented coding for doing cloning. This concept has came to overcome the limitation found with shallow cloning which fails to clone the data member. Through deep cloning we can be able to cover up the problem with the shallow cloning. Now with the help of deep cloning we can able to clone the object members as well but to achieve this we don't have any predefined method, so we need to write our own code. Deep Cloning is just a term to indicate that we are also cloning the object members.

To achieve deep cloning we need to override the clone method and need to create an object of the object member so that we have other object  and need to copy return that object to the clone object.

See the example below then you will be more clear about the above statement written.

Example showing Deep Cloning

class E{
    int y=40;
    String s1="tutorial";
    public E(int y2, String s12) {
 this.y=y2;
 this.s1=s12;
   }
   public E(){}
 }

public class deepCloning implements Cloneable{

    int x= 20;
    String s="java";
    E e;
  
   deepCloning(int x2, String s2, E e1){ //To initialize the property 
 this.x=x2;
 this.s=s2;
 this.e=e1; 
   }
   public deepCloning() {
 e=new E();
   }
   protected Object clone(){   //overridden clone() method 
 deepCloning d2=null;
 E e1= new E(this.e.y,this.e.s1);
 d2=new deepCloning(this.x,this.s,e1);
 return d2;
   }

public static void main(String[] args) {

        deepCloning d = new deepCloning();
 deepCloning d1=null;
 try{
  d1=(deepCloning)d.clone();// Cloning statement 
 }catch(Exception e){
  e.printStackTrace();
 }
 System.out.println(d);
 System.out.println(d1);
 d1.e.y=30;
 System.out.println(d1.e.y);
 System.out.println(d.e.y);

 }  
}

In the above code we can see that clone method is overridden to our class in which we try to create and separate object for the class E and also create and object of the current object to return the class E object so that the clone object will have that reference value for its Object member. 

And all the constructor used in the respective class to initialize the property otherwise there may have chance to throw NullPointerExcpetion. 

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic