Solved

Java String question

Posted on 2004-08-15
14
385 Views
Last Modified: 2010-08-05
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


 
0
Comment
Question by:hemanexp
  • 3
  • 2
  • 2
  • +6
14 Comments
 

Expert Comment

by:Drop_of_Rain
ID: 11806973
With StringBuffer you can append to it.
0
 

Expert Comment

by:Drop_of_Rain
ID: 11806984
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11807041
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
 
LVL 92

Expert Comment

by:objects
ID: 11807229
> 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
 
LVL 6

Expert Comment

by:expertmb
ID: 11807320
0
 
LVL 30

Accepted Solution

by:
mayankeagle earned 100 total points
ID: 11807332
>> 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 7

Expert Comment

by:tomboshell
ID: 11807393
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
 
LVL 35

Expert Comment

by:girionis
ID: 11807432
> 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
 
LVL 8

Expert Comment

by:thomas908
ID: 11807625
>>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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11807635
Also found something for this at Sun's Java tutorial:

http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11807660
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
 

Expert Comment

by:rafiek
ID: 11838725
> 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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11839693
Not very original, was that?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
return in catch statement 1 40
wordlen challenge 3 49
bitbucket vs gitbucket 3 35
compre toata in where clue oracle 4 44
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now