Java String question

Hi,

   This is about "String" and "StringBuffer" in java.

   what is the difference between String str="aaa" and String str1 = new    String("aaa")?

   Wnen we create a String object, we are creating a string that cannot be changed. Then how the string concatenation works? When we concatenate two strings we are not only changing the content but also the size of the string. This violates the string concept of "immutable and fixed length". If the string object can increase its length, what is the use of StringBuffer over String object?

Thanks


 
hemanexpAsked:
Who is Participating?
 
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
>> It creates a new String, it does *not* modify the original strings

- which is also a reason why you should prefer to use StringBuffer if you're modifying your String or appending to it. It saves a lot of performance because it performs all operations over one object. In case you're appending to Strings, you would end up making a lot of String objects. To optimize that, however, Java uses a String pool. But still, more the number of Strings you use in that process, it will still be slow.

Have a look at:

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20898574.html

There was a lot of discussion on that one. Its a long one, I know. But worth reading. Should clear your doubts.
0
 
Drop_of_RainCommented:
With StringBuffer you can append to it.
0
 
Drop_of_RainCommented:
Here is an example:

StringBuffer buf = new StringBuffer();
        buf.append(myInt1.toString());
        // 1st: the number chosen in the 1st combo
        if (myInt2.intValue() != 0) {
            // if the number chosen in the 2nd combo is != 0
            buf.append(".");
            // add "."
            buf.append(myInt2.toString());
            // followed by the number chosen in the 2nd combo
        }
        // this bracket was forgotten!!
       
        if (myUnit.equals(SECONDS)) {
            buf.append("seconds");
            // add "seconds" or...
        }
        else if (myUnit.equals(MINUTES)) {
            buf.append("minutes");
            // "minutes" according to value chosen in the 3rd combo
        }
        buf.append(".wav");
        // Add ".wav"
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
sudhakar_koundinyaCommented:
Although String is Immutable, you can concatenate the string the reason is it internally uses StringBuffer to concatenate the Strings

here is an example how Java Byte code works for concatenating the strings

// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) annotate
// Source File Name:   StringTest.java


class StringTest
{

    StringTest()
    {
    //    0    0:aload_0        
    //    1    1:invokespecial   #1   <Method void Object()>
    //    2    4:return          
    }

    public static void main(String args[])
    {
        String s = "Hello ";
    //    0    0:ldc1            #2   <String "Hello ">
    //    1    2:astore_1        
        s = s + "World !!!";
    //    2    3:new             #3   <Class StringBuffer>
    //    3    6:dup            
    //    4    7:invokespecial   #4   <Method void StringBuffer()>
    //    5   10:aload_1        
    //    6   11:invokevirtual   #5   <Method StringBuffer StringBuffer.append(String)>
    //    7   14:ldc1            #6   <String "World !!!">
    //    8   16:invokevirtual   #5   <Method StringBuffer StringBuffer.append(String)>
    //    9   19:invokevirtual   #7   <Method String StringBuffer.toString()>
    //   10   22:astore_1        
    //   11   23:return          
    }
}


Now coming to your other point, there is no difference between str="Hello" and str=new String("Hello");

Bets Regards
Sudhakar
0
 
objectsCommented:
> what is the difference between String str="aaa" and String str1 = new    String("aaa")?

As far as you are concerned probably none :)

> Then how the string concatenation works?

It creates a new String, it does *not* modify the original strings
0
 
expertmbCommented:
0
 
tomboshellCommented:
I think they have covered it all.  Basically, stop thinking that you are working on the same string.  It is a new string that was created.  Concat took your original string and added to it in the method, returning a new string.  If you assign it to a different variable then your original string will stay the same.  If you assign the return value back to the calling object then you are overwriting it.  
0
 
girionisCommented:
> what is the difference between String str="aaa" and String str1 = new    String("aaa")?

The first one creates a string and puts it in a pool of strings (so any subsequent string you create with the same value will be pointing to the same instance of string in the pool) while the second one creates a brand new string in a brand new memory location.
0
 
thomas908Commented:
>>what is the difference between String str="aaa" and String str1 = new    String("aaa")?

String String str="aaa" creates a string object and puts it in string constant pool. if another string is created with "aaa" it points to the existing string in the pool. This feature is provided because Strings are immutable so it improves perfomance. had it not been there every time you created a string with contents "aaa" it would have created a new object. But if u write
String str1 = new String("aaa");

it will create a new object regardless of where same string exists the pool or not.



>> Wnen we create a String object, we are creating a string that cannot be changed. Then how the string concatenation works? When we concatenate two strings we are not only changing the content but also the size of the string. This violates the string concept of "immutable and fixed length". If the string object can increase its length, what is the use of StringBuffer over String object?

When itt looks String are changing they aren't actually changing(immutable) but every time you make a concatenation a new string object is created.
   String s = "abc";
   s = "abc" + "xyz";
This creates 3 String object
1. "abc" which is intially refered to by s but after 2nd line is executed there is no reference to it and it is left in the cold without any way to refer it back.
2. "xyz" with no reference to it.
3. "abcxyz" now refered to by s.

if there are lot of such concatenation you'll end up making lot of string obejcts in the memory thereby wasting memory so StringBuffer comes handy here as it is not immutable.

 
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Also found something for this at Sun's Java tutorial:

http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html
0
 
sudhakar_koundinyaCommented:
FYI

Strings are quite different from C++. They are immutable , i.e. You can't change the characters in a string. To look at individual characters, you need to use charAt() . Strings in Java are 16-bit Unicode. To edit strings, you need to use a StringBuffer object or a char[] . For manipulating 8-bit characters, you want an array of bytes -- byte[] . There are three types of empty string, null, "" and " ". Here is how to check for each flavour:

if ( s == null ) echo ( "was null" );
else if ( s .length() == 0 ) echo ( "was empty" );
else if ( s .trim().length () == 0 ) echo ( "was blank or other whitespace" );

The following form:

if ( "abc" .equals (s)) echo ( "matched" );

is preferable to:

if ( s.equals ( "abc" ) ) echo ( "matched" );

because it won't give an exception if s is null.

Strings are immutable. Therefore they can be reused indefinitely, and they can be shared for many purposes. When you assign one String variable to another, no copy is made. Even when you take a substring there is no new String created. New Strings are created when:

    * you concatentate.
    * you do reads.
    * you foolishly use new String(String); //
    * you use new String(somethingElse) ; for conversion.



Source : http://mindprod.com/jgloss/string.html

0
 
rafiekCommented:
> what is the difference between String str="aaa" and String str1 = new    String("aaa")?

when the "keyword" is invoked, it makes a call to the String class's constructor and creates a new object in memory.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Not very original, was that?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.