TestStringStringBuffer.java


public class TestStringStringBuffer {
   public static void main (String[] args){
   	   
      // test Boolean contructors
      Boolean b0 = new Boolean(true);
      Boolean b1 = new Boolean("sss");
      Boolean b2 = new Boolean("tRue");
      System.out.println(b0 + " " + b1 + " " + b2);//true false true
         	   
      //String is immutable
      //-------------------
      String s1 = "abc";
      String s2 = "def";
      String s3 = s1.concat(s2.toUpperCase());
      String s4 = s3.replace('a', 'z');
      String s5 = s3.valueOf(12);
         	   
      System.out.println(s1 + ' ' + s2 + ' ' + s3 + ' ' + s4 + ' ' + s5); 
      // abc def abcDEF zbcDEF 12
         	   
      // String and StringBuffer
      //------------------------
      String       s   = new String("Hello");
      StringBuffer sb1 = new StringBuffer("Hello");
      StringBuffer sb2 = new StringBuffer("Hello");
         	   
      if (sb1 == sb2)
         System.out.println("sb1 == sb2");
      else
         System.out.println("sb1 != sb2");
         	   
      // StringBuffer does not override equals()
      // ---------------------------------------
      if (sb1.equals(sb2))
         System.out.println("sb1.equals(sb2)");
      else
         System.out.println("NOT sb1.equals(sb2)");
         	   
      // Notice the diff of logical "&&" and logical "&"
      // -----------------------------------------------
      if ( sb1.length() > 5 && sb1.append(" There").equals(s) )
         ;//do nothing
         	      
      System.out.println("&& " + sb1);
         	   
      // This will have side effect
      // --------------------------
      if ( sb2.length() > 5 & sb2.append(" There").equals(s1) )
         ;//do nothing
         	      
      System.out.println("& " + sb2);
   }
}

last updated: 09-25-1999
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]