Monday, 27 July 2015

Initilize final variable using constructer

package com.swain.sitansu;

public class Test {

private final String TEST;

public Test(String TEST) {
this.TEST = "Hello";//Initilize final variable using constructer
}

public static void main(String[] args) {
System.out.println(new Test("hello").TEST);
}

}

Meaning public static void main(String args[])


1. public: It is a keyword and denotes that any other class (JVM) can call the main() method without any restrictions.
2. static: It is a keyword and denotes that any other class (JVM) can call the main() method without the help of an object
3. void: It is a keyword and denotes that the main() method does not return a value.
4. main(): It is the name of the method.
5. String args[]: The parameter is a String array by name argsThe string array is used to access command-line arguments.
  
JVM is in another context area. To call the main(), the JVM requires an object. When the JVM has not entered into the program, how it can create an object or get an object. To overcome this, allow the JVM to access the main() without object just by declaring static. Once the JVM enters, it can create hundreds of objects.
  
Whether you pass right now command-line arguments or not, you must have the string array as parameter as it is the part of syntax.

Any word is missed in the above statement, the program compiles, but does not execute.

EXAMPLE : 

class First
    {
//  A java program will start from here.

        public static void main(String args[]) 
            {
              System.out.println("  Welcome to Javamadelife...!!! ");
            }

 }

Saturday, 11 July 2015

Sorting in Descending order in Java.

We are using Collections.reverseOrder() method along with Collections.sort() in order to sort the list in decreasing order. In the below example we have used the following statement for sorting in reverse order.
Collections.sort(arraylist, Collections.reverseOrder());
However the reverse order sorting can also be done as following – This way the list will be sorted in ascending order first and then it will be reversed.
Collections.sort(list);
Collections.reverse(list);
Complete example:
package com.swain.sitansu;

import java.util.ArrayList;
import java.util.Collections;

public class ArraylistDesendingSort {

public static void main(String[] args) {

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("AA");
arrayList.add("BB");
arrayList.add("ZZ");
arrayList.add("FF");

/* Unsorted list */
System.out.println("Before Sorting:");
for (String str : arrayList) {
System.out.println(str);
}

Collections.sort(arrayList, Collections.reverseOrder());

/* Sorted list with reverse order */
System.out.println("ArrayList in descending order:");
for (String str1 : arrayList) {

System.out.println(str1);
}

}
}

Output:

Before Sorting:
AA
BB
ZZ
FF
ArrayList in descending order:
ZZ
FF
BB
AA


Thursday, 9 July 2015

What is Marker interfaces in Java and why required

Why Marker or Tag interface do in Java

1) Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.

marker interfaces java example tutorialThis is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked "Why this indication can not be done using a flag inside a class?” this make sense right? Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java.

Where Should I use Marker interface in Java

Apart from using built in marker interface for making a class Serializable or Clonnable. One can also develop his own marker interface. Marker interface is a good way to classify code. You can create marker interface to logically divide your code and if you have your own tool than you can perform some pre-processing operation on those classes. Particularly useful for developing API and framework like Spring or Struts.
After introduction of Annotation on Java5, Annotation is better choice than marker interface and JUnit is a perfect example of using Annotation e.g. @Test for specifying a Test Class. Same can also be achieved by using Test marker interface.


Another use of marker interface in Java

One more use of marker interface in Java can be commenting. a marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Marker interface can also help code coverage or code review tool to find bugs based on specified behavior of markerinterfaces.
Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.


Usage of hashCode() and equals()

The hashCode() and equals() methods have been defined in Object class which is parent class for java objects. For this reason, all java objects inherit a default implementation of these methods.


Usage of hashCode() and equals()

hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.

Overriding the default behavior

Everything works fine until you do not override any of these methods in your classes. But, sometimes application needs to change the default behavior of some objects.
Lets take an example where your application has Employee object. Lets create a minimal possible structure of Employee class::
public class Employee
{
    private Integer id;
    private String firstname;
    private String lastName;
    private String department;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
}
Above Employee class has some very basic attributes and there accessor methods. Now consider a simple situation where you need to compare two employee objects.
public class EqualsTest {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        e1.setId(100);
        e2.setId(100);
        //Prints false in console
        System.out.println(e1.equals(e2));
    }
}
No prize for guessing. Above method will print “false“. But, is it really correct after knowing that both objects represent same employee. In a real time application, this must return true.

After override  equals() method in Employee class :


public class Employee {

private Integer id;
private String firstname;
private String lastName;
private String department;

public Integer getId() {

return id;
}

public void setId(Integer id) {

this.id = id;
}

public String getFirstname() {

return firstname;
}

public void setFirstname(String firstname) {

this.firstname = firstname;
}

public String getLastName() {

return lastName;
}

public void setLastName(String lastName) {

this.lastName = lastName;
}

public String getDepartment() {

return department;
}

public void setDepartment(String department) {

this.department = department;
}


@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 (department == null) {
if (other.department != null)
return false;
} else if (!department.equals(other.department))
return false;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
}


import java.util.HashSet;

import java.util.Set;

public class HashCodeAndEqualMethod {


private final String importantField;

private final String anotherField;

public HashCodeAndEqualMethod(final String equalField, final String anotherField) {

this.importantField = equalField;
this.anotherField = anotherField;
}

public String getEqualField() {

return importantField;
}

public String getAnotherField() {

return anotherField;
}

public static void main(String[] args) {

Employee e1 = new Employee();
Employee e2 = new Employee();

e1.setId(100);

e2.setId(100);

// Prints false in console if you are not override equals method in Employee class.

System.out.println(e1.equals(e2));

Set<Employee> employees = new HashSet<Employee>();

employees.add(e1);
employees.add(e2);

// Prints two objects if you are not override equals  and hashCode()  method in Employee class.

System.out.println(employees);
}

}