Thursday, June 17, 2010

Java Interview Question 5

<< Previous                                                                                    Next  >>

Java Interview Question 14:
What's the difference between == and equals method?

The “==” operator compares two object references to check whether they refer to the same instances or not. That is, they looks at the actually memory address to see if it is actually the same object. Whereas the equals method compares the contents of the objects.

For example, consider the following

String str1 = new String("abcd");
String str2 = new String("abcd");

The line of code create a new String object, with a value of "abcd", and assign it to a reference variable str1 and str2.

Now, if you use the "equals()" method to check for their equivalence as

if(str1.equals(str2))
     System.out.println("str1.equals(str2) is TRUE");
else
     System.out.println("str1.equals(str2) is FALSE");

The output will be TRUE as the 'equals()' method compares the contents of the objects.

Lets check the '==' operator..

if(str1==str2)
    System.out.printlln("str1==str2 is TRUE");
else
    System.out.println("str1==str2 is FALSE");

The output will be FALSE because both str1and str2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.

Java Interview Question 15:
What is inheritance?

In OOPs, the concept of inheritance provides the idea of reusability. That is, when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. We can add additional features to the derived class. The derived class will have combined features of both the classes. In other words, inheritance can be defined as the capability of a class to use the properties and methods of another class while adding its own functionality. Java uses the extends keyword to set the relationship between a base class (also a superclass or a parent class) and a derived class (also a subclass, extended class, or child class). Only properties with access modifier public and protected can be accessed in child class. Constructors are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. Each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

The syntax for creating a subclass.

class A extends B{

             // new fields and methods would go here
}

Here, class A is the subclass and B is the superclass
<< Previous                                                                              Next  >>

No comments: