Thursday, July 23, 2015

Validating an XML with DTD in Java

      In this example i will show you how to validate an incoming xml . To validate an XML you have two options . One is to use XSD and second one is to use DTD's . I will explain you about XSD and why its is better compared to DTD's in a different post . In this post i will try to explain you about DTD's  and how will we validate a XML document.

 DTD's are non-xml documents which defines characteristics of an incoming xml . DTD's can be a separate document or can be included in the same XML . Lets look at a sample DTD defined XML

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE students [
   <!ELEMENT students (student+)><!-- any Number of students -->
   <!ELEMENT student (studentid, name)><!-- student can have only two elements -->
   <!ATTLIST student department CDATA #REQUIRED> <!-- department is required -->
   <!ELEMENT studentid (#PCDATA)><!-- studentId is parsable String -->
   <!ELEMENT name (#PCDATA)>
  <student department="computers">
  <student> <!--  Gives a parser Exception as department is required. -->

   The DOCTYPE element is the DTD , It defines how the XML is expected to be . Lets look closely at what  this DTD means

1. The root element is students.
2. Students tag can contain one or many elements of student type. (+ indicates one or more , * indicates zero or more)
3. Student type contains two elements studentid and name.
4. Department is Required.
5. StudentId and Name should be a parsable Data .  PCDATA means parsed character data

More details on writing DTD's is found here .

Lets look how we write a java code to validate the XML . While doing a domBuilder parse , we have to set the factory to be validating true. In case you have to handle the validation errors with custom logic then you have to use the setErrorHandler method (of builder)  and pass a custom ErrorHandler Class

public class DTDValidator {

 public static void main(String[] args) throws SAXException,ParserConfigurationException,IOException {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("src\\com\\learning\\xml\\student.xml");
        //builder.setErrorHandler(<Custom Implementation Of Error Handler );
  System.out.println("Successfully Parsed");

Tuesday, July 21, 2015


   I will take this blog post to point you what all are the key differences between an XML and HTML  and what all are the rules driving both of them .

1. XML is case sensitive while HTML is not.
    <BR> and <br> are two different tags for xml but html consider both as one.

2. Close tags are not mandatory for HTML .
    HTML parser is not so strict and it will not complain you if you have missed a closing tag. It understands from the context. However XML is strict with respect to closing tags.

3. An Attribute without a value is valid for HTML  but not for an XML
   <table name="table1" visible>  is a valid HTML but not a valid XML . To be a valid xml this should be  <table name="table1" visible="true">

4. Attribute values should be given inside a "double quote" for XML, However HTML doesnt stick to this rule <table name="table1" visible=true> is a valid HTML.

Hope it helps . Happy coding :) 

How to create a drop shadow effect in android

          Recently on working on a project, My client requested me to add a shadow to an custom action bar layout.This was something i have never done before  so i decided to look for it. With my experience in CSS i was expecting a drop shadow to be enabled. But interestingly android doesnt have such a feature.
  But you can do a workaround. Here is how i do it.

1. Define a custom drawable  named it as shadow_drawable.xml ( inside res/drawable folder)

<shape xmlns:android="">

<gradient android:startColor="@color/background_material_dark"

And yes here is your shadow drawable. You could use it in your app always ( May be in another app too) if you can copy paste  :)

Lets look at how do we implement it.
I added it to a linear layout to have a drop shadow. So under the layout i added the following code.

<View     android:layout_below="@+id/some_layout_item"

  And thats it. Your drop shadow is now ready .  Adding a demo picture .

Happy coding  :)

Monday, July 20, 2015

ArrayList vs Vector in java

Most of the developers are still not sure if they have to use a Vector or an ArrayList. As from my experience we cannot state a general statement that option A is better than option B. But here i outline some important things to check before choosing either of them.

1 . Vector is synchronized , While ArrayList is not. Which means that all operations done on a Vector is thread safe by default and you don't have to provide any explicit synchronization . So i would prefer Vector over ArrayList when i am working with threads. But this has a negetive side . Vector has synchronization code which makes it bit less performing in normal cases where thread safety is not a concern
2 . The size of a ArrayList increases 50% , While Vector it doubles as the data goes out of bounds . You have to understand the pattern in which the data grows to consider which is better. Remember Vector has an option to set the increment value .

3. Retrieving elements from a particular position is of the O(1) , in both ArrayList and Vector . However both suffers a penalty of O(n) to insert an element to the middle mainly because one have to shift all n-i element to insert an element at ith Position.

Hope you will look into these points from now on .  Happy coding :)

Wednesday, July 15, 2015

Inner Classes-2(Local Classes)

         In java you could define a class inside a code block/Method. This kind of classes are known as Local classes .       Lets look at an Example :
public class HelloWorld{
    public int studentId;
 public  void method(){
    int loop=0;
    final int CONSTANT=10;
    System.out.println("Main Execution begins , Student id is :" +studentId);
    class  LocalClass{
     public void printStudentId(){
      System.out.println("Inside Inner class, Student id is :" +studentId); // Remember that if studentId is also present in local class
                                                                         // this will print the local class variable student id , in such cases  use Student.this.studentId
            System.out.println("Inside Inner class, CONSTANT is :" +CONSTANT); // only final local variables can be accessed.
             System.out.println("Inside Inner class, loop is :" +loop); // errors out , loop is not final
   LocalClass local = new LocalClass();
   public static void main(String args[]){
       HelloWorld hello = new HelloWorld();

Some points to remember:
 1. A local class can access variables inside outer class (instance variables of outer class)
 2. A local class cannot be instatiated/visible outside the code block/method.
 3. A local class cannot access non final local variables as they both have different scopes , Local variables get destroyed on method exit . But final local variables are accessible inside local classes. Final variables are copied to the code stack internally before the inner class instance is created and can be used inside.

Tuesday, July 14, 2015

Java Inner Classes -1 (Member classes)

In Java we can define nested classes . Nested classes only make sense if the class which is nested is only used by outer class. A class which is defined inside another class is known as Inner class.  If you look at JDK code, we could see nested classes present in HashMap code.  This nested class is Map.Entry .  As we all know Entry class only make sense to a Hashmap class .
  Now lets look at different ways of doing it :
  1. Member class :
      A member class acts as a non static member of outer class.  Lets look at an example :

class Outer{ 
      class Inner{

  How do we use this inner class ?  Lets look at that now :
// Working example

 public Class OuterClass {
private int data = 20;
class InnerClass {
 public void printMessage(){
    System.out.println(" Data is :" +data);
public static void main(String args[]){
 OuterClass out = new OuterClass();
 OuterClass.InnerClass in = InnerClass(); // Look for syntax

Some good points :

1. Inner class can access both private and public members of outer class .
2. Inner class cannot be instatiated alone. it is always attached to an outer class instance.
3. Java compiler creates two class files, One  OuterClass.class and second one OuterClass#InnerClass class file for the inner class.

Hello Lamda

                                       From the beginning of java 8 release, We are hearing about something called lamda . Here i try to explain all that one should know about this mysterious thing called lamda which is one of the feature introduced in Java 8. For a functional programmer ( who uses different programming languages than java) , lamda expressions is something which they can relate to . A traditional object oriented java programmer will not expect such a feature to get introduced in Java. I will try to explain how lamda differs from object orientedness of java.
    Lets look at a case where we have to execute a piece of code multiple times . An example may be an ActionListener on a button click

// Defined using Inner classes

button.setOnAction(new EventHandler<ActionEvent>() {

   public void handle(ActionEvent event) {

      System.out.println("Thanks for clicking!");



     Here , The handle method is executed multiple times on each button click . This is an example of a code which is executed multiple times in an application . Same can be applied to a
Comparator which is passed to a Collections.sort method for sorting.  The compare method inside the defined comparator is called multiple times.Uptill now these kind of codes were passed as an object where a method is defined inside it . From now onwards we could pass it as a block of code, Which is to be executed .  This is more or less what lamda expressions are

  Lets look at it in detail.  Let me take the example of a String Comparator which does the comparison by length .  I will write the old way of doing it

   ArrayList<Strings> sortingNeeded = new ArrayList<String>();




   Collections.sort(sortingNeeded, LengthComparator);


   // LengthComparator code is defined as :


   class LengthComparator implements Comparator<String> {

   public int compare(String first, String second) {

      return, second.length());



Lets now do it the Lamda way :

    ArrayList<Strings> sortingNeeded = new ArrayList<String>();



   // The block of code which needed to be executed here  is :, second.length()) , 
//But since java is strongly typed, We have to provide the type of arguments as 
// well, So the code comes to be :


   Collections.sort(sortingNeeded, (String first, String second)->, second.length()) );

Whaat ?  isnt ?   Yes ,You have just seen one form of lambda expressions in Java: "parameters, the -> arrow, and an expression". . If the code carries out a computation that doesn’t fit in a single expression, write it exactly like you would have written a method: enclosed in {} and with explicit return statements. For example,

(String first, String second) -> {

   if (first.length() < second.length()) return -1;

   else if (first.length() > second.length()) return 1;

   else return 0;


Now you may be asking what if we have return  values , how do we specify the type of the return value . The answer is that you can never provide the return type , its always inferred from the context.

 Also if the type of the arguments can be inferred , You could avoid that too ,

  Comparator<String> comp = ( first,  second)->, second.length());

    here the type of first and second can be inferred from the context that it will be strings as the lamda function is assigned to a variable which is of the type string comparator. Hence we can avoid the type.

What if there is no argument type?
 yes , ()-> System.out.println("Hello")  is a valid  lamda expression .

 You are not at all expected to be clear about lamda expressions with this post . There will be a lot of questions , Where is this code executed ? What if an exception occurs  ? Where exactly do you use the lamda expressions . All this and much more on coming topics. Stay tuned.  Happy Coding :)