Leaderboard1

Leaderboard2

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, May 28, 2014

Difference between String s = "java" and String s = new String("java")

We all known the equals() check the content of the string , but '= =' checks the object reference.

Strings are immutable and final in Java
Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality. Now if you are puzzled why String is immutable or final in Java.

Strings are maintained in String Pool
Advanced Java String tutorial and example programmers As I Said earlier String is special class in Java and all String literal e.g. "abc"  (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.


String str = "John"; //1st String object
String str1 = "John"; //same Sring object assigned
String str2 = new String("John") //forcing JVM to create a new String object

//this will return true
if(str == str1){
System.out.println("both str and str1 are pointing to same string object");
}

//this will return false
if(str == str2){
System.out.println("both str and str2 are pointing to different string objects");
}

Please post comments !

Why String is Immutable in Java ?

As Java developer, we all know that String is an immutable class. But very few knows that why String is immutable. As String is used vastly in Java application, as parameter in network connection, database url, serialization etc, so for security reasons, memory saving, it's made immutable.

1. String Pool

String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

The following code will create only one string object in the heap.

String string1 = "abcd";
String string2 = "abcd";

2. Cashing String hash code


Being immutable, String provides a constant hashCode. As String is widely used as a key in HashMap, so being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes. That means, there is no need to calculate hashcode every time it is used. This is more efficient.

3. Security

String us used as a parameter in many places, database connections, file opening etc, so mutable Strings cam create huge problems. To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded.

Please post comments !

Importance of equals() and hashCode() methods in Java objects

equals() and hashCode() methods are required when you insert objects in s collection. Both play a very important role for Java objects. Both methods are defined in Object class. As Object class is the parent of all classes by default, so we override these methods in our objects and give our own definitions. 

equals()

equals() is required to compare the properties of one object with other. equals() method uses identity operator(= =)to determine whether object are equal. In equals()we compare only those properties on the basis of them objects are compared. For primitive data types like int, double identity operator is sufficient but in case on objects we need more functionality for comparing. For example:

class Employee{
private String name;
private int age;
public Employee(String name, int age){
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj){
if(obj != null && obj instanceof Employee){
if(((Employee) obj).name.equals(this.name) && ((Employee) obj).age == this.age){
return true;
} else
return false;
} else
return false;
}
}

Comparing Employee class objects.

Employee e1 = new Employee("john", 25);
Employee e2 = new Employee("Dev", 26);
System.out.println(e1.equals(e2)); // false


hashcode()

hashCode() method is used when object are inserted in HashMap, HashTable, HashSet. When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object. 

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:

  1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
  2. If object1 and object2 have the same hash code, they do NOT have to be equal too.

In shorter words:
  1. If equal, then same hash codes too.
  2. Same hash codes no guarantee of being equal.

class Employee{
private String name;
private int age;
public Employee(String name, int age){
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj){
if(obj != null && obj instanceof Employee){
if(((Employee) obj).name.equals(this.name) && ((Employee) obj).age == this.age){
return true;
} else
return false;
} else
return false;
}
@Override
public int hashCode(){
return this.name.hashCode() * this.age; // calculating hashCode using Employee properties   
}
}


Please post comments !