Q: What is the Contract First and Service First Approach?
Contract-first is where you create the WSDL, and then you can create the implementation from this, and since the WSDL is your contract, this would be contract-first.
Service First or Contract-last or Code-First is where the WSDL is created from the source code, or implementation, so it will most likely be generated by a tool rather than created by the developer.

Q: Which is the better approach to web services – contract first or contract last?
Contract-first is the generally accepted ‘best practice.’.Both the producer and consumer of the service exactly what is needed and what is expected. It empowers the developer to use the full capabilities of XML (restrictions, patterns, …) and from there it is fairly easy to generate code for any programming language. One other reason is that the schema in the is the contract between the two systems talking to each other. If the developer creates the WSDL from code, technical dependencies on the specific programming language might be introduced (datatypes, …)

WSDL should be manually composed without using third party tool. Many now adays are not doing so since they find code first approach and generating WSDL is easy for them.

Below is simple code which generates WSDL using @WebService annotation

@WebService
public class TestService {
	@WebMethod
	public String sayHello(String msg){
		return "Hello "+msg;
	}	
}

Q: What JAXB does?
JAXB helps in converting Java Class to XML and Vice Versa. We always code our business logic in Java but the web service communication always happens by XML. So in order for this to happen we use third party tools like JAXB or JAXB2 plugins.

Q: What is the structure of SOAP Envelope?
A SOAP based web service message is a hierarchical XML packet, consisting of up to four parts.

  1. Envelope
  2. Header
  3. Body(Contains either Request or Response)
  4. Fault(Found only in Response)
<?xml version = "1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" 
   SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">
 
   <SOAP-ENV:Header>
      ...
      ...
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      ...
      ...
      <SOAP-ENV:Fault>
         ...
         ...
      </SOAP-ENV:Fault>
      ...
   </SOAP-ENV:Body>
</SOAP_ENV:Envelope>

Q: What are different part of WSDL Denote?
wsdl:types – Datatypes used in Request and Response. It contains the copy of entire XSD.
wsdl:message – Request and Response structure composed from various datatypes defined above.
wsdl:portType – PortType is like Interface. It tells about methods, their input and output.
wsdl:binding – Binding is like implementation of PortType. Defines how the SOAP service could be accessed over http,https or MQ.
wsdl:service – Contains the port which defines the Endpoint URL, port number

Q: What does REST Webservice follow? Contract First or Service First?
Unlike SOAP that exposes methods and method signatures, REST exposes resources. An understanding of the media types used in the exchange of those resources is all a REST client needs in order to communicate with a REST web service. There is no need for a separate document to describe the resources. Hence REST follows Service First Approach though Contract First Approach could be implemented.

Q: What are the Key Components in Webservices
All the web services has a Service Definition. Service Definition contains the following

  1. Request and Response Format
  2. Request Structure
  3. Response Structure
  4. API Endpoints

Q: what is the difference between XSD and WSDL?
WSDL (Web Services Description Language) describes your service and its operations – what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

It’s a description of the behavior of the service – its functionality.

XSD (XML Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern), and so forth.

WSDL documents have an associated XSD that shows what is valid to put in a WSDL document.

Q:Short Descriptions on Tags below

<definitions name = "HelloService"
   targetNamespace = "http://www.examples.com/wsdl/HelloService.wsdl"
   xmlns:tns = "http://www.examples.com/wsdl/HelloService.wsdl"
   xmlns = "http://schemas.xmlsoap.org/wsdl/"
   xmlns:soap = "http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
.
.
</definitions>
  • targetNamespace – is a convention of XML Schema that enables the WSDL document to refer to itself
  • xmlns:tns – When a complex object type is defined the targetnamespace could be used for deriving the way the object should be interpreted
    Refer Here
  • xmlns – Unique Identifier for xml elements
  • xmlns:soap – It should always have the value of: “http://www.w3.org/2003/05/soap-envelope/”.The namespace defines the Envelope as a SOAP Envelope.
    If a different namespace is used, the application generates an error and discards the message.
  • xmlns:xsd – XSD is XML Schema Definition Language. XSD files are used to validate that XML files conform to a certain format.Without XML Schema (XSD file) an XML file is a relatively free set of elements and attributes. The XSD file defines which elements and attributes are permitted and in which order. In SOAP, XSD tells how the Structure of Request and Response should be

What is use of xsi:schemalocation?
While developing Webservice XSD is the first file that is created. XSD contains data types that would be used in requests and responses. Once XSD is created Request and Response would be developed based on XSD. xsi:schemalocation is a tag used in response and request which helps in validating the datatype used conforms to one is XSD. In other words, it helps the IDE to keep a check by cross-checking elements defined in request and response are the same as one defined in XSD.

Q1:Difference between concrete wsdl and abstract wsdl
Typically a wsdl contains – types, Messages, porttype, Binding and service
Using Types ,messages and porttype we can’t do anything with that.. which is abstract part. Binding and service has more info about the webservices. So it’s concrete.abstract wsdl is enough to consume a soap service … If we use an abstract wsdl and if we try to generate classes we will not be able to see the java files and only class files can be obtained …
Concrete wsdl can provide complete details about the service…

It is not safe to provide the concrete wsdl to the consumer if he is not to be trusted ..
Please Refer Here

Q2:What is the Difference between SOAP and REST
Refer Here

Q3:What do you mean by Stateless in terms of RESTAPI?
The state of the client application is never stored on the server and is passed on. In this process, the client send all the information that is required for the server to fulfill the HTTP request and the server responds make with HTTP Response.The following are the advantages of Statelessness
HTTP protocol and REST web service, both shares the feature of statelessness. Every method required for communication is identified as an independent method i.e. there are no dependencies to other methods.Any previous communication with the client and server is not maintained and thus the whole process is very much simplified.If any information or metadata used earlier in required in another method, then the client sends again that information with HTTP request.

Q4:What is Resource in RESTApi? What is Resource Representation? Why its important?
‘Resource’ is defined as an object of a type which can be an image, HTML file, text data, and any type of dynamic data.JSON
YAML,XML,HTML are some of the Resource Types.Representation of Resource is important because it determines the easy identification of resources. With proper representations of resource in the proper format, allows the client to easily understand the format.

Q5:What is Caching?Use of Cache Control Header?
Caching is the process in which server response is stored so that a cached copy can be used when required and there is no need of generating the same response again. This process not only reduces the server load but in turn increase the scalability and performance of the server. Only the client is able to cache the response and that too for a limited period of time.

Cache control header can help in attaining cache ability.
Public: Resources that are marked as the public can be cached by any intermediate components(gateways) between the client and server.
Private: Resources that are marked as private can only be cached by the client.
No cache means that particular resource cannot be cached and thus the whole process is stopped.

Q6:What is Payload?
Request data which is present in the body part of every HTTP message is referred as ‘Payload’. In Restful web service, the payload can only be passed to the recipient through POST method.

Q7:Different HTTP methods
GET: This is a read only operation which fetches the list of users on the server.
PUT: This operation is used for the creation of any new resource on the server.
POST: This operation is used for updating an old resource or for creating a new resource.
DELETE: As the name suggests, this operation is used for deleting any resource on the server.
OPTIONS: This operation fetches the list of any supported options of resources that are available on the server.

Q8:What is the difference between PUT method and POST method?
PUT is idempotent, so if you PUT an object twice, it has no effect. You can update or create a resource with PUT with the same object URL.POST is to create new resource.If you are depending on server to create new resource using POST will result in multiple resource creation since server is the one which decides where to place the object. refer here

Q9:What is JAX-RS and what are its implementations?
JAX-RS is defined as the Java API for RESTful web service. Few of its implementations include Jersey,RESTEasy,Apache CFXPlay

Q10:What is use of OPTIONS and HEAD?
OPTIONS tells you things such as “What methods are allowed for this resource”.OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?OPTIONS method returns info about API (methods/content type)

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource.Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval.HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned.

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270

Q11.Maximum length of HTTP GET request?
The limit is dependent on both the server and the client.As already mentioned, HTTP itself doesn’t impose any hard-coded limit on request length; but browsers have limits ranging on the 2kb – 8kb .If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning

HTTP 1.1 defines Status Code 414 Request-URI Too Long for the cases where a server-defined limit is reached which is usually configureable somewhere in the server configuration.For the case of client-defined limits, there is no sense on the server returning something, because the server won’t receive the request at all.

Q12.What is need for HttpMessageConverter?
Spring MVC uses HttpMessageConverter to convert the Http request to an object representation and back.Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.Spring will use the “Accept” header to determine the media type that it needs to respond with and uses the “Content-Type” header to determine the media type of the request body.

Default Message Converters in Spring MVC
StringHttpMessageConverter: it converts Strings from the HTTP request and response.
FormHttpMessageConverter: it converts form data to/from a MultiValueMap.
ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
AtomFeedHttpMessageConverter: it converts Atom feeds.
RssChannelHttpMessageConverter: it converts RSS feeds.

@EnableWebMvc annotation, it automatically registered default Http message converters with application as listed above according to available library in the class path.

Q13.What is WS-Addressing?
WS-Addressing is useful in situations where the SOAP response can’t be served immediately. Either the resources to form the response are not available right away or the result itself takes a long time to be generated. There are times where your business takes time.something which needs manually intervention, something to be approved, whatever, but it takes days to do it. keeping the connection opened all that time and waiting for the response would be inefficient.notification process comes to rescue in these kind of scenarios.The client makes a requests but does not wait for the response. It instead instructs the server where to send the response by use of a “reply to” address. Once the response is available, the server connects to that address and sends the response.Instead of relying on network-level transport to convey routing information, a message utilizing WS-Addressing may contain its own dispatch metadata in a standardized SOAP header.WS-Addressing you are not tied to that. You can demand the response on another type of channel. Request comes on HTTP for example, but you can instruct the server to send the response back over SMTP, for example.

Q14.What is SOAP handler or handler Resolver ?
The handler framework in the Java API for XML Web Services (JAX-WS) allows applications to address cross-cutting and/or system-level concerns by opening the service and client runtimes for applications to plug in modular components. SOAP handler is a SOAP message interceptor, which is able to intercept incoming or outgoing SOAP message and manipulate its values. For example, attach a SOAP handler in client side, which will inject client’s computer MAC address into the SOAP header block for every outgoing SOAP message that is send by the client. In server side, attach another SOAP handler, to retrieve back the client’s MAC address in SOAP header block from every incoming SOAP message.This mechanism also allows the separation of the most fundamental concerns of application software in Web services development, effectively abstracting the system service into handlers and leaving the clients and services to focus on business logic.

JAX-WS specifies two types of handlers:

  1. Protocol handlers are specific to a protocol and may access or change the protocol-specific aspects of a message
  2. Logical handlers are protocol-agnostic and act only on the payload of a message

How XML Namespaces work?
Every element (or attribute) in XML belongs to a namespace, a way of “qualifying” the name of the element.Imagine you and I both invent our own XML. You invent XML to describe people, I invent mine to describe cities. Both of us include an element called name. Yours refers to the person’s name, and mine to the city name

<person>
    <name>Rob</name>
    <age>37</age>
    <homecity>
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

If our two XMLs were combined into a single document, how would we tell the two names apart? As you can see above, there are two name elements, but they both have different meanings.The answer is that you and I would both assign a namespace to our XML, which we would make unique:

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person"
                  xmlns:cityxml="http://www.my.example.com/xml/cities">
    <personxml:name>Rob</personxml:name>
    <personxml:age>37</personxml:age>
    <cityxml:homecity>
        <cityxml:name>London</cityxml:name>
        <cityxml:lat>123.000</cityxml:lat>
        <cityxml:long>0.00</cityxml:long>
    </cityxml:homecity>
</personxml:person>

All of the tags that start with personxml: are tags belonging to your XML, all the ones that start with cityxml: are mine.

If you declare a namespace without the identifier, that is, xmlns=”http://somenamespace”, rather than xmlns:rob=”somenamespace”, it specifies the default namespace for the document.

Q1:What would be the output for the following Program?

Output:

True
False
False

Question1.java

public class Question1 
{
	public static void main(String[] args) 
	{
		String Name1 = "Mugil";
		String Name2 = "Mugil";
		String Name3 = new String("Mugil");
		String Name4 = new String("Mugil");
		
		System.out.println(Name1 == Name2);
		System.out.println(Name2 == Name3);
		System.out.println(Name3 == Name4);
	}
}

Output

true
false
false

Q2: there is a arraylist with Employee objects in it. The list contains duplicate Employee objects, Now i need to remove the duplicate objects from the list.how do you do that?
Override equals and hashcode and use equals method to compare two objects.If the class is coming from jar or uneditable use extends and override the hashcode and equals method
Question2.java

import java.util.ArrayList;
import java.util.List;

public class Question2 
{
	public static void main(String[] args) 
	{
		List<Employee> arrEmp = new ArrayList<Employee>();
		
		Employee objEmp1 = new Employee();
		objEmp1.setName("Mugil");
		objEmp1.setEmpId(101);
		
		Employee objEmp2 = new Employee();
		objEmp2.setName("Mugil");
		objEmp2.setEmpId(101);
		
		Employee objEmp3 = new Employee();
		objEmp3.setName("mugil");
		objEmp3.setEmpId(101);
		
		
		System.out.println("Both Object are Equal - " + objEmp1.equals(objEmp2));
		System.out.println("Both Object are Equal - " + objEmp3.equals(objEmp2));
		
	}
}

Question2.java

class Employee
{
	String Name;
	int EmpId;
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + EmpId;
		result = prime * result + ((Name == null) ? 0 : Name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (EmpId != other.EmpId)
			return false;
		if (Name == null) {
			if (other.Name != null)
				return false;
		} else if (!Name.equals(other.Name))
			return false;
		return true;
	}
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public int getEmpId() {
		return EmpId;
	}
	public void setEmpId(int empId) {
		EmpId = empId;
	}
}

`

Output

Both Object are Equal - true
Both Object are Equal - false

Q3:What will happen if you call return or System.exit in try or catch block?Will finally block execute?
Scenario 1: Positive Scenario with no System.exit()

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {
			return "Mugil";
		} catch (Exception e) {
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

Output

Finally Block Executed
Mugil

Scenario 2 :System.exit() in try block before exception

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {
			System.exit(1);
			throw new NullPointerException("return value is null");
		} catch (Exception e) {
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

If the System.exit(1) is used after throw new NullPointerException then it compiler will complain for unreachable code.
Finally will not get executed
Output(Blank Screen)


Scenario 3 :System.exit() in catch block before exception

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {			
			throw new NullPointerException("return value is null");
		} catch (Exception e) {
			System.exit(1);
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

Output(Blank Screen)


The only times finally won’t be called are

  1. If you invoke System.exit();
  2. If the JVM crashes first;
  3. If there is an infinite loop
  4. If the host system dies; e.g. power failure, hardware error

Q3a:What are parameters of System.exit?

  • Zero(0) – when execution went fine – Everything Okay
  • Positive(1-127) – Something I expected could potentially go wrong went wrong anticipated exception – (bad command-line, can’t find file, could not connect to server)
  • Negative(values greater than 128) – Something I didn’t expect at all went wrong (system error – unanticipated exception – externally forced termination e.g. kill -9)

Q4:What is the difference between Iterator and ListIterator
When you loop through list use listiterator since it is faster then iterator. It can traverse in both directions. Iterator can be used over collections whereas list iterator call be used only for list

When you are simple moving through List but you are not modifying the List object foreach is more efficient.In case you want to perform operations on each element of list individually taking out the element in such case use Iterator.

ListIterator Iterator
ListIterator to traverse List only Iterator is used for traversing List and Set both.
ListIterator, we can traverse a List in both the directions (forward and Backward). traverse in only forward direction using Iterator
We cannot obtain indexes while using Iterator We can obtain indexes at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose.
We can add element at any point of time while traversing a list using ListIterator. We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it.
By using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods. We cannot replace the existing element value when using Iterator.
Methods of ListIterator:

add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)

Methods of Iterator:

hasNext()
next()
remove()

Q5:What would be the output of Following Program?

package com.mugil.org.qs;

public class Question4 
{
	public static void main(String[] args) 
	{
		my m = new my(){};
		m.myMethod();
		System.out.println(m.getClass().getSuperclass());
	}
}

abstract class my
{
	public void myMethod()
	{
		System.out.println("Abstract");
	}
}

Ans:The reason for this any anonymous class which has the same name as abstract class would be child class of the abstract class

Q6:Why we are unable to add primitives as generic type?

//Allowed
List<Integer> arrAges = new ArrayList<Integer>();

//Not allowed
List<int> arrAges = new ArrayList<int>();

Ans:This is to maintain backwards compatibility with previous JVM runtimes in the sense it could be referred by parent class instance Object

Q7: What would be the Output of following program

package com.mugil.org.qs;

public class Question7 
{
	public static void main(String[] args) {
		System.out.println(getSomeNumber());
	}
	
	public static int getSomeNumber()
	{
		try{
			throw new RuntimeException();			
		}finally{
			return 1;
		}
	}
}

Output

1

Ans: Finally will run at any cause other than system.exit() call.

Q7a: What would be the Output of following program

package com.mugil.org.qs;

public class Question7a 
{
	public static void main(String[] args) 
	{
		if(isQAAssured())
		  System.out.println("QA Checked");
		else
		  System.out.println("QA is not Checked");
	}
	
	public static boolean isQAAssured()
	{
		try 
		{
			return true;
		}
		finally 
		{
			return false;
		}
	}
}

Output

QA is not Checked

Q7a: What would be the Output of following program

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		javaHungry(null);
	}

	public static void javaHungry(Integer s)
	{
		System.out.println("Integer");
	}
	
	public static void javaHungry(Object s)
	{
		System.out.println("Object");
	}
	
	public static void javaHungry(String s)
	{
		System.out.println("String");
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method javaHungry(Integer) is ambiguous for the type Question8

Q8:The code wont compile since, To explain the things in details let have a look into the following code
Question8.java

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		javaHungry(null);
	}

	/*public static void javaHungry(Integer s)
	{
		System.out.println("Integer");
	}*/
	
	public static void javaHungry(Object s)
	{
		System.out.println("Object");
	}
	
	public static void javaHungry(String s)
	{
		System.out.println("String");
	}
} 

Output

String

The reason the above code worked is java compiler tries to find out the method with most specific input parameters to invoke a method.We know that Object is the parent class of String, so the choice was easy. If more than one member method is both accessible and applicable to a method invocation … The Java programming language uses the rule that the most specific method is chosen.

Now when the same is used in the before code which has String and int.You will get compile time error as The method foo(Object) is ambiguous for the type Test because both String and Integer class have Object as parent class and there is no inheritance. So java compiler doesn’t consider any of them to be more specific, hence the method ambiguous call error.

What would be the output?

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		callMe(null);
	}

	public static void callMe(Exception e) {
		System.out.println("Exception");
	}

	public static void callMe(NullPointerException ne) {
		System.out.println("NullPointerException");
	}

	
	public static void callMe(Object s)
	{
		System.out.println("Object");
	}
}

Output

NullPointerException

As above explained, here callMe(NullPointerException ne) is the most specific method because it’s inherited from Exception class and hence this code compiles fine and when executed prints “NullPointerException”.

What would be the output?

package com.mugil.org.qs;

public class Question9 
{
	public static void main(String[] args) 
	{
		System.out.println(methodOfA());
	}
	
	public static int methodOfA()
	{	
		return (true?null:1);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.org.qs.Question9.methodOfA(Question9.java:12)
	at com.mugil.org.qs.Question9.main(Question9.java:7)
  1. Now when you see the above code the first thing you notice is the code might throw compilation error.how a int can return a null.Whenever you return a primitive value from a method then it would be autoboxed to the wrapper type and sent back to calling method
  2. int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.
  3. So the output would be runtimeexception that is NullPointerException

Q9:What would be the output?

package com.mugil.org.qs;

public class Question10 
{
	public static void main(String[] args) 
	{
		System.out.println("main1");
		main ("main2");
	}
	
	public static void main(String arg)
	{
	      System.out.println(arg);
	}
}

Output

main1
main2

Ans:Overloading static methods are allowed. Overloading is legal, Overriding is illegal since the static methods belong to a class and there could not be method with same name and parameters within the class

Q11:What would be the output?

package com.mugil.org.qs;

public class Question11 
{
	public static void main(String[] args) 
	{
		try 
		{
			printName();
			System.out.println("Inside Try Block");
		}
		catch (Exception e) 
		{
			System.out.println("Inside Exception Block");
		}
		finally 
		{
			System.out.println("Inside finally Block");
		}
	}
	
	public static void printName()
	{
		throw new Error();
	}
}

Output

Exception in thread "main" Inside finally Block
java.lang.Error
	at com.mugil.org.qs.Question11.printName(Question11.java:24)
	at com.mugil.org.qs.Question11.main(Question11.java:9)

Ans:-Control will go inside finally and Inside finally Block would be printed despite error.

Q11:What would be the output?

package com.mugil.org.qs;

public class Question12 
{
	public static void main(String[] args) 
	{
		Animal[] arrAnimal = {new Animal(), new Dog(),new Animal()};
		
		for (int i = 0; i < arrAnimal.length; i++) 
		{
			arrAnimal[i].doStuff();
		}
	}
}


class Animal
{
	public static void doStuff()
	{
		System.out.println("Animal Stuff");
	}
}

class Dog extends Animal
{
	public static void doStuff()
	{
		System.out.println("Dog Stuff");
	}	
}

Output

Animal Stuff
Animal Stuff
Animal Stuff

Ans:-Since the methods are static it belongs to class not objects, the reference types are ignored and the calling type are considered. In our case Animal.

Q12:Why Fail fast are not thread safe where as fail safe are thread safe?
Concurrent Modification: Concurrent Modification in programming is to modify an object concurrently when another task is already running over it. For example, in Java to modify a collection when another thread is iterating over it. Some Iterator implementations may choose to throw ConcurrentModificationException if this behavior is detected.

Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.

To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class FailFastExample {
    public static void main(String[] args)
    {
        Map<String, String> cityCode = new HashMap<String, String>();
        cityCode.put("Delhi", "India");
        cityCode.put("Moscow", "Russia");
        cityCode.put("New York", "USA");
 
        Iterator iterator = cityCode.keySet().iterator();
 
        while (iterator.hasNext()) {
            System.out.println(cityCode.get(iterator.next()));
 
            // adding an element to Map
            // exception will be thrown on next call
            // of next() method.
            cityCode.put("Istanbul", "Turkey");
        }
    }
}

Output

India
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
    at java.util.HashMap$KeyIterator.next(HashMap.java:1466)
    at FailFastExample.main(FailFastExample.java:18)

Q13:What is Marshalling and Unmarshalling?
To marshall an object is to convert it into a form suitable for serialised storage or transmission; that is, to convert it from its native form within the JVM’s memory, into a form that could be sent down a wire, inserted into a file/database, etc. The specifics will vary depending on the form of marshalling involved; Java’s default serialisation mechanism is one way, but converting the object into an XML or JSON representation are equally valid.

Unmarshalling is just the reverse/other side of this process; taking a representation of the object created by marshalling, and using it to reconstitute an object instance within the JVM.

Q14:What will happen if we directly call run method?

class TestRunnable implements Runnable
{
    public static void main(String[] args)
    {
      TestRunnable nr = new TestRunnable();
      Thread t = new Thread(nr);
      t.setName("Fred");
      t.start();
    }

    public void run()
    {
      System.out.println("TestRunnable in " + Thread.currentThread().getName());
    }
}

Output if only start is called:

TestRunnable in Fred

Output if only run is called:

TestRunnable in main

Existing thread will stop it’s current execution and it will call the newly created thread for which you called run()

Q14:Why is char[] preferred over String for passwords?
Strings are immutable. That means once you’ve created the String, if another process can dump memory, there’s no way (aside from reflection) you can get rid of the data before garbage collection kicks in.Character arrays (char[]) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0’s, the password is secure.With an array, you can explicitly wipe the data after you’re done with it. You can overwrite the array with anything you like, and the password won’t be present anywhere in the system, even before garbage collection.

Q15:Java is pass-by-value or pass-by-reference?
Java is pass-by-value.Value of reference(address) is passed as value.

public class Question13 
{
	public static void main(String[] args) 
	{
		Points objPoints = new Points();
		Question13 objQuestion13 = new Question13();
		objPoints.setPoint(10);
		
		System.out.println(objPoints.getPoint());
		objQuestion13.swap(objPoints);
		System.out.println(objPoints.getPoint());
		
		
		objQuestion13.swapValue(objPoints);
		System.out.println(objPoints.getPoint());
	}	
	
	public void swap(Points pobjPoints)
	{
		Points objPoints = new Points();
		objPoints.setPoint(30);
		pobjPoints = objPoints;
	}
	
	
	public void swapValue(Points pobjPoints)
	{	
		pobjPoints.setPoint(30);
	}
}


class Points
{
	Integer point;
	
	public Integer getPoint() {
		return point;
	}
	public void setPoint(Integer point) {
		this.point = point;
	}
}

Output

10
10
30
  1. In the above program in the swap method we are passing the reference as value.So inside swap method the reference is assigned to new value and nothing happens outside
  2. In the swapvalue method again reference is passed as parameter, but we change the value by setting the value inside the location, inside the container using the setter method. so the changes we do inside would be shown up outside

Q16:Why does StringBuffer/StringBuilder not override equals or hashCode?

String Name1=new String("Mugil");
		String Name2=new String("Mugil");
		
		Map<String, Integer> hmNames = new HashMap();
		hmNames.put(Name1, 30);
		hmNames.put(Name1, 48);
		
		for (Map.Entry<String,Integer> entry : hmNames.entrySet()) 
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

Output

Key = Mugil, Value = 48
StringBuilder Name1 = new StringBuilder("Mugil");
		StringBuilder Name2 = new StringBuilder("Mugil");
		
		Map<StringBuilder, Integer> hmNames = new HashMap();
		hmNames.put(Name1, 30);
		hmNames.put(Name1, 25);
		
		for (Map.Entry<StringBuilder,Integer> entry : hmNames.entrySet()) 
           System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

Output

Key = Mugil, Value = 25

overriding hashCode() for mutable objects, since modifying such an object that is used as a key in a HashMap could cause the stored value to be “lost.”.In other sense if you have overridden the hashcode then the class would become mutable like in first hashmap example where String becomes mutable incontext to hashMap.String are immutable, but when the same is used in hashMap it becomes mutable because strings having Same value despite having different memory locations replace the before string since they have hashcode and equals overridden in their class.

Q17:When do you prefer to use ibatis over hibernate
Hibernate works well for case Create/Update/Delete some complex domain entities.myBatis is great for fetch queries (case 2) where you just want an answer. Run analytic fetch queries (i.e. summation/aggregation queries).Hibernate would attempt to load the entire object graph and you’d need to start tuning queries with LazyLoading tricks to keep it working on a large domain. Conversely if you just want some analytic POJO page, the myBatis implementation of the same query would be trivial.

Q18:What is the difference between singleton scope in spring and singleton pattern?
One is scope of bean in spring container and another is design pattern, single object per jvm instance.

Q19:Why does Map interface not extend the Collection interface in the Java Collections Framework?
One of the reason is other than map, all the interfaces designed to store a single element. But map is storing the elements in the key value pair.So methods in Collection interface are incompatible for Map interface.Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.

Q20:How to create a ArrayList of fixed size in java
Note the question again.The question is wrong.For arrayList we can only set the Capacity not Size.
Capacity is how many elements the list can potentially accommodate without reallocating its internal structures.When you call new ArrayList(10), you are setting the list’s initial capacity, not its size.Size is the number of elements in the list.So the question supposed to be how will you allocate arrayList with some number of capacity.

List<Integer> arr = new ArrayList<Integer>(10);
System.out.println(arr);
System.out.println(arr.size());

Output

[]
0

So from above code though the memory space for the arrayList has been allocated the size of the array is still 0.

Now I want to allocated ArrayList with Size 10 with initial values being 0 in that.

public static void main(String[] args) 
	{	
		ArrayList<Integer> arr = new ArrayList<Integer>(Collections.nCopies(10, 0));
		System.out.println(arr);
		System.out.println(arr.get(0));
	}

Output

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
0

Q21:Has anyone used ArrayBlockingQueue? How does it work ?
The ArrayBlockingQueue class implements the BlockingQueue interface. ArrayBlockingQueue is a bounded, blocking queue that stores the elements internally in an array. That it is bounded means that it cannot store unlimited amounts of elements. There is an upper bound on the number of elements it can store at the same time. You set the upper bound at instantiation time, and after that it cannot be changed.

BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
queue.put("1");
String string = queue.take();

Q21:What is the significance of the attribute delete orphan in hibernate
DELETE_ORPHAN means if an entity is removed from a related one-to-many collection, then not only disassociate it from the current entity, but delete it.Lets take a Employee and Address Model.If you do a Cascade Delete in the Employee then the Employee rows would be removed from the Employee table and the association between the Address and the Employee is removed. The Row in Address table still exist and its a orphan record not referred. Now when you do delete orphan also this row in the address table would also be deleted.
de-associating the parent and child relation and then immediately delete orphan records from db.

Q22:What is difference between pojo and javabean?
Please Refer Answer

Q23: Difference between comparator and comparable?
Please Refer Here

Q24: What is coercion polymorphism in java
For example, you divide an integer by another integer or a floating-point value by another floating-point value. If one operand is an integer and the other operand is a floating-point value, the compiler coerces (implicitly converts) the integer to a floating-point value to prevent a type error. (There is no division operation that supports an integer operand and a floating-point operand.) Another example is passing a subclass object reference to a method’s superclass parameter. The compiler coerces the subclass type to the superclass type to restrict operations to those of the superclass.

Q25: What is double dispatching
please refer here

Q26: How does cocurrentmodification exception occur while modifying array list. To be precise based on which indicator
When we iterate through the same list and when we try to modify the same list … Then we get the concurrent modification exception …
Fail fast iterator is used for iteration so we get that error.There is an indicator called modcount which is checked inbetween every operation to make sure whether List is modified or not.

Q27: How will you copy object attributes from one object to another or how to create a object which has replica of all attributes from another object ?
Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process

Shallow copy
The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow copy is not 100% independent of original object.

Deep Copy
Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object or vice-versa.

clone is tricky to implement correctly.It’s better to use Defensive copying, copy constructors or static factory methods.

Refer Here

Q28: While doing hashing we use to have prime numbers to perform modulo operation?even when u generate equals and hashcode in eclipse for ur class you would get 31 as divisor, culd someone explain this?
What is Prime Number
A number that is divisible only by itself and 1.Primes are unique numbers. They are unique in that, the product of a prime with any other number has the best chance of being unique due to the fact that a prime is used to compose it. This property is used in hashing functions.Given a string “Samuel”, you can generate a unique hash by multiply each of the constituent digits or letters with a prime number and adding them up. This is why primes are used.

Now why is 31 used?
Using a prime of 31 gives a better distribution to the keys, and lesser no of collisions. If you take over 50,000 English words (formed as the union of the word lists provided in two variants of Unix), using the constants 31, 33, 37, 39, and 41 will produce less than 7 collisions in each case.Using P(31), as it’s the cheapest to calculate (because 31 is the difference of two powers of two). P(33) is similarly cheap to calculate, but it’s performance is marginally worse, and 33 is composite(3*11=33)

Q29:You are thrown with a chained exception, now you need to find the root cause for the exception, which method will you use to get the actual cause for the exception?

Throwable getCause(Throwable e) {
    Throwable cause = null; 
    Throwable result = e;

    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}

Same using Recursion

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Using ApacheUtils

Throwable getRootCause(Throwable throwable) 
String getRootCauseMessage(Throwable th) 
java.lang.UnsupportedClassVersionError: test_hello_world :
 Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)

Why this Happens?
When you did maven build in Java 8 and try to deploy the ear file in Server which uses Java 1.7 then this issue happens.Error means you’re trying to load a Java “class” file that was compiled with a newer version of Java than you have installed.For example, your .class file could have been compiled for JDK 7, and you’re trying to run it with JDK 6.You must have compiled your code with a higher version and trying to run it using a lower version

Solution

Window -> Preferences -> Java -> Compiler and then set "Compiler compliance level" to 1.7

SOAP(Simple Object Access Protocol) – SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

WSDL(Web Services Definition Language) – A WSDL is an XML document that describes a web service. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract, and so on. what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

XSD(XML Schema Definition) – describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern), and so forth.It’s a description of datatypes and thus static properties of the service – it’s about data.

XSD definitions are part of WSDL in the tag

UDDI(Universal Description, Discovery, and Integration)– It is directly that is used to publish and discover public web services. UDDI is an obsolete failure that is almost never used in practice.UDDI works just like a telephone directory where a business can be registered as per its name, geography and the web services it publishes.UDDI registers the WSDL address URL of a web service. A client of the web service searches and finds the WSDL in the UDDI registry. Once received the WSDL can be invoked by using the URL.

WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL’s.
Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.
SOAP: Then when we actually order the food based on the Menu’s: Meaning we use proxy classes to call upon the service methods which is done using SOAP

SEI(service endpoint interface): The endpoint is a connection point where HTML files or active server pages are exposed. A web service endpoint is a URL that another program would use to communicate with your program. To see the WSDL, you add WSDL to the web service endpoint URL.

Parts of WSDL
Definitions – variables – ex: myVar, x, y, etc.

Types – data types – ex: int, double, String, myObjectType

Operations – methods/functions – ex: myMethod(), myFunction(), etc.

Messages – method/function input parameters & return types

ex: public myObjectType myMethod(String myVar)
Porttypes – classes (i.e. they are a container for operations) – ex: MyClass{}, etc.

Example of a Endpoint URL

protocol://host:port/partOfThePath

where

host=someIp
port=8080
partOfThePath=/some/service/path

serviceAEndpoint=http://host:port/some/service/path?dynamicParam=

Simple SOAP Request and Response

 package com.mugil.org;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

@WebService
public class Products 
{
  List<String> arrProducts = new ArrayList<String>();
	
  public Products()
  {
	arrProducts.add("Books");
	arrProducts.add("EReader");
	arrProducts.add("PDF");	
  }
  
  public String getProduct(int index)
  {
	return arrProducts.get(index);  
  }
}

SOAP Request

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:org="http://org.mugil.com/">
   <soapenv:Header/>
   <soapenv:Body>
 
      <org:getProduct>
         <arg0>0</arg0>
      </org:getProduct>
   </soapenv:Body>
</soapenv:Envelope>

SOAP Request

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:getProductResponse xmlns:ns2="http://org.mugil.com/">
         <return>Books</return>
      </ns2:getProductResponse>
   </soap:Body>
</soap:Envelope>

Part of WSDL
Typical WSDL document contains the following tags

  1. service – Contains the port which defines the Endpoint URL, port number
  2. portType – Contains input and output for an operation.Though there are multiple input and output arguments they would be bundled together as one message
  3. binding – Defines how the SOAP service could be accessed like over http,https
  4. types – Type defined as complex type defines the Input and output
  5. message – Kind of input and output taken as argument, mostly represented as Message

Service

 <wsdl:service name="ProductsService">
  <wsdl:port binding="tns:ProductsServiceSoapBinding" name="ProductsPort">
   <soap:address location="http://localhost:8096/WebService1/Products"/>
  </wsdl:port>
  </wsdl:service>

Porttype

 <wsdl:portType name="Products">
   <wsdl:operation name="getProduct">
    <wsdl:input message="tns:getProduct" name="getProduct"></wsdl:input>
    <wsdl:output message="tns:getProductResponse" name="getProductResponse"></wsdl:output>
   </wsdl:operation>
  </wsdl:portType>

Binding

<wsdl:binding name="ProductsServiceSoapBinding" type="tns:Products">
      <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
      <wsdl:operation name="getProduct">
         <soap:operation soapAction="" style="document" />
         <wsdl:input name="getProduct">
            <soap:body use="literal" />
         </wsdl:input>
         <wsdl:output name="getProductResponse">
            <soap:body use="literal" />
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>

Types

 <wsdl:types>
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified" targetNamespace="http://org.mugil.com/" version="1.0">
         <xs:element name="getProduct" type="tns:getProduct" />
         <xs:element name="getProductResponse" type="tns:getProductResponse" />
         <xs:complexType name="getProduct">
            <xs:sequence>
               <xs:element name="arg0" type="xs:int" />
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getProductResponse">
            <xs:sequence>
               <xs:element minOccurs="0" name="return" type="xs:string" />
            </xs:sequence>
         </xs:complexType>
      </xs:schema>

Message

 <wsdl:message name="getProduct">
      <wsdl:part element="tns:getProduct" name="parameters" />
   </wsdl:message>
   <wsdl:message name="getProductResponse">
      <wsdl:part element="tns:getProductResponse" name="parameters" />
   </wsdl:message>

Service(Class name with @WebService Annotation) 
                | 
Port(has Binding which defines portType)
                | 
    PortType(defines Operations)
                | 
Operations(defines input and output Type)

Annotations for WebService

@Webservice(name="MartCatalogue", portName="MartCataloguePort", serviceName="ProductsService", targetNamespace="MartProducts.com")
.
.
@WebMethod(action="fetch_products", operationName="fetchProducts")
.

name

<wsdl:portType name="MartCatalogue">
.
.

portName and serviceName

wsdl:port binding="tns:productServiceSoapBinding" name="productPort">
  <soap:address location="http://localhost:8096/WebService1/productService"/>
</wsdl:port>
.
.

targetNamespace
Defines unique set of operations under namespace.Defaults to package name in java in reverse order
targetNamespace=”MartProducts.com”

targetNamespace

<wsdl:operation name="fetchProducts">
.
.
 <wsdl:operation name="fetchProducts">
      <soap:operation soapAction="fetch_products" style="document" />
  .
  .

String is immutable for several reasons

Design Strings are created in a special memory area in java heap known as “String Intern pool”. If the String is not immutable, changing the String with one reference will lead to the wrong value for the other references.

Security: String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

Caching: Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys. Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of Java String class and makes it special.

Class loading: Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.

substring(), concat(), replace() etc are internally use String constructor for creating new string object.

In javascript date validation, while checking selected date is less than or equal to today’s date, time should be taken into consideration otherwise even when the selected day is equal to today’s date the validation fails.

i.e

 
 var strStartDate          = $("selectedStartDate").val();
 var strStartDateFormatted = new Date(strStartDate);
 var today                 = new Date();
 
 today.setHours(12,0,0,0);

  if(strStartDateFormatted == today)
    console.log("Both are Same");

new Date() will return date with time where as date returned using the datepicker does not contain time so if you directly compare new Date() which comes along with time it would return false even when the date-month-year are equal.

Date.prototype.withoutTime = function () {
    var d = new Date(this);
    d.setHours(0, 0, 0, 0);
    return d;
}

var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true

Coach Sleeper Class NON-AC COACH (ICF)

Coach Postion

Note

  1. While booking tickets book lower berth tickets which is easy to exchange with others
  2. Make sure the lower berth tickets are booked and the lower berth tickets should be booked
    with people who will not cancel tour at any cost because once they drop it would get assigned to senior citizens who may dampen your plan
  3. If there is more than 300 tickets left in a train try to book 3 lower, 3 middle so you can get all the seats in the cabin
  4. While booking tickets book when all tickets are available in same coach takes precedence to preferred coach
  5. If a person is holding a confirmed ticket and is unable to travel, then the ticket can be transferred to his/her family members including father, mother, brother, sister, son, daughter, husband or wife, not to the friend.For transfer of ticket, an application must be submitted at least 24 hours in advance of the scheduled departure of the train to chief reservation supervisor with ID proof.

To customize request parameter data binding, we can use @InitBinder annotated methods within our controller.

  1. The @InitBinder annotated methods will get called on each HTTP request if we don’t specify the ‘value’ element of this annotation.
  2. Each time this method is called a new instance of WebDataBinder is passed to it.
  3. To be more specific about which objects our InitBinder method applies to, we can supply ‘value’ element of the annotation @InitBinder. The ‘value’ element is a single or multiple names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to.
    @InitBinder("User")
    public void customizeBinding (WebDataBinder binder) 
    {
      .
      .
      .
    }

@Controller
@RequestMapping("/register")
public class UserRegistrationController 
{
    @InitBinder("user")
    public void customizeBinding (WebDataBinder binder) 
    {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        dateFormatter.setLenient(false);
        binder.registerCustomEditor(Date.class, "dateOfBirth", new CustomDateEditor(dateFormatter, true));
    }
    
    .
    . 
}

simpleDateFormat.setLenient(false); — Will check for out of range Date. For Example, If lenient is set to true, Aug 32 will be converted to Sep 1 .

To find the Variables assigned in JSP page use Windows->Show View->Display

  • In debug perspective: Window -> Show View -> Display
  • Put a break point in your code

Lets have a expression like one below

 <c:if test="${user.isSuccess}">
 .
 . 
 </c:if>

Now i need to find the value of user.isSuccess you can run the below code in in Display to see the values
set in the userObject

_jspx_page_context.findAttribute("user") 

It takes the value from the Page context and displays the values stored in the User Object

Note : The pageContext, _jspx_page_context are different variable names used for based on IDE while debugging JSP page.