Monday, 11 April 2016

Difference between == and equals() method in Java - String Object

What is difference between == and equals() method for comparing Objects in Java is one of the classical Interview Questions which appears now and then on many interviews. This question is mostly asked in conjunction with String because comparing String using == and equals() method returns different results. I have often seen as along with other popular String question e.g. StringBuffer vs StringBuilder, Why String is final etc. Java is a pure object oriented language and every object has one state and location in the memory and equals () and == are related with the state and location of the object, now in this article will try to understand this concept and difference between == and equals method in Java.


What is equals method and == operator in Java
equals vs == or eqaulity operator in Java
Both equals() method and == operator is used to compare two objects in Java. == is an operator and equals() is method. But == operator compare reference or memory location of objects in heap, whether they point to same location or not .whenever we create any object using the operator new it will create new memory location for that object. So we use == operator to check memory location or address of two objects are same or not. And when we talk about equals() method main purpose is two compare the state of two objects or contents of the object. But there is one relation between this two isdefault implementation of equals() method  work like == means it will check the memory reference of the object if they point to same location then two objects are equals and it is defined in  Object class .as we know java.lang.Object class is parent for every other object so default  implementation is common for every object but if we want to override the method and want to give own implementation  for checking the equality for two objects we can do, and most of the Java  classes have their own implementation for equals method where they check the contents of the object .

For example  java.lang.String class override the equals() and hashcode method and in overridden method it will check that two string contains same value or character if yes then they are equals other wise not equal.

Difference between == and equals method in Java
Now we know what is equals method, how it works and What is equality operator (==) and How it compare objects, its time to compare them. Here is some worth noting difference between equals() method and == operator in Java:

·          First difference between them is, equals() is a method defined inside the java.lang.Object class and == is one type of operator and you can compare both primitive and objects using equality operator in Java.

·          Second difference between equals and == operator is that, == is used to check reference or memory address of the objects whether they point to same location or not, and equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer its there numeric values etc. You can define your own equals method for domain object as per business rules e.g. two Employes objects are equal if there EmployeeId is same.

·          Third difference between equals and == operator is that, You can not change the behavior of == operator but we can override equals() method and define the criteria for the objects equality.

Let clear all these differences between equals and == operator using one Java example :

String s1=new String("hello");
String s2=new String("hello");

Here we have created two string s1 and s2 now will use == and equals () method to compare these two String to check whetherthey are equal or not.

First we use equality operator  == for comparison  which only returns true if both reference variable are pointing to same object.

if(s1==s2) {
     System.out.printlln("s1==s2 is TRUE");
} else{
     System.out.println("s1==s2 is FALSE");
}

Output of this comparison is FALSE because we have created two objects which have different location in heap so == compare their reference or address location and return false. Now if we use equals method to check their equivalence what will be the output


if(s1.equals(s2)) {
      System.out.println("s1.equals(s2) is TRUE");
} else { 
      System.out.println("s1.equals(s2) is FALSE");
}

Output of this comparison is TRUE because java.lang.String class has already overridden the equals() method of Object class and check that contents are same or not because both have same value hello so they are equal according to String classequals() method .

Point to remember:
If you have not overridden equals() method in  a user defined object,  it will only compare the reference or memory address, as defined in default equals() method of java.lang.Object class and return true only if both reference variable points to same object. So in a user defined class, both equals() and == operator behave similarly but that may not be logically correct and that’s why we should always define the equivalence criteria for custom or domain objects.

That’s all on difference between equals() method and == operator in Java. Both can compare objects for equality but equals()is used for logical and business logic comparison while == mostly for object reference comparison in Java.

Other Java articles and Interview questions from java 67

Hashtable vs HashMap in Java



TAGS :     SQL          SQL TUTORIAL           SQL STUDY ONLINE                 GNIIT HELP
Read More »

What is difference between View and Materialized View in Database or SQL?

Difference between View and Materialized view is one of the popular SQL interview question, much like truncate vs deletecorrelated vs noncorrelated subquery or primary key vs unique key This is one of the classic question which keeps appearing in SQL interview now and then and you simply can’t afford not to learn about them. Doesn’t matter if you are a programmer, developer or DBA, this SQL questions is common to all. Views are concept which not every programmer familiar of, it simply not in the category of CRUD operation or database transactions or SELECT query, its little advanced concept for average programmer. Views allows a level of separation than original table in terms of access rights but it always fetch updated data. Let’s see What is View in database, What is materialized View and difference between view and materialized view in database.

What is View in database
What is difference between View vs Materialized View in database or SQL?Views are logical virtual table created by “select query” but the result is not stored anywhere in the disk and every time we need to fire the query when we need data, so always we get updated or latest data from original tables. Performance of the view depend upon our select query. If we want to improve the performance of view we should avoid to use join statement in our query or if we need multiple joins between table always try to use index based column for joining as we know index based columns are faster than non index based column. View allow to store definition of the query in the database itself.

What is Materialized View in database
Materialized views are also logical view of our data driven by select query but the result of the query will get stored in the table or disk, also definition of the query will also store in the database .When we see the performance of Materialized view it is better than normal View because the data of materialized view will stored in table and table may be indexed so faster for joining also joining is done at the time of materialized views refresh time so no need to every time fire join statement as in case of view.

Difference between View vs Materialized View in database
Based upon on our understanding of View and Materialized View, Let’s see, some short difference between them :

1) First difference between View and materialized view is that, In Views query result is not stored in the disk or database but Materialized view allow to store query result in disk or table.

2) Another difference between View vs materialized view is that, when we create view using any table,  rowid of view is same as original table but in case of Materialized view rowid is different.

3) One more difference between View and materialized view in database is that, In case of View we always get latest data but in case of Materialized view we need to refresh the view for getting latest data.

4) Performance of View is less than Materialized view.

5) This is continuation of first difference between View and Materialized View, In case of view its only the logical view of table no separate copy of table but in case of Materialized view we get physically separate copy of table

6) Last difference between View vs Materialized View is that, In case of Materialized view we need extra trigger or some automatic method so that we can keep MV refreshed, this is not required for views in database.

When to Use View vs Materialized View in SQL
Mostly in application we use views because they are more feasible,  only logical representation of table data no extra space needed. We easily get replica of data and we can perform our operation on that data without affecting actual table data but when we see performance which is crucial for large application they use materialized view where Query Response time matters so Materialized views are used mostly with data ware housing or business intelligence application.

That’s all on difference between View and materialized View in database or SQL. I suggest always prepare this question in good detail and if you can get some hands on practice like creating Views, getting data from Views then try that as well.

Other SQL Interview Question articles for you


TAGS :     SQL          SQL TUTORIAL           SQL STUDY ONLINE
Read More »

Java Enum Example with Constructor

Java Enum with Constructor
Java Enum can have Constructor to pass data while creating Enum constants. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass action to each Enum instance e.g. GREEN is associate with go, RED is associate with stop and ORANGE is associated with slow down. You can also provide one or more constructor to your Enum as it also support constructor overloading. Just note that modifierpublic and protected are not allowed to Enum constructor, it will result in compile time error. By the way We have covered see some enum examples in our previous posts e.g. Java Enum Switch Example, Java Enum valueOf Example and Enum to String Exmaple in Java, which is good to learn enum in Java.


Java Enum with Constructor Example
Java Enum with constructor example tutorialhere is complete code example of using Constructor with Java Enum. Here our TrafficLight constructor accept an String argument which is saved to action field which is later accessed by getter method getAction().

/**
 * Java enum with constructor for example.
 * Constructor accept one String argument action
 */

public enum TrafficSignal{
    //this will call enum constructor with one String argument
    RED("wait"), GREEN("go"), ORANGE("slow down");
  
    private String action;
  
    public String getAction(){
        return this.action;
    }
  
    // enum constructor - can not be public or protected
    TrafficSignal(String action){
        this.action = action;
    }
}

/**
 *
 * Java Enum example with constructor. Java Enum can have constructor but can not
 * be public or protected
 *
 * @author http://java67.blogspot.com
 */

public class EnumConstructorExample{

    public static void main(String args[]) {
      
      //let's print name of each enum and there action - Enum values() examples
      TrafficSignal[] signals = TrafficSignal.values();
    
      for(TrafficSignal signal : signals){
          //Java name example - Java getter method example
          System.out.println("name : " + signal.name() + " action: " + signal.getAction());
      } 
    
    } 
  
}
This was our Java Enum example with Constructor. Now you know that Enum can  have constructor in Java which can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor can not be protected or public, it can either have private or default modifier only.

Other Java 5 tutorial you may like

Java 5 new features list



TAGS :     JAVA          JAVA TUTORIAL           JAVA STUDY ONLINE
Read More »

Java ArrayList Examples For Programmers

ArrayList Example in Java
In this Java ArrayList Example we will see how to add elements in ArrayList, how to remove elements from ArrayList, ArrayList contains Example and several other ArrayList functions which we use daily. ArrayList is one of the most popular class from Java Collection framework along with HashSet and HashMap and a good understanding of ArrayList class and methods is imperative for Java developers. ArrayList is an implementation ofList Collection which is ordered and allow duplicates. ArrayList is alos index based and provides constant time performance for common methods e.g. get().Apart from very popular among Java programmers, ArrayList is also a very popular interview topic. Questions like Difference between Vector and ArrayList and LinkedList vs ArrayList is hugely popular on various Java interview specially with 2 to 3 years of experience. Along with Vector this is one of the first collection class many Java programmer use. By the way e have already seen some ArrayList tutorial e.g. ArrayList sorting example,  converting Array to ArrayList looping through ArrayList which is good to understand ArrayList in Java.

Java ArrayList Examples
Java ArrayList Example contains empty size removeIn this section we will see actual code example of various ArrayList functionality e.g. add, remove, contains,clear, size, isEmpty etc.


  
import java.util.ArrayList;
import java.util.Arrays;

/**
 *
 * Java ArrayList Examples - list of frequently used examples in ArrayList e.g. adding 
 * elements, removing elements, contains examples etc
 * @author
 */

public class ArrayListTest {

    public static void main(String args[]) {
      
        //How to create ArrayList in Java - example
        ArrayList<String> list = new ArrayList<String>();
      
        //Java ArrayList add Examples
        list.add("Apple");
        list.add("Google");
        list.add("Samsung");
        list.add("Microsoft");
    
        //Java ArrayList contains Example, equals method is used to check if
        //ArrayList contains an object or not
        System.out.println("Does list contains Apple :" + list.contains("Apple"));
        System.out.println("Does list contains Verizon :" + list.contains("Verizon"));
      
        //Java ArrayList Example - size
        System.out.println("Size of ArrayList is : " + list.size());
      
        //Java ArrayList Example - replacing an object
        System.out.println("list before updating : " + list);
        list.set(3, "Bank of America");
        System.out.println("list after update : " + list);
      
        //Java ArrayList Example - checking if ArrayList is empty
        System.out.println("Does this ArrayList is empty : " + list.isEmpty());
      
        //Java ArrayList Example - removing an Object from ArrayList
        System.out.println("ArrayList before removing element : " + list);
        list.remove(3); //removing fourth object in ArrayList
        System.out.println("ArrayList after removing element : " + list);
      
       //Java ArrayList Example - finding index of Object in List
        System.out.println("What is index of Apple in this list : " + list.indexOf("Apple"));
      
        //Java ArrayList Example - converting List to Array
        String[] array = list.toArray(new String[]{});
        System.out.println("Array from ArrayList : " + Arrays.toString(array));
      
        //Java ArrayList Example : removing all elements from ArrayList
        list.clear();
        System.out.println("Size of ArrayList after clear : " + list.size());
    } 
  
}

Output:
Does list contains Apple :true
Does list contains Verizon :false
Size of ArrayList is : 4
list before updating : [Apple, Google, Samsung, Microsoft]
list after update : [Apple, Google, Samsung, Bank of America]
Does this ArrayList is empty : false
ArrayList before removing element : [Apple, Google, Samsung, Bank of America]
ArrayList after removing element : [Apple, Google, Samsung]
What is index of Apple in this list : 0
Array from ArrayList : [Apple, Google, Samsung]
Size of ArrayList after clear : 0

These were some frequently used examples of ArrayList in Java. We have seen ArrayList contains example which used equals method to check if an Object is present in ArrayList or not. We have also see how to add, remove and modify contents of ArrayList etc.

Other Java Collection tutorial and Interview Questions



Read More »