Thursday, November 21, 2013

Web Services in JAVA

REST :- Stands for Representation State Transfer and is an architectural style of client-server application centered around the transfer of representations of resources through requests and responses.

The Web is comprised of resources. A resource is any item of interest. For example, the Boeing Aircraft Corp may define a 747 resource. Clients may access that resource with this URL:
http://www.boeing.com/aircraft/747
A representation of the resource is returned (e.g., Boeing747.html). The representation places the client application in a state. The result of the client traversing a hyperlink in Boeing747.html is another resource is accessed. The new representation places the client application into yet another state. Thus, the client application changes (transfers) state with each resource representation --> Representational State Transfer! Here is Roy Fielding's explanation of the meaning of Representational State Transfer: "Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."
In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs)

Note: URI (Uniform Resource Identifier) consists of either URL (Uniform Resource Locator )or URN(Uniform Resource Name) or both

REST is an Architectural Style, not a Standard
While REST is not a standard, it does use standards:
  • HTTP
  • URL
  • XML/HTML/GIF/JPEG/etc (Resource Representations)
  • text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)
The web service makes available a URL to a list of  resource. For example, a client would use this URL to get the parts list:
http://www.parts-depot.com/parts
Note that "how" the web service generates the list is completely transparent to the client. All the client knows is that if he/she submits the above URL then a document containing the list of resources is returned. Since the implementation is transparent to clients, Parts Depot is free to modify the underlying implementation of this resource without impacting clients. This is loose coupling.

Principles of REST Web Service Design
1. The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services. Above we saw some examples of resources: parts list, detailed part data, purchase order. 2. Create a URL to each resource. The resources should be nouns, not verbs. For example, do not use this:
http://www.parts-depot.com/parts/getPart?id=00345
Note the verb, getPart. Instead, use a noun:
http://www.parts-depot.com/parts/00345
3. Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.  
4. All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.  
5. No man/woman is an island. Likewise, no representation should be an island. In other words, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.  
6. Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema (DTD, W3C Schema, RelaxNG, or Schematron). For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WSDL document, or simply an HTML document.
Reference:-
http://www.xfront.com/REST-Web-Services.html
http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/

 







Web.xml

References:-
http://download.oracle.com/docs/cd/E13222_01/wls/docs81/webapp/web_xml.html
This file is used to define each servlet and JSP page inside a web-application.
It is found in WEB-INF directory under the document root of the web application.
It is also called Deployment Descriptor

Context parameters are accessible to any servlet or JSP in the web-app and can be accessed through ServletContext object.
String value = getServletContext().getInitParameter("name_of_context_initialization_parameter");

For springs Context param name for
    application context is  "contextConfigLocation" with value "*.xml"
    log4j is "log4jConfigLocation" with value "*.properties"
    applicationContext.xml is an XML file having the context parameters

Init parameters are specific to a particular servlet and and can be accessed through ServletConfig object.
String value = getServletConfig().getInitParameter("name_of_context_initialization_parameter");

load-on-startup gives the order in which the servlet will initialize

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <display-name>The name of the application </display-name>
    <description>Description of Application</description>
    <welcome-file-list>
           <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
     <description>Description of parameter</description>
     <param-name>name_of_context_initialization_parameter</param-name>
     <param-value>value_of_context_initializtion_parameter</param-value>
    </context-param>

 //In case of Servlets , we define our own Servlet classes and corresponding mappings are given  in web.xml

    <servlet>
     <servlet-name>guess_what_name_of_servlet</servlet-name>
     <description>Again, some description</description>
     <servlet-class>com.foo-bar.somepackage.TheServlet</servlet-class>
     <init-param>
       <param-name>foo</param-name>
       <param-value>bar</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
     <servlet-name>name_of_a_servlet</servlet-name>
     <url-pattern>*.some_pattern</url-pattern>
    </servlet-mapping>


 //In case of struts 2 , we define the filters and corresponding mapping of FilterDispatcher in web.xml
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>

//In case of springs, we define the servlet and  corresponding mapping of Dispatcher Serv
    <servlet>
        <servlet-name>employee</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/employee-servlet.xml</param-value>
    </context-param>
    <session-config>
     <session-timeout>30</session-timeout>
    </session-config>
</web-app>

Wednesday, November 20, 2013

SQL

Primary Key:-
  • A column or a group of columns in a table which uniquely identifies a row. 
  • It can not accept null value
  • It is created as
    CONSTRAINT pk_name PRIMARY KEY (column1, column2, ...)
  • A table can have only one primary key column(s)
  • It created a clustered index by default
  • It can be referred as a foreign key in some other table

Unique Key:-
  •  A column or a group of columns in a table which uniquely identifies a row.
  •  It can  accept null value
  • It is created as
    CONSTRAINT uk_name UNIQUE (column1, column2, ...)
  • A table can have more than one unique key column(s)
  • It creates a non clustered index by default
  • It can not be referred as a foreign key in other table 


Tuesday, November 19, 2013

Multi-threading

Process :-  A program in execution is called a process e.g running Microsoft word. It is heavyweight component. Two processes can never share same address space. A process has at least one thread which is main, excluding the system threads that help in memory management and signal handling.

Note : IPC (Inter process communication) resources like sockets and pipes are used to communicate between two different processes.

Thread :- A thread is a part of execution with in a process.e.g spell checker in above process. It is  a lightweight component. Two threads of a process can share the same address space.

Note: Programming constructs like wait, notify and notify all used for communication between threads

Life Cycle of thread :-
  1. New (Born). A thread is in new state when its instance is created.
  2. Runnable (Starts) A thread is in runnable state if its starts method is invoked.
  3. Running (Runs): A thread is in running state if thread scheduler has selected it.
  4. Non Runnable:- A thread is in non running state if it alive but is not eligible to run.
  5. Terminated Dies:- A thread is in dead state if its run method exits.
Note :-
  1. There are several ways to enter in Runnable state e.g. on invoking of start() method, after either running, waiting, sleeping or coming back from blocked state etc, but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 
  2. A running thread can enter to any non-runnable state directly but a non-runnable thread can not enter to running state directly. It has to first enter runnable state.
Non Runnable States:-
  1. Sleeping 
  2. Waiting
  3. Blocked on IO
  4. Blocked on Joint Completion
  5. Blocked on lock acquisition
Thread Priorities:-
Each JAVA thread is given a priority that helps the operating system to determine what thread is needed to be executed and at what priority
  1. MIN_PRIORITY (1)
  2. MAX_PRIORITY (10)
  3. NORM_PRIORITY (5)
Thread Creation:-
  • Extending Thread Class
  • Implementing Runnable Interface(provides multiple inheritance)
Synchronization:- It is the capability of controlling access to shared resources by multiple threads.  
Difference between Thread.start() and Thread.run():-
  1. Thread.start() creates a new thread while Thread.run() runs on the same thread.
  2. start() can not be called twice on the object  as it will throw illegal state exception.
Context Switching
Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time

Thread.join()
This method is used to pause the current thread execution until unless the specified thread is dead. There are three overloaded join functions.
  1. Thread.join():- This method puts the current thread on wait until the thread on which it’s called is dead. If the thread is interrupted, it throws InterruptedException.
  2. Thread.join(long millis):- This method is used to wait for the thread on which it’s called to be dead or wait for specified milliseconds.
  3. Thread.join(long millis, int nanos):- This method is used to wait for thread to die for given milliseconds plus nanoseconds. 
package com.arsoft.tutorials.multithreading;
import java.util.Vector;
public class ThreadTestWithJoin {
    private Vector<String> threadsName = new Vector<String>();
     private void startThreads(int nfOfThreads) {
         Thread[] threads = new Thread[nfOfThreads];
         for (int i = 0; i < threads.length; i++) {
             threads[i] = new MyThread();
             threads[i].start();
         }
         for (int i = 0; i < threads.length; i++) {
             try {
                 threads[i].join();//This means that means that the parent thread is waiting until the thread who called join that is thread[i] ends.
             } catch (InterruptedException e) {
               
             }
         }
     }
     public static void main(String[] args) {
         ThreadTestWithJoin test = new ThreadTestWithJoin();
         test.startThreads(20);
         System.out.println("At the end of main the thread which have executed are \n"+test.threadsName);
         System.out.println("Total threads executed are "+test.threadsName.size());
     }
      class MyThread extends Thread {
         public void run() {
             threadsName.add(getName());
         }
     }
}
Wait, notify and notifyAll methods are in Object class not in thread?

It was a design decision.

Java’s concurrency model needs "locks" and it was decided that each object was to be associated with a lock.

The wait, notify and notifyAll methods are not associated with a thread but with a lock, so the decision of coupling locks and objects meant that each
object should have wait,notify and notifyAll methods that operate on that object’s lock.

Explanation and Example:-

A gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists.
To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.

Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.

Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchorinized keywokd, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.

Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.

However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bath room is open ("notify") or ask people to wait when it is locked wait.

If the threads were designed to give the lock to one another, then one thread might ‘chose’ a ‘friendly’ thread leading to nepotism.Hence, the wait and notify methods have to be in Object class.Threads borrow keys from JVM and return to JVM.

NOW what is a lock?

Locks are inbuilt, hidden objects in a class. For static synchorinized methods the class object has a lock and for non-staic classes the objects instances themselves are the lock.

That is why while blocking a piece of code (instead of an entire method) we use synchronized(this)

If the same thread has to access various piece of code which are mutually exclusive to modifications then simply create two objects and call them lock1 and lock2 and use these two locks to synchornize.

example. if within the same code there are two areas that have to be synchronized and if the two areas are mutually exclusive then we SHOULD NOT USE this keyword for locking.

In our analogy, if there is a condom vending machine in the toilet, then if an user who does not want to buy condoms is using the bathroom, then the same key will lock the toilet and the vending machine and if there is a person in the queue who wants to use the toilet only to get a condom, then he is unnecessarily locked. In this case the gas station has to use two rooms and two keys. That way using one will not affect the other.

Synchronization :-

Intrinsic lock or monitor lock :-
Every object has an intrinsic lock associated with it. A thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

The Java programming language provides two basic synchronization idioms:
  • Synchronized methods
  • Synchronized statements

Synchronized method:-
To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter {
    private int c = 0;
    public synchronized void increment() {
        c++;
    }
}

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.The changes to the state of the object are visible to all the threads.

Synchronized statements:-
Synchronized statements must specify the object that provides the intrinsic lock
1. If case there are variables which are used together, in this case we can use one lock for synchronization
    public void addName(String name) {
        synchronized(this) {
        lastName = name;
        nameCount++;
        }
        nameList.add(name);
    }
2. If case there are variables which are never used together, in this case we should use separate locks for synchronization
    public class MsLunch {
        private long c1 = 0;
        private long c2 = 0;
        private Object lock1 = new Object();
        private Object lock2 = new Object();
        public void inc1() {
        synchronized(lock1) {
            c1++;
        }
        }
        public void inc2() {
        synchronized(lock2) {
            c2++;
        }
        }
    }
   
Re-entrant synchronization:- This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock
 

Thursday, November 14, 2013

JAVA Basics

System.out.println()

‘out’ is a static member variable belonging to the System class.

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut(). 

Thus out is  a static variable of system class of type PrintStream which is having a method println().

//the System class belongs to java.lang package
class System {
  public static final PrintStream out;
  //...
}

//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
} 

Java is platform independent

Every Java program is first compiled into an intermediate language called Java bytecode. The JVM is used primarily for 2 things: the first is to translate the bytecode into the machine language for a particular computer, and the second thing is to actually execute the corresponding machine-language instructions as well. The JVM and bytecode combined give Java its status as a "portable" language – this is because Java bytecode can be transferred from one machine to another.

But the JVM depends on the operating system – so if you are running Mac OS X you will have a different JVM than if you are running Windows or some other operating system. This fact can be verified by trying to download the JVM for your particular machine – when trying to download it, you will be given a list of JVM’s corresponding to different operating systems, and you will obviously pick whichever JVM is targeted for the operating system that you are running.

Method Overloading :-
Overloading in Java can occur when two or more methods in the same class share the same name or even if a child class shares a method with the same name as one of it’s parent classes but
1.) The number of parameters is different for the methods 
2.) The parameter types are different. 

But it is not overloading if :-
1. Changing the return type of the method 
2. Changing the name of the method parameters, but not changing the parameter types.

Method Overriding :- 
Overriding occurs when an overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.

Overriding is a runtime phenomenon whereas overloading is a compile time phenomenon.

Private Constructor :- 
  1. It is used to limit the access of the constructor to class only.The object of class can not be instantiated outside the class. Like in case of singleton design pattern.
  2. It is used to prevent the creation of any object of the class entirely. This is used when a class has only static members which can be accessed using only the class name 
Copy Constructor :-
  1. It is a constructor of a class that accepts only one parameter and even that parameter is of the type as the class.
    public class A{
              public A(A a){
                 System.out.println("This is a copy constructor");
              }
    }
  2. It is used to create an object identical to the original one and to prevent the original object being altered.
Final modifier:-
  1. If used before method, the method can not be overridden.
  2. If used before class, the class can not be subclassed.
  3. If used before a variable, the variable can not be changed.
package com.arsoft.tutorial.javabasics;
public final class FinalModifier {
    public static final int a = 50;
    public static void main(String args[]){
        //Compile time error that final variable can not be reassigned
        a = 50;
    }
}
//Compile time error that final class can not be extended
class FinalModifierA extends FinalModifier{
   
}
class FinalModifierB {
    public final String sayHi(){
        return "Hi";
    }
}
class FinalModifierC extends FinalModifierB{
    //Compile time error that final method can not be overridden
    public final String sayHi(){
        return "Hi Anshul";
    }
}

Finally block :-

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block.

It will be called in any of the below scenario's:-
  1. The try block runs without any exception
  2. An exception is caught in catch block
  3. An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception. In this scenario, the call to the method ends, and the exception object is thrown to the enclosing method - as in the method in which the try-catch-finally blocks reside. But, before the method ends, the finally block is executed. 
  4. Finally takes precedence over the return statement. Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block will still be executed even if there is a return statement somewhere in the try block.
It will not be called in below scenario's:-
  1. System.exit() is called.
  2. JVM crashes. 
If there is a return statement in finally block as well, the values returned in try or catch block will be overridden but this is a bad idea to return a value in finally block


Virtual Memory and Paging ;-
Real, or physical, memory exists on RAM chips inside the computer. Virtual memory, as its name suggests, doesn’t physically exist on a memory chip. It is an optimization technique and is implemented by the operating system in order to give an application program the impression that it has more memory than actually exists. Virtual memory is implemented by various operating systems such as Windows, Mac OS X, and Linux. Let’s say that an operating system needs 120 MB of memory in order to hold all the running programs, but there’s currently only 50 MB of available physical memory stored on the RAM chips. The operating system will then set up 120 MB of virtual memory, and will use a program called the virtual memory manager (VMM) to manage that 120 MB. The VMM will create a file on the hard disk that is 70 MB (120 – 50) in size to account for the extra memory that’s needed. The O.S. will now proceed to address memory as if there were actually 120 MB of real memory stored on the RAM, even though there’s really only 50 MB. So, to the O.S., it now appears as if the full 120 MB actually exists. It is the responsibility of the VMM to deal with the fact that there is only 50 MB of real memory. The VMM creates a file on the hard disk that holds the extra memory that is needed by the O.S., which in our case is 70 MB in size. This file is called a paging file (also known as a swap file), and plays an important role in virtual memory. The paging file combined with the RAM accounts for all of the memory. Whenever the O.S. needs a ‘block’ of memory that’s not in the real (RAM) memory, the VMM takes a block from the real memory that hasn’t been used recently, writes it to the paging file, and then reads the block of memory that the O.S. needs from the paging file. The VMM then takes the block of memory from the paging file, and moves it into the real memory – in place of the old block. This process is called swapping (also known as paging), and the blocks of memory that are swapped are called pages. The group of pages that currently exist in RAM, and that are dedicated to a specific process, is known as the working set for that process.


Memory Management in JAVA
All the objects in JAVA are stored in heap while all the references or variables are stored in stack.  The stack is for transient data objects (like variables in your methods). The heap is for things that have to persist awhile longer.

1. Heap and Nursery:- All JAVA objects reside on a heap. This heap is created when JVM is initialized.The heap is divided into two parts
  • Young space where the new and short lived objects reside
  • Old space where long living objects reside
Young collection removes the garbage from Young space swiftly and promotes the long living objects to old space while old collection removes garbage from old space only after it is full.

Large Objects (size >2kb) are allocated directly on heap while the small objects are allocated in thread local areas (TLAs)

Any java objects needs
  1. 12 bytes for object header
  2. 8 bytes for boundary
  3. rest depends on the datatype of member variables
    1. byte, booleans          1 byte
    2. short, char                2 bytes
    3. int, float                   4 bytes
    4. long, double             8 bytes
 Any java reference variables needs
  1.  4 bytes if heap is under 32G 
  2. 8 bytes ig heap is more 
Difference between == and equals:-
“==” tests if references are equal and equals() tests if values are equal

char[] is preferred over String for security sensitive information:-
Because String is immutable and will be present in heap until garbage collection kicks in.
Volatile is used to indicate that a variable's value will be modified by different threads.

static class : A class can be static only if it is declared inside another class. In this case we can use the nested class without having an instance of the outer class.

E.g.
class OuterClass{
    public static class StaticNestedClass{
    }
} 

Types of JAVA classes
  • Top-level classes
  • Inner classes

Top Level classes
A normal java class is a top level class

Inner classes
A class defined inside a top level class is called inner class. They are of below types
  • Anonymous class
  • Local class
  • Member class
    • Static
    • Non static

Anonymous class
Classes that are declared and instantiated within the same statement. They do not have names, and they can be instantiated only once. They can not be static

E.g.
    okButton.addActionListener( new ActionListener(){
       public void actionPerformed(ActionEvent e){
          dispose();
       }
    });

Local Class
Classes that are created and used inside a block. They can not be static

E.g.
    //some code block .......{
       class ListListener implements ItemListener {
          List list;
          public ListListener(List l) {
         list = l;
          }
          public void itemStateChanged(ItemEvent e) {
         String s = l.getItemSelected();
         doSomething(s);
          }
       }
       List list1 = new List();
       list list2 = new List();
       list1.addItemListener(new ListListener(list1));
       list2.addItemListener(new ListListener(list2));
    }

Member
Classes that are defined within the body of a class.
The member class is the only class that you can declare static or non static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared
To initialize a static inner class we can use
             StaticInnerClass sic = new StaticInnerClass ();
but to initilaize a non static inner class we will need an instance of OuterClasse
             OuterClass oc = new OuterClass();
             NonStaticInnerClass nsic = oc.new NonStaticInnerClass();
A static member class is also called Nested top-level class

Default Initial Values
boolean                                              false
byte                                                    (byte) 0
short                                                   (short) 0
int                                                       0
long                                                    0L
char                                                    \u0000
float                                                    0.0f
double                                                0.0d
object reference                                 null

PS:- Each variable value is initialized twice, first time to the default initial value and then to the given value.

Features of Constructors: 
  • They are used to initialize the variables of class
  • They can have parameters but no return type
  • The public, private and protected access levels can not be inherited by subclass. The access level only determines the ability to initialize object
  • It is always used with new operator
  • A class can have any number of overloaded constructor
  • A class can have no-argument constructor
  • A constuctor of a class can be called from another constuctor of the same class using this() and it should be first statement in the constructor
  • It has always the name as that of class
  • Every class which is having no class constructor, has a default no argument constructor which is initialized by JVM. So every class in indeed has at least one constructor.






Differences between JDK6 and JDK 7:-

1. substring():- In case of jdk6




Design Patterns

A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

String in JAVA

String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized

StringBuilder is faster than StringBuffer as it is not synchronized.

The maximum size for either of these is Integer.MAX_VALUE (231 - 1 = 2,147,483,647)

package com.anshul.projects.iwts.tutor.string;
public class StringDemo {
    public static void main(String args[]){
        String s = "Let’s test";
        s.concat(" if the String object is IMMUTABLE");
        System.out.println(s);
        s = s.concat(" if the String object is IMMUTABLE");
        System.out.println(s);
        StringBuffer s1 = new StringBuffer("Hello");
        s1.append(" Hello");
        System.out.println(s1);
        s1 = s1.append(" Hello ");
        System.out.println(s1);
    }
}


==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:  

The equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory. So, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations.

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...