Wednesday, 16 July 2014

Java Threading

  1. Why we need multi-threaded applications?
    Now a day most of servers are coming with multiple processors. To take benefit of these multi core processing capabilities, we need to run application with multiple processes concurrently. In Java, Thread is one of the way to create these light weight process, which can execute at same time and perform tasks. 
  2. What is synchronization ?
    Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.                                                                               
  3. Different way of creating thread?
    The thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
    a) public class MyThread extends Thread
    b) public class MyThread implements Runnable
  4. What is the difference between Thread.start() & Thread.run() method?
    Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.   In this sequence the thread changes state.
       
  5. Why do we need run() & start() methods?
    We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called.
    Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
  6. What is ThreadLocal class? 
    - A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
    - ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
    - In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
    - Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
    Good article on ThreadLocal: http://www-128.ibm.com/developerworks/java/library/j-threads3.html
    Good example : http://javaboutique.internet.com/tutorials/localdata/
    Multithreading in Swing: http://java.sun.com/developer/JDCTechTips/2003/tt1208.html
    Refer API Docs: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html
       
  7. When InvalidMonitorStateException is thrown? Why? 
    This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll())
          wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
  8. What is the difference between sleep(), suspend() and wait() ? 
    Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the
    sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
          t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.
          object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original,
    waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
  9. What happens when I make a static method as synchronized?
    Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.
  10. Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
    Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized.
    Below is the example which demonstrates this, The Common class has two methods
    synchronizedMethod1() and method1()
    MyThread class is calling both the methods in separate threads,
      

package com.learning.thread;

class MyThread extends Thread {
 private int id = 0;
 private Common common;   
 public MyThread(String name, int no, Common object) {  
  super(name);
  common = object;
  id = no;
 
 }
 public void run() {
  System.out.println("Running Thread" + this.getName());
  try {
   if (id == 0) {
    common.synchronizedMethod1();
   } else {
    common.method1();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
 public class Common {
  public synchronized void synchronizedMethod1() {
   System.out.println("synchronizedMethod1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("synchronizedMethod1 done");
  }

  public void method1() {
   System.out.println("Method 1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("Method 1 done");
  }

  public static void main(String... strings){
   Common c = new Common();
   MyThread t1 = new MyThread("MyThread-1", 0, c);
   MyThread t2 = new MyThread("MyThread-2", 1, c);
   t1.start();
   t2.start(); 
  }

 }



OutPut-->
1.  Running ThreadMyThread-1
2.  synchronizedMethod1 called
3.  Running ThreadMyThread-2
4.  Method 1 called
5.  synchronizedMethod1 done
6.  Method 1 done
This shows that method1() - is called even though the synchronizedMethod1() was in execution.
11. Can two threads call two different synchronized instance methods of an Object?
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods.
 public class Common {
  public synchronized void synchronizedMethod1() {
   System.out.println("synchronizedMethod1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("synchronizedMethod1 done");
  }

  public synchronized void synchronizedMethod2() {
   System.out.println("synchronizedMethod1 called");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }  
 }
12. What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
o    When two threads call Thread.join() on each other.
o    When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

13. What is Starvation? and What is a Livelock?
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
LiveLock
Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:

  •    When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
  •     When all the threads in a program are stuck in infinite loops.
Starvation
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.
Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

14. How to make sure Thread 1 , 2, 3 can run in sequence?
We can use join() to run the thread in sequence.
thread1.join();
thread2.join();
thread3.join();
package com.learning.thread;
public class Join implements Runnable {
 class çounter {
  private int c = 0;
  public void increment() {
   c++;
  }
  public void decrement() {
   c--;
  }
  public int value() {
   return c;
  }
 }
 @Override
 public void run() {
  for (int x = 1; x <= 5; x++) {
   System.out.println("this is thread "
     + Thread.currentThread().getName());
  }
 }
 public static void main(String[] args) throws Exception {
  Join j1 = new Join();
  Thread t1 = new Thread(j1, "1");
  Thread t2 = new Thread(j1, "2");
  Thread t3 = new Thread(j1, "3");
  t1.start();
  t1.join(0);
  t2.start();
  t2.join();
  t3.start();
 }
}
output :
this is thread 1
this is thread 1
this is thread 2
this is thread 2
this is thread 3
this is thread 3

 If you do not use join then you will get the result in random order.
15. What is ThreadGroup and its benefit?
The ThreadGroup class manages groups of threads for Java applications. A ThreadGroup can contain any number of threads, presumably related in some way such as who created them, what function they perform, or when they should be started and stopped. ThreadGroup provides benefit of assigning similar threads to same group.
       ThreadGroups can contain not only threads but also other ThreadGroups. The top-most thread group in a Java application is the thread group named "main". You can create threads and thread groups in the "main" group. You can also create threads and thread groups in subgroups of "main" and so on. The result is a root-like hierarchy of threads and thread groups.  Below example shows how to get all threads running under current threadGroup.

class EnumerateTest {
    void listCurrentThreads() {
 ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
 int numThreads;
 Thread listOfThreads[];

 numThreads = currentGroup.activeCount();
 listOfThreads = new Thread[numThreads];
 currentGroup.enumerate(listOfThreads);
 for (int i = 0; i < numThreads; i++) {
     System.out.println("Thread #" + i + " = " + listOfThreads[i].getName());
 }
    }
}
15. Create Producer and Consumer of data using synchronization ?
class DataHolder {
    private int seq;
    private boolean available = false;

    public synchronized int get() {
        while (available == false) {
     try {
           wait();
     } catch (InterruptedException e) {
     }
    }
        available = false;
        notify();
        return seq;
    }

    public synchronized void put(int value) {
 while (available == true) {
     try {
            wait();
     } catch (InterruptedException e) {
     }
    }
        seq = value;
        available = true;
        notify();
    }
}

16. Why Java locks \ object monitors are re-entrant? 
The Java runtime system allows a thread to re-acquire a monitor that it already holds because Java monitors are re-entrant. Re-entrant monitors are important because it eliminates the possibility of a thread deadlocking on a monitor that it already holds. 

Tips for Interview

1) Practice Good Nonverbal Communication
        It's about demonstrating confidence: standing straight, making eye contact and connecting with a good, firm handshake. That first impression can be a great beginning -- or quick ending -- to your interview.

 2) Dress for the Job or Company
     Today's casual dress codes do not give you permission to dress as "they" do when you interview. It is important to look professional and well-groomed. Whether you wear a suit or something less formal depends on the company culture and the position you are seeking. If possible, call to find out about the company dress code before the interview.

3) Listen
    From the very beginning of the interview, your interviewer is giving you information, either directly or indirectly. If you are not hearing it, you are missing a major opportunity. Good communication skills include listening and letting the person know you heard what he said. Observe your interviewer, and match that style and pace.

4) Don't Talk Too Much
     Telling the interviewer more than he needs to know could be a fatal mistake. When you have not prepared ahead of time, you may tend to ramble, sometimes talking yourself right out of the job. Prepare for the interview by reading through the job posting, matching your skills with the position's requirements and relating only that information.

 5) Don't Be Too Familiar
      The interview is a professional meeting to talk business. This is not about making a new friend. Your level of familiarity should mimic the interviewer's demeanour. It is important to bring energy and enthusiasm to the interview and to ask questions, but do not overstep your place as a candidate looking for a job.

6) Use Appropriate Technical Language
    It's a given that you should use technical language during the interview. Be aware of any inappropriate slang words or references to age, race, religion, politics or sexual orientation -- these topics could send you out the door very quickly.

 7) Show Attitude 
    Attitude plays a key role in your interview success. There is a fine balance between confidence, professionalism and modesty. Even if you're putting on a performance to demonstrate your ability, overconfidence is as bad, if not worse, as being too reserved.

 8)Take Care to Answer the Questions
    When an interviewer asks for an example of a time when you did something, he is seeking a sample of your past behaviour. If you fail to relate a specific example, you not only don't answer the question, but you also miss an opportunity to prove your ability and talk about your skills.

 9) Ask Questions
When asked if they have any questions, most candidates answer, "No." Wrong answer. It is extremely important to ask questions to demonstrate an interest in what goes on in the company. Asking questions also gives you the opportunity to find out if this is the right place for you. The best questions come from listening to what is asked during the interview and asking for additional information.

 10) Don't show Desperation
When you interview with the "please, please hire me" approach, you appear desperate and less confident. Maintain the three C's during the interview: cool, calm and confident. You know you can do the job; make sure the interviewer believes you can, too.

General Questions  
1. Tell us about yourself?
Keep your answer very simple and brief. Don't prolong by telling your family history and schooling. Be brief and focus more on your skills initiatives and adaptability.

2. Why should we hire you?
Because I have all the attributes that this role requires. Knowledge, experience, skills and abilities. You need to be confident while replying and no vague answers.

3. Why are you looking for a change? or Why do you want to leave your company?
Be positive while answering. You want to work with a company where you can make a long term career. Where you can use your skills and learn new skills. Be honest if there was any retrenchment in the previous company e.g. Our Department was consolidated or eliminated.

4. What are your strengths?
Your strengths should relate to the company and job opening. I have a proven track record as an achiever.Positive attitude, good sense of humour, good communication skills, dedicated, team player, willingness to walk the extramile to achieve excellence etc.   Your answer should highlight the qualities that will help you succeed in this particular job. (Back up each point with something specific). Give examples and quantify how your strengths benefited your previous employers. You should also demonstrate reliability, and the ability to stick with a difficult task yet change courses rapidly when required.

5. What are your weaknesses?
Never say you do not have any weak points. Try not to reveal your personal characteristics. I often get impatient with others sloppy work.
The best “weaknesses” are disguised as strengths, such as “I dislike not being challenged at work”. Another good approach is to mention a weakness that is irrelevant for the job or one that can be overcome with training. Try to keep these to one weakness, explaining why you think it is a weakness and what you are doing to overcome the problem – a well thought out strategy you have developed to deal with the issue will turn this potentially tricky question into a positive.
One common variation on this question is to ask about any problems or failures you’ve encountered in previous positions. In describing problems, pick ones you’ve solved and describe how you overcame it. Show yourself to be a good team player by crediting co-workers for all their contributions. To distance yourself from failure, pick one that occurred earlier in your career when you were still learning. Don’t blame others – simply explain how you analysed your mistake and learned from it.

6. What challenges did you face in your previous jobs?

Getting things planned and done on time within the budget. Quote any example that you have experienced.

7. How will you motivate your team?
Bottom line is do it show it and inspire. Involve all the members in the ongoing development and progress of the company. Communicate and interact with the team members. They want regular updates on their personal performance. Keep them updated.Celebrate individual and team performance. Catch people doing something right and focus on recognising excellent performance.Set challenging goals. Team will work hard to accomplish them. Believe in your people. Majority of them want to perform.Motivate employes for the next level. Consistent and transparent with the team. Let the members know why doing an assigned task is important to you the Organisation and them.Set the example for others to follow.

8. “What’s the worst problem you’ve ever faced?”
Here the interviewer is offering you the two ways to trip yourself up:
  • First of all, the question doesn’t confine itself to the workplace, so there is temptation to reveal a personal problem. Don’t! Restrict yourself to employment matters only.
  • Second, you are being asked to reveal a weakness or error again. You must have a good response ready for this question, one which shows how well you reacted when everything depended on it.
Always show a problem you have solved and concentrate your answer on the solution not the problem.

9. “How would you describe a typical day in your current job?”
You are eager to look good but don’t make the common mistake of exaggerating your current position. Mentioning some of the routine tasks in your day adds realism to your description and show that you don’t neglect important details such as paperwork. Put yourself in the interviewer’s place as your answer. When you’ve been doing a job for years it becomes second nature to you, and you must be aware of all the tasks you undertake. You should spend a few days making notes of your activities at work to regain an outsider’s perspective. Try to show that you make good use of your time, that you plan before you begin your work and that you review your achievements at the end of it

XML

What is the difference between SAX parser and DOM parser?
DOM parser - reads the whole XML document and returns a DOM tree representation of xml document. It provides a convenient way for reading, analyzing and manipulating XML files. It is not well suited for large xml files, as it always reads the whole file before processing.
SAX parser - works incrementally and generate events that are passed to the application. It does not generate data representation of xml content so some programming is required. However, it provides stream processing and partial processing which cannot be done alone by DOM parser.

What is XSL?
XSLT - a language for transforming XML documents
XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
XPath - a language for navigating in XML documents
XSL-FO - a language for formatting XML documents

Why Use a DTD?
A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.
A DTD can be declared inline inside an XML document, or as an external reference.
Seen from a DTD point of view, all XML documents (and HTML documents) are made up by the following building blocks:
  • Elements
  • Attributes
  • Entities
  • PCDATA
  • CDATA
Elements
Elements are the main building blocks of both XML and HTML documents.
Examples of HTML elements are "body" and "table". Examples of XML elements could be "note" and "message". Elements can contain text, other elements, or be empty. Examples of empty HTML elements are "hr", "br" and "img".
Examples:
<body>some text</body>
< message>some text</message>

Attributes
Attributes provide extra information about elements.
Attributes are always placed inside the opening tag of an element. Attributes always come in name/value pairs. The following "img" element has additional information about a source file:
<img src="computer.gif" />
The name of the element is "img". The name of the attribute is "src". The value of the attribute is "computer.gif". Since the element itself is empty it is closed by a " /".

Entities
Some characters have a special meaning in XML, like the less than sign (<) that defines the start of an XML tag.
Most of you know the HTML entity: "&nbsp;". This "no-breaking-space" entity is used in HTML to insert an extra space in a document. Entities are expanded when a document is parsed by an XML parser.
The following entities are predefined in XML:
Entity References
Character
&lt;
<
&gt;
>
&amp;
&
&quot;
"
&apos;
'

PCDATA
PCDATA means parsed character data.
Think of character data as the text found between the start tag and the end tag of an XML element.
PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded.
However, parsed character data should not contain any &, <, or > characters; these need to be represented by the &amp; &lt; and &gt; entities, respectively.

CDATA
CDATA means character data.
CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and entities will not be expanded.
With a DTD, each of your XML files can carry a description of its own format.

With a DTD, independent groups of people can agree to use a standard DTD for interchanging data.

Your application can use a standard DTD to verify that the data you receive from the outside world is valid.
You can also use a DTD to verify your own data.
Sample DTD
<!DOCTYPE TVSCHEDULE [
< !ELEMENT TVSCHEDULE (CHANNEL+)>
< !ELEMENT CHANNEL (BANNER,DAY+)>
< !ELEMENT BANNER (#PCDATA)>
< !ELEMENT DAY (DATE,(HOLIDAY|PROGRAMSLOT+)+)>
< !ELEMENT HOLIDAY (#PCDATA)>
< !ELEMENT DATE (#PCDATA)>
< !ELEMENT PROGRAMSLOT (TIME,TITLE,DESCRIPTION?)>
< !ELEMENT TIME (#PCDATA)>
< !ELEMENT TITLE (#PCDATA)>
< !ELEMENT DESCRIPTION (#PCDATA)>
< !ATTLIST TVSCHEDULE NAME CDATA #REQUIRED>
< !ATTLIST CHANNEL CHAN CDATA #REQUIRED>
< !ATTLIST PROGRAMSLOT VTR CDATA #IMPLIED>
< !ATTLIST TITLE RATING CDATA #IMPLIED>
< !ATTLIST TITLE LANGUAGE CDATA #IMPLIED>
]>

What is an XML Schema?
The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD.
An XML Schema:
•defines elements that can appear in a document
•defines attributes that can appear in a document
•defines which elements are child elements
•defines the order of child elements
•defines the number of child elements
•defines whether an element is empty or can include text
•defines data types for elements and attributes
•defines default and fixed values for elements and attributes

XML Schemas are the Successors of DTDs
We think that very soon XML Schemas will be used in most Web applications as a replacement for DTDs. Here are some reasons:
•XML Schemas are extensible to future additions
•XML Schemas are richer and more powerful than DTDs
•XML Schemas are written in XML
•XML Schemas support data types
•XML Schemas support namespaces

XML Schema Details:
This chapter will demonstrate how to write an XML Schema. You will also learn that a schema can be written in different ways.
An XML Document
Let's have a look at this XML document called "shiporder.xml":
< ?xml version="1.0" encoding="ISO-8859-1"?>
< shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
< orderperson>John Smith</orderperson>
< shipto>
< name>Ola Nordmann</name>
< address>Langgt 23</address>
< city>4000 Stavanger</city>
< country>Norway</country>
< /shipto>
< item>
< title>Empire Burlesque</title>
< note>Special Edition</note>
< quantity>1</quantity>
< price>10.90</price>
< /item>
< item>
< title>Hide your heart</title>
< quantity>1</quantity>
< price>9.90</price>
< /item>
< /shiporder>
The XML document above consists of a root element, "shiporder", that contains a required attribute called "orderid". The "shiporder" element contains three different child elements: "orderperson", "shipto" and "item". The "item" element appears twice, and it contains a "title", an optional "note" element, a "quantity", and a "price" element.
The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that this document should be validated against a schema. The line: xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE the schema resides (here it is in the same folder as "shiporder.xml").

Create an XML Schema
Now we want to create a schema for the XML document above.
We start by opening a new file that we will call "shiporder.xsd". To create the schema we could simply follow the structure in the XML document and define each element as we find it. We will start with the standard XML declaration followed by the xs:schema element that defines a schema:
< ?xml version="1.0" encoding="ISO-8859-1" ?>
< xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
< /xs:schema>
In the schema above we use the standard namespace (xs), and the URI associated with this namespace is the Schema language definition, which has the standard value of http://www.w3.org/2001/XMLSchema.
Next, we have to define the "shiporder" element. This element has an attribute and it contains other elements, therefore we consider it as a complex type. The child elements of the "shiporder" element is surrounded by a xs:sequence element that defines an ordered sequence of sub elements:
< xs:element name="shiporder">
< xs:complexType>
< xs:sequence>
...
< /xs:sequence>
< /xs:complexType>
< /xs:element>
Then we have to define the "orderperson" element as a simple type (because it does not contain any attributes or other elements). The type (xs:string) is prefixed with the namespace prefix associated with XML Schema that indicates a predefined schema data type:
< xs:element name="orderperson" type="xs:string"/
Next, we have to define two elements that are of the complex type: "shipto" and "item". We start by defining the "shipto" element:
< xs:element name="shipto">
< xs:complexType>
< xs:sequence>
< xs:element name="name" type="xs:string"/>
< xs:element name="address" type="xs:string"/>
< xs:element name="city" type="xs:string"/>
< xs:element name="country" type="xs:string"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>
With schemas we can define the number of possible occurrences for an element with the maxOccurs and minOccurs attributes. maxOccurs specifies the maximum number of occurrences for an element and minOccurs specifies the minimum number of occurrences for an element. The default value for both maxOccurs and minOccurs is 1!
Now we can define the "item" element. This element can appear multiple times inside a "shiporder" element. This is specified by setting the maxOccurs attribute of the "item" element to "unbounded" which means that there can be as many occurrences of the "item" element as the author wishes. Notice that the "note" element is optional. We have specified this by setting the minOccurs attribute to zero:

< xs:element name="item" maxOccurs="unbounded">
< xs:complexType>
< xs:sequence>
< xs:element name="title" type="xs:string"/>
< xs:element name="note" type="xs:string" minOccurs="0"/>
< xs:element name="quantity" type="xs:positiveInteger"/>
< xs:element name="price" type="xs:decimal"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>

We can now declare the attribute of the "shiporder" element. Since this is a required attribute we specify use="required".
Note: The attribute declarations must always come last:
< xs:attribute name="orderid" type="xs:string" use="required"/>
Here is the complete listing of the schema file called "shiporder.xsd":
< ?xml version="1.0" encoding="ISO-8859-1" ?>
< xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
< xs:element name="shiporder">
< xs:complexType>
< xs:sequence>
< xs:element name="orderperson" type="xs:string"/>
< xs:element name="shipto">
< xs:complexType>
< xs:sequence>
   < xs:element name="name" type="xs:string"/>
   < xs:element name="address" type="xs:string"/>
   < xs:element name="city" type="xs:string"/>
   < xs:element name="country" type="xs:string"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>
< xs:element name="item" maxOccurs="unbounded">
< xs:complexType>
< xs:sequence>
  < xs:element name="title" type="xs:string"/>
  < xs:element name="note" type="xs:string" minOccurs="0"/>
  < xs:element name="quantity" type="xs:positiveInteger"/>
  < xs:element name="price" type="xs:decimal"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>
< /xs:sequence>
  < xs:attribute name="orderid" type="xs:string" use="required"/>
< /xs:complexType>
< /xs:element>
< /xs:schema>

Divide the Schema
The previous design method is very simple, but can be difficult to read and maintain when documents are complex.
The next design method is based on defining all elements and attributes first, and then referring to them using the ref attribute.
Here is the new design of the schema file ("shiporder.xsd"):
< ?xml version="1.0" encoding="ISO-8859-1" ?>
< xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
< !-- definition of simple elements -->
< xs:element name="orderperson" type="xs:string"/>
< xs:element name="name" type="xs:string"/>
< xs:element name="address" type="xs:string"/>
< xs:element name="city" type="xs:string"/>
< xs:element name="country" type="xs:string"/>
< xs:element name="title" type="xs:string"/>
< xs:element name="note" type="xs:string"/>
< xs:element name="quantity" type="xs:positiveInteger"/>
< xs:element name="price" type="xs:decimal"/>
< !-- definition of attributes -->
< xs:attribute name="orderid" type="xs:string"/>
< !-- definition of complex elements -->
< xs:element name="shipto">
< xs:complexType>
< xs:sequence>
    < xs:element ref="name"/>
    < xs:element ref="address"/>
    < xs:element ref="city"/>
    < xs:element ref="country"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>
< xs:element name="item">
< xs:complexType>
< xs:sequence>
    < xs:element ref="title"/>
    < xs:element ref="note" minOccurs="0"/>
    < xs:element ref="quantity"/>
    < xs:element ref="price"/>
< /xs:sequence>
< /xs:complexType>
< /xs:element>
< xs:element name="shiporder">
< xs:complexType>
< xs:sequence>
< xs:element ref="orderperson"/>
< xs:element ref="shipto"/>
< xs:element ref="item" maxOccurs="unbounded"/>
< /xs:sequence>
    < xs:attribute ref="orderid" use="required"/>
< /xs:complexType>
< /xs:element>
< /xs:schema>

Using Named Types
The third design method defines classes or types, that enables us to reuse element definitions. This is done by naming the simpleTypes and complexTypes elements, and then point to them through the type attribute of the element.
Here is the third design of the schema file ("shiporder.xsd"):
< ?xml version="1.0" encoding="ISO-8859-1" ?>
< xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
< xs:simpleType name="stringtype">
< xs:restriction base="xs:string"/>
< /xs:simpleType>
< xs:simpleType name="inttype">
< xs:restriction base="xs:positiveInteger"/>
< /xs:simpleType>
< xs:simpleType name="dectype">
< xs:restriction base="xs:decimal"/>
< /xs:simpleType>
< xs:simpleType name="orderidtype">
< xs:restriction base="xs:string">
< xs:pattern value="[0-9]{6}"/>
< /xs:restriction>
< /xs:simpleType>
< xs:complexType name="shiptotype">
< xs:sequence>
    < xs:element name="name" type="stringtype"/>
    < xs:element name="address" type="stringtype"/>
    < xs:element name="city" type="stringtype"/>
    < xs:element name="country" type="stringtype"/>
< /xs:sequence>
< /xs:complexType>
< xs:complexType name="itemtype">
< xs:sequence>
    < xs:element name="title" type="stringtype"/>
    < xs:element name="note" type="stringtype" minOccurs="0"/>
    < xs:element name="quantity" type="inttype"/>
    < xs:element name="price" type="dectype"/>
< /xs:sequence>
< /xs:complexType>
< xs:complexType name="shipordertype">
< xs:sequence>
    < xs:element name="orderperson" type="stringtype"/>
    < xs:element name="shipto" type="shiptotype"/>
    < xs:element name="item" maxOccurs="unbounded" type="itemtype"/>
< /xs:sequence>
    < xs:attribute name="orderid" type="orderidtype" use="required"/>
< /xs:complexType>
< xs:element name="shiporder" type="shipordertype"/>
< /xs:schema>

The restriction element indicates that the datatype is derived from a W3C XML Schema namespace datatype. So, the following fragment means that the value of the element or attribute must be a string value:
  < xs:restriction base="xs:string">
The restriction element is more often used to apply restrictions to elements. Look at the following lines from the schema above:
< xs:simpleType name="orderidtype">
< xs:restriction base="xs:string">
< xs:pattern value="[0-9]{6}"/>
< /xs:restriction>
< /xs:simpleType>

This indicates that the value of the element or attribute must be a string, it must be exactly six characters in a row, and those characters must be a number from 0 to 9.

Difference in DTD and Schemas?
A DTD is:
 The XML Document Type Declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition or DTD.
  The DTD can point to an external subset containing markup declarations, or can contain the markup declarations directly in an internal subset, or can even do both.

A Schema is:
 XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents.

In summary, schemas are a richer and more powerful of describing information than what is possible with DTDs.

 Code Example of SAX XML Parsing ?
XML Parsing with SAX builder
// Get the instance of the SAX parser factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// Get SAX parser Instance
SAXParser saxParser = factory.newSAXParser();
// Define own handler
      DefaultHandler handler = new DefaultHandler() {
        boolean name = false;
        public void startElement(String uri, String localName,
            String qName, Attributes attributes)
            throws SAXException {
          if (qName.equalsIgnoreCase("EMAIL")) {
            name = true;
          }
        }
        public void characters(char ch[], int start, int length)
            throws SAXException {
          if (name) {
            System.out.println("Name: "
                + new String(ch, start, length));
            name = false;
          }
        }
      };
// parse the document
   saxParser.parse(fileName, handler);

Sample usage of above Sax Factory:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Main {
public static void main(String[] argv) throws Exception {
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     SaxHandler handler = new SaxHandler();
     parser.parse("sample.xml", handler);
}
}
class SaxHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
     if (qName.equals("order")) {
        String date = attrs.getValue("date");
        String number = attrs.getValue("number");
        System.out.println("Order #" + number + " date is '" + date + "'");
     }
   }
}