22 May, 2014

What is the difference between "==" and .equals() Method ?

While programming it is a quite common condition in which we have to equate two objects. That is to identify that two objects are equal or not.
To find out equality Java provides us two options
§ By Using Operator ==
§ By Using Method equals
To understand which should be used when, let us think as coders of Java language would have. Assume that we are going to write the functionality for the operator "==".
Our aim is to identify that is L.H.S equal to R.H.S or not. Another target that we need to achieve is that this operator should work on all kinds of objects, including those which are not even defined today.
How can we equate two objects, whose classes are not even written till date? There has to be a factor on which we can decide if the objects are equal. There is one, and only one such scenario in which we can be sure that L.H.S is equal to R.H.S, and that is when both the objects are placed on same memory location.
And this is exactly what Java guys did. They wrote the code for this operator to match the references (Memory location) on both the sides. If they refer to same memory location, they are equal else not.
If == operator solves our purpose, then what is the use of equals method? In fact, if you check the class Object in java, equals method does nothing more than using == operator.

 public boolean equals(Object obj) {   
        return (this == obj)
Calling equals method is only adding a method call.
Consider a scenario, you have two objects of same class, having exactly same values of member variables but since they are present on different memory locations, == operator will return 'false' for them.
What will equals method return? (If you said 'true', wait my tiger)
I will simply say that when equals method is called, its definition will be executed.
Where is the definition present? It is in the Object Class. So the equals method will still return 'false' as it is simply calling == operator.
So what is the solution, if we want to equate two objects based on the values inside,and not on the basis of its memory location?
Remember the concept of method overriding? It is the technique of hiding method definition in parent class by providing a new method definition with same signature in child class. So making use of method overriding we will give the definition of equals method, and it will behave according to this new definition. One fine example can be seen in String class
The equals method here, equates two objects on the basis of there values and ignores the memory location they are on.
So for String class
String first = new String ("test"); // creates a new string object with value "test"
String second= new String ("test");// creates another string object with value "test" at different memory location
first.equals(second) // returns true as values are compared
first==second// returns false as memory location is compared.
This was good for String class, only because  String defines its own equals method.  Point to be noted here is for any class which does not defines equals method of its own, the method definition will still be available (From top most parent class i.e. Object). And for such classes equals method will behave exactly similar to == operator.

What is the difference between primitive and Wrapper Classes?

  1. Primitives are not objects
  2. We cannot perform any function on primitives
  3. Primitives are stored on Stack, Wrapper Objects are stored on heap
  4. primitives store value where as objects store a reference to actual objects. (References are not present for primitives)
  5. since primitives are stored on stack, the will be garbage collected once their visibility is over. Objects on other hand are present on heap, so their Garbage collection decision making is a bit complex.
  6. Wrapper Class Integer create final objects where as the value of int is modifiable.

what is the difference between CharSequence and a String?

CharSequence is an interface present in package java.lang. A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character. However, in particular, CharSequence does not make any guarantees about whether the sequence is mutable or not. So, you can have an immutable implementing class, like String or mutable ones, like StringBuilder and StringBuffer.
In addition, CharSequence does not refine the general purpose implementations of the equals() or hashCode() methods, so there is no guarantee that objects of different classes implementing CharSequence will compare to be equal even if the underlying sequence that they hold is the same. So, given:
String seq1 = "hello";
StringBuilder seq2 = new StringBuilder("hello");
StringBuffer seq3 = new StringBuffer("hello");
comparisons between these three using .equals() return false on Java 1.6, but I can't find any guarantees that this will not change in the future (though it's probably fairly unlikely).
And CharSequence[] and String[] are just arrays of their respective types.
The practical upshot of this is to compare CharSequences for equality, you have to use their toString() method and compare the resultant Strings, since this is guaranteed to return true if the underlying sequences are the same.

Does Java supports Pass-By-Reference ?

Well, this is one of those tricky questions. The correct answer to this question would be
Theoretically: No, Practically: Yes
All passing in Java are Pass-By-Value only. Which means, the value of argument being passed is copied and provided to the called method. In case when the argument of method is of type Object (or sub-class) the value of such an argument is a reference. In this case a copy of this value (which is a reference) is made (but it still refers to same reference) and passed to the called method. So theoretically it is Pass-by-Value but it behaves like Pass-By-Reference.

How to run a Java Application without main method?

public static void main(String[] args) is usually considered the entry point of an application (which is true). But there is a case where we can tweak around and omit the need of main method completely. The answer lies in the keyword "static".
A static block is one per class block (not part of objects). Since this block is one per class, it will be called at the time of class load, not at the time of object creation. Usually this block is used to initialize static variables of the class.
Static blocks are loaded first in JVM (even prior to main method). We can even call other static methods from this block (exactly similar to main method).
consider the code below:
public class WithoutMain{
System.out.println("Hello world");
When this class is loaded in JVM, the anonymous static block is loaded and executed before anything else and the SysOut statement is executed.
Being said this, the entry point remains still the same (main method) i.e. even if static block is present, the JVM will look for main method. if this method does not exist, following exception would be raised
Exception in thread "main" java.lang.NoSuchMethodError: main
We can even tweak around this. The exit(int) method of System class is used to exit the program. The int argument defines the state of program exit. A successful program will exit with a state '0'. Hence writing a statement System.exit(0); would immediately end the application (before JVM can try to find the main method). 

public class WithoutMain{
System.out.println("Hello world");
Once I wrote this article, my friends started complaining that a program without main method could not be run. This was because they were trying to run the application from an IDE. When an IDE detects that the class doesn't contain main method, it is considered that there is no direct entry point (remember that this is a tweak) hence the UI of IDE doesn't displays "run as" options. To test above, try running the application by the naive method, through command prompt.

Creating String with new operator

What is the difference between following String object creations?
  • String a = new String("hello world");
  • String a ="hello world";
When ever a java program encounters a first double quote (") it treats it as beginning of a String Object, and the ending is recognized by consecutive double quote.
going by the above fact, let us analyse the above two statements
String a : We are creating a reference of type String and naming it a
 "hello world" : A string object with value "hello world" is created and added in String pool
In the statement String a ="hello world"; the reference a is now referring to the object created and added to String pool.
new String ("hello world");: In this statement one object is created with value "hello world" and the same is added to the string pool when the highlighted part is encountered. new String ("hello world"). After that, another object is created by the new operator new String ("hello world"), please note that this newly created object (by new operator) is not added to String pool.
String a = new String("hello world");
In the above statement, the reference a is referring to an object which is not present in String pool.
There is a method intern() available in String class. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object(from pool) is returned.

What will happen if you create a package java.lang and create a class String in it..?

Can we create and compile a class String, with package name java.lang ? Will it override the functionality of the existing class present in JVM ?
Surprizingly, we can create any class in any package, and if basic rules of compilation are followed, it will compile fine. Going by that, we can actually compile a class String in java.lang Package. But at run-time, JVM's java.lang package has a higher priority over user created java.lang package, hence original class will be referred.Try creating a String class with a method "printMyName() in java.lang package. Create a main class and call that method. The program will not give any compilation error (as at compile time the class u created is being referred) but at run time you will get java.lang.NoSuchMethodError (as the original class which is present in JVM is being referred and it does not contains this method)

The class which we created will be referred to at the time of compilation. So if we have written code considering the String class that we wrote, it will compile fine. But at runtime, as the JVM's classes have higher priority, original String class will be invoked and the code would behave buggy.