Saturday 25 August 2012

When should I use an interface instead of an abstract class?


Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.

Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts

Say a real estate builder is constructing an apartment with many flats.All the rooms in the flats have the same design,except the bedroom. The bedroom design is left for the ppl who would own the flats i.e; the bedRooms can be of different designs for different flats. 

I can achieve this through an abstract class like below:



public abstract class Flat
{
 //some properties


 public void livingRoom(){
    //some code
 }
 
 public void kitchen(){
    //some code
 }

 public abstract void bedRoom();

}

An implementation class would be as follows:
public class Flat101 extends Flat
{
        public void bedRoom() {
            System.out.println("This flat has a customized bedroom");
       }  

}

Suppose real estate builder is allowing you to customize all the rooms according to
your taste then you can go with interface.


interface Flat {
 // some properties

 public void livingRoom();

 public void kitchen();

 public void bedRoom();

}

public class Flat101 implements Flat {

 @Override
 public void livingRoom() {
  System.out.println("This flat has a customized living room");

 }

 @Override
 public void kitchen() {
  System.out.println("This flat has a customized kitchen");

 }

 @Override
 public void bedRoom() {
  System.out.println("This flat has a customized bedroom");

 }

}


One more thing is that interface supports multiple inheritance in Java i.e. you can implement more than one interface at a time or you can extend one class and implement one or more interfaces at the same time.

Interfaces can also be used as marker interface, interface with no methods in it.For example java.lang.Cloneable and java.io.Serializable.

Friday 24 August 2012

Compare two StringBuffer objects in Java

We can't use the equals method of the StringBuffer class for comparing two StringBuffer objects.The StringBuffer class equals method returns true only if both the comparing objects pointing to the same memory location.i.e. here comparing the memory address of the StringBuffer objects, not their contents.

Hence we have to convert the StringBuffer objects to String and use the String class equals method for comparing StringBuffer objects.String class equals method returns true if both the String objects occupies the same content.

See the example given below:


public class CompareStringBuffer {

	public static void main(String[] args) {

		StringBuffer sb1 = new StringBuffer("Java");
		StringBuffer sb2 = new StringBuffer("Java");

		System.out.println("sb1.equals(sb2)=" + sb1.equals(sb2));
		System.out.println("Is sb1 equals sb2?="
				+ sb1.toString().equals(sb2.toString()));

	}
}


The output is:


sb1.equals(sb2)=false
Is sb1 equals sb2?=true

New Java 7 Features: Using String in the Switch Statement

In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:


public class StringSwitchDemo {

 public static int getMonthNumber(String month) {

  int monthNumber = 0;

  if (month == null) {
   return monthNumber;
  }

  switch (month.toLowerCase()) {
  case "january":
   monthNumber = 1;
   break;
  case "february":
   monthNumber = 2;
   break;
  case "march":
   monthNumber = 3;
   break;
  case "april":
   monthNumber = 4;
   break;
  case "may":
   monthNumber = 5;
   break;
  case "june":
   monthNumber = 6;
   break;
  case "july":
   monthNumber = 7;
   break;
  case "august":
   monthNumber = 8;
   break;
  case "september":
   monthNumber = 9;
   break;
  case "october":
   monthNumber = 10;
   break;
  case "november":
   monthNumber = 11;
   break;
  case "december":
   monthNumber = 12;
   break;
  default:
   monthNumber = 0;
   break;
  }

  return monthNumber;
 }

 public static void main(String[] args) {

  String month = "August";

  int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month);
  System.out.println("The month number is:");
  if (returnedMonthNumber == 0) {
   System.out.println("Invalid month");
  } else {
   System.out.println(returnedMonthNumber);
  }
 }
}


The output is:


The month number is:
8

Sunday 12 August 2012

Comparing String with StringBuilder in Java


This example shows how to compare String object with a StringBuilder object using equals and contentEquals  methods of the String class.



public class ComapreStringWithStringBuilder {
 public static void main(String args[]) {

  String str = "Java";
  StringBuilder strBuild = new StringBuilder(str);

  /**
   * String.equals method can be used only for comparing
   * two Strings,so first convert StringBuilder to String
   * using toString method and then compare.
   **/
  if (str.equals(strBuild.toString())) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }

  /**
   * boolean contentEquals(CharSequence cs) Compares this
   * string to the specified CharSequence. The result is
   * true if and only if this String represents the same
   * sequence of char values as the specified
   * sequence.
   **/

  if (str.contentEquals(strBuild)) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuilder contains same data
String and StringBuilder contains same data

Comparing String with StringBuffer in Java


This example shows how to compare String object with a StringBuffer object using equals and contentEquals  methods of the String class.


public class ComapreStringWithStringBuffer {
 public static void main(String args[]) {

  String str = "Java";
  StringBuffer strBuff = new StringBuffer(str);

  /**
   * String.equals method can be used only for comparing two
   * Strings,so first convert StringBuffer to String using
   * toString method and then compare.
   **/
  if (str.equals(strBuff.toString())) {
   System.out.println("String and StringBuffer contains" +
     " same data");
  }

  /**
   * boolean contentEquals(StringBuffer sb) - Compares this
   * string to the specified StringBuffer. The result is true
   * if and only if this String represents the same sequence
   * of characters as the specified StringBuffer.
   **/
  if (str.contentEquals(strBuff)) {
   System.out.println("String and StringBuffer contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuffer contains same data
String and StringBuffer contains same data