Tuesday, 26 April 2016

Java Tutorial : Java String vs StringBuffer (Hashcode difference)

HashCodeTest.java
public class HashCodeTest
{

    public static void main(String[] args)
    {

        System.out.println("Hashcode test of String:");
        
        /*
         * String is immutable(once created, can not be
         * modified).
         */
        String str = "Welcome";
        
        System.out.println("Before Concat,HashCode = "
                + str.hashCode());
        
        str = str + "Peter";
        
        System.out.println("After Concat,HashCode  = "
                + str.hashCode());

        System.out.println("---------------------------------");

        System.out.println("Hashcode test of StringBuffer:");

        /*
         * StringBuffer is mutable (once created, can be
         * modified.
         */
        StringBuffer sb = new StringBuffer("Welcome");
        
        System.out.println("Before Concat,HashCode = "
                + sb.hashCode());
        
        sb.append("Peter");
        
        System.out.println("After Concat,HashCode  = "
                + sb.hashCode());

    }
}
Output
Hashcode test of String:
Before Concat,HashCode = -1397214398
After Concat,HashCode  = 44468202
---------------------------------
Hashcode test of StringBuffer:
Before Concat,HashCode = 1704856573
After Concat,HashCode  = 1704856573
Click the below link to download the code:
https://sites.google.com/site/javaee4321/java/StringBufferDemo_HashCode_diff_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StringBufferDemo_HashCode_diff_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/ea6705eb8d861d880326570ef3992b3db7646c7d/BasicJava/StringBufferDemo_HashCode_diff_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment