aspose file tools*
The moose likes Beginning Java and the fly likes strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "strings" Watch "strings" New topic
Author

strings

Gopal Krishna
Greenhorn

Joined: Sep 22, 2005
Posts: 10
What is the difference between

String arg="gopal"; and String arg=new String("gopal");


plz help me

thanks in advance
vidhyasagar reddy
Ranch Hand

Joined: Jul 05, 2005
Posts: 40
In the first statement when one object is created for the string

"xx"---> memory is allocated for xx and the corresponding variable just refer to the already created memory

for String s = new String("xx");

memory is allocated for "xx"

and for var s again seperate memory allocated

here 2 objects are created in the memory
Darren Horsman
Greenhorn

Joined: Dec 04, 2005
Posts: 9
Also, with the first, if the String "gopal" is already being used, the same object may be reused.

When you use the new keyword, you are forcing the creation of a new object.
Gopal Krishna
Greenhorn

Joined: Sep 22, 2005
Posts: 10
hi vidya sagar,

can u plz send ur personal mail id
Masoud Kalali
Author
Ranch Hand

Joined: Jul 08, 2004
Posts: 531

String is *mutable , there is no diffrences between using
String s = "aa" ;
or
String s =new String ("aa") ;
whether you used string before or not,imho

when ever you change the value of an string variable you are forcing it to call its constructor.

*mutable is a pttern , in this pattern object allways re-new in case that its state changes.


Masoud Kalali
Software Engineer - My Weblog - GlassFish Security
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
I think one should also note that when you see:

It's usually a sign that the programmer is new to Java! Perhaps a convert
from C++. There's no practical reason to do that, although if they write:

It could be because x is a substring of a larger string. The above will
*copy* the text out of x, perhaps allowing the larger string to be gc'ed.
Here's a demo (at least, it works with my JRE):

[ December 05, 2005: Message edited by: Jeff Albrechtsen ]

There is no emoticon for what I am feeling!
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791

String is *mutable , there is no diffrences between using
String s = "aa" ;
or
String s =new String ("aa") ;
whether you used string before or not,imho

when ever you change the value of an string variable you are forcing it to call its constructor.

*mutable is a pttern , in this pattern object allways re-new in case that its state changes.

This is not quite right. String is immutable meaning you cannot change its state at all, ever. (Except by cheating with reflection.) Any of the operations you might think of as changing string state actually create and return new strings.

For example:

String s = "abc";
s += "def";

The second line creates a new string containing "abcdef" and sets the variable s to point to the new string. What happens to the old string? Don't know, don't care. It may be pooled by the JVM or something tricky, but it's not something I have to worry about.

Ok, sometimes I care. This code ...

String one = TWO_MILLION_CHARACTER_STRING;
String two = one.substring( 0, 1 );
String one = null; // or goes out of method scope or something

... may look like I just picked out a couple bytes of interest and let the giant string go to garbage collection. However the String class might say "I'm going to save memory and point two at a chunk of the immutable byte buffer already built for one rather than create a new buffer. Aren't I clever?" Then the two million characters would not be collected and I could eventually be in memory trouble.
[ December 05, 2005: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Gopal,

This is, as far as I can reckon, your third warning about the JavaRanch naming policy. You need to add a second name, and you need to do it now, please. Here is the link to the "My Profile" page which lets you change this. Otherwise, I'll have to close your account. Thanks for your cooperation.


[Jess in Action][AskingGoodQuestions]
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

Gopal,
welcome to JavaRanch!

We're a friendly bunch here, but we do have one rule that we take seriously -- the JavaRanch Naming Policy

Basically we require display names to be two words: your first name, a space, then your last name. While we prefer you use your real name, we of corse cannot enforce it. However, obviously fictitious names are not allowed.

Please edit your profile and correct your display name.


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Thomas Samimuthu
Greenhorn

Joined: Aug 07, 2001
Posts: 8
Originally posted by Gopal:
What is the difference between

String arg="gopal"; and String arg=new String("gopal");


plz help me

thanks in advance


String arg="gopal" //this value is added to the pool

String arg=new String("gopal"); //this is not added to the pool

so if your program uses a particular string value then use string literal.
or you can push the string value to the pool by calling intern() method.


Thomas
Masoud Kalali
Author
Ranch Hand

Joined: Jul 08, 2004
Posts: 531

Originally posted by Stan James:

This is not quite right. String is immutable meaning you cannot change its state at all, ever. (Except by cheating with reflection.) Any of the operations you might think of as changing string state actually create and return new strings.

it is what i meant by that post.
for more description : I said that an String re-new itself by calling its constructor when-ever you change its value.
so when you have
String a = "Masoud" ;
then you have some code like
a="Stan" ;

a's constructor called again here to change the value of string by reCreation of the object.


The second line creates a new string containing "abcdef" and sets the variable s to point to the new string. What happens to the old string? Don't know, don't care. It may be pooled by the JVM or something tricky, but it's not something I have to worry about.

indeed it is marked by jvm for GC , so in next GC wave the unreferenced object will be cleaned.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Originally posted by Masoud Kalali:

indeed it is marked by jvm for GC , so in next GC wave the unreferenced object will be cleaned.


No. All literal strings and string-valued constant expressions are interned,
meaning they are maintained in a pool and thus never gc'ed.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Masoud]: it is what i meant by that post.

OK - but note that you said "mutable" when the correct word there was "immutable". The two words have opposite meanings, so it's important to pay attention to which word is which. A mutable object can be changed (without needing to create a new object), and an immutable object cannot.

[Jeff]: No. All literal strings and string-valued constant expressions are interned, meaning they are maintained in a pool and thus never gc'ed.

Mmmm... "never" is an overstatement here. It will never happen in the code shown here, assuming it's started from the command line with java Test" or something fairly similar. However the Strings associated with compile-time constants can become eligible for GC if you start playing around with class loaders (or running in an app server). See here for a recent discussion.


"I'm not back." - Bill Harding, Twister
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Thanks for the correction, Jim. It's got me playing around with intern,
but I'm getting no output from the following program:According to the API for intern:


When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method, then
the string from the pool is returned. Otherwise, this String object is added
to the pool and a reference to this String object is returned.

I would think that the latter case would apply to most of the
strings I'm interning, but when I run this code, line==line.intern()
is never true. What's happening?
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

Emperical evidence suggests that a copy of the string is placed in the pool, not the string itself.



None of the lines equal their interned value, but the line that does exist as a constant is correctly located.
[ December 07, 2005: Message edited by: Joel McNary ]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
So much for the API... But my real goal was to be able to solve the following:
How to tell if there is an interned String equal to a given String?
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
... The reason I'm curious about whether or not a String in interned is
that I'd like to verify that when a class is unloaded, it's String literals
may become eligible for gc. Here's my best attempt: if you'd like to try it
youself, compile the following class and jar it into sample.jar:
...Then delete the file LoadMe.class! So it's not loaded by the following:
When you run Main, you should see that the identity hash code for "foo" changes
(at least, it does for me) and I take that as evidence that the String
disappeared from the pool and was re-interned.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes, it does appear that this particular part of the API is violated. For a string not already in the pool, it seems to return a copy, not the original, as Joel said. No idea why.

[Jeff]: How to tell if there is an interned String equal to a given String?

There doesn't seem to be a way to tell that. It would be possible if intern() obeyed the part of the API you quoted, but apparently not. Fortunately I don't think it really matters in any practical way. It seems to be one of those how-many-angels-on-the-head-of-a-pin questions.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Jeff]: I take that as evidence that the String disappeared from the pool and was re-interned.

Yup. That's enough, in my opinion. If the number had stayed the same, we'd be somewhat less certain about what happened. But if the number did change, then we've definitely got a new instance.

If you wanted to see it another way I suppose you could create a really big string, big enough that you could clearly observe its effect on available memory. Then get it to go away, and then make it reappear. If the memory usage in the middle is too small to possibly hold the big string, then you've demonstrated it really was GC'ed. To my mind that's a bit less definite than the identity hash code. But if you're looking for additional confirmation, it might be interesting.
jiju ka
Ranch Hand

Joined: Oct 12, 2004
Posts: 306
http://javatechniques.com/public/java/docs/basics/string-equality.html
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
That reference repeats the API line "Otherwise, this String object is added to
the pool and a reference to this String object is returned" that no longer
seems to be true...
Masoud Kalali
Author
Ranch Hand

Joined: Jul 08, 2004
Posts: 531

hi friends.
I am sorry if my miss-understanding and uncorrect use of Pattern name bring any inconvenience to any one.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: strings