fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String sl = "First Name"; // a string literal
  13. String so = new String("First Name"); // a string object
  14. StringBuffer sb = new StringBuffer("First Name"); // a stringBuffer object
  15.  
  16.  
  17. System.out.println("s1 = " + sl + " hashCode = "+ mimicObjectToString(sl));
  18. sl += "Kumar"; // appended ,
  19. System.out.println("s1 = " + sl + " hashCode = "+ mimicObjectToString(sl)+ "\n");
  20. // if the output differs it means a new reference has been created during appending
  21.  
  22. System.out.println("so = " + so + " hashCode = "+ mimicObjectToString(so));
  23. so += "Kumar";
  24. System.out.println("so = " + so + " hashCode = "+ mimicObjectToString(so)+ "\n");
  25.  
  26. System.out.println("sb = " + sb + " hashCode = "+ mimicObjectToString(sb));
  27. sb.append("Kumar");
  28. System.out.println("sb = " + sb + " hashCode = "+ mimicObjectToString(sb)+ "\n");
  29.  
  30. System.out.println("Changed hashCode denotes different reference has been created, implying its \"immutable\" nature");
  31. }
  32. public static String mimicObjectToString(Object o) {
  33. //prevent a NullPointerException by returning null if o is null
  34. String result = null;
  35. if (o !=null) {
  36. result = o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
  37. }
  38. return result;
  39. }
  40. }
  41.  
Success #stdin #stdout 0.23s 42636KB
stdin
Standard input is empty
stdout
s1 = First Name hashCode = java.lang.String@2ff4acd0
s1 = First NameKumar hashCode = java.lang.String@3b9a45b3

so = First Name hashCode = java.lang.String@4f3f5b24
so = First NameKumar hashCode = java.lang.String@15aeb7ab

sb = First Name hashCode = java.lang.StringBuffer@7b23ec81
sb = First NameKumar hashCode = java.lang.StringBuffer@7b23ec81

Changed hashCode denotes different reference has been created, implying its "immutable" nature