Results 1 to 10 of 10

Thread: Which is worse?

Hybrid View

  1. #1
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: Which is worse?

    Java treats string of the same content to be of the same ref. So in essence i guess they share the same memory location. Since you said your Strings are going to constantly change you will be in effect creating a new object for each new String. As lemenz70 pointed out the Garbage Collector will clean up any unused objects but you will probably get a performance hit though. You are better off just using a StringBuffer and set it's length to zero when you want to clear it out.

  2. #2
    Junior Member lemenz70's Avatar
    Join Date
    Apr 2005
    Location
    Canada (Quebec)
    Posts
    23

    Re: Which is worse?

    Quote Originally Posted by Dilenger4
    Java treats string of the same content to be of the same ref.
    False
    make a test program and do this
    Code:
     String lsString1 = new String ("Hi");
        String lsString2 = new String ("Hi");
        if (lsString1 == lsString2)
        {
          JOptionPane.showMessageDialog(null, "lsString1 == lsString2");
        }
        if (lsString1.compareTo(lsString2) == 0)
        {
          JOptionPane.showMessageDialog(null, "lsString1 compare to lsString2 = 0");
        }
    result: only the MessageBox called by the compareTo will be displayed because lsString1 == lsString2 is false. The object reference is compared and it is not the same even if lsString1 is the same text as lsString2. By using compareTo, it compares the text itself and not the reference.
    (I learned that in my java class)

    that's why I said use the StringBuffer or there will be too much unuseful String objects.

    I hope didn't make that much mistakes!
    William

  3. #3
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Re: Which is worse?

    No True. You are using String Objects. I was talking about String literals.
    Code:
    public class RefTest{
      public static void main(String[] args){
    
       String s1 = "java"; 
       String s2 = "java"; // same refs
       if(s1 == s2){
       System.out.println("Same java refs"); 
       }
       String s3 = new String("sun"); 
       String s4 = new String("sun"); //! same refs
       if(s3 == s4){
       System.out.println("Same sun refs"); 
       }
      }
     }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width