aspose file tools*
The moose likes Beginning Java and the fly likes String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String" Watch "String" New topic
Author

String

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


It is said Strings are Immutable Object, You can change the value of Immutable Object. But How can it be changed in that example?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3654
    
  15
s is not a String object, it is a String reference. All that code is doing is getting s to refer to a different String object.


Joanne
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
You mean that:



This line create an object. and this line creates another?


Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Make s final and then try to change it.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11411
    
  16

yup. it's like erasing someone's address and writing a new one down on the same piece of paper. You have not done a thing to the original house, and in fact may not be able to find it anymore, but it's still there.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
samir vasani
Ranch Hand

Joined: Nov 24, 2010
Posts: 62
The answer can be as follow:

in the above example s="456" is overwritten by s="1" in a string pool
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11411
    
  16

What do you mean by 'overwritten'? The string "456" still exists in the string pool after the second assignment. If you have no other reference to it, you can't get back to it again, but it's still there.

the only thing that gets overwritten is the value stored in 's'.
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


In line one, S points to the address of 456 in memory, In line 2 S points to address of 1 in memory, It is like pointer in C.Right?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

abalfazl hossein wrote: It is like pointer in C.Right?


Yes, although Java won't let you turn it into a number!


[Jess in Action][AskingGoodQuestions]
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Whenever dealing with items in memory I find it is always easier to draw a picture.

So after the line

there is some area in memory that now looks like this, with the reference variable S "referring" to some string object in memor

|S| -------> |"456"|


so all the line does is creates a new String object in memory and changes S to refer to that object.

so memory now looks like this:

|S| --------> |"1"|


|"456"| (This is just sitting in memory somewhere)


Notice that as Fred said the String "456" still exists, it just has no variable referring to it.

Hope this helps,
Hunter

"If the facts don't fit the theory, get new facts" --Albert Einstein
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Thanks!
I search about string to learn more and I find this:
String str1 = new String("java");

Above statement will create two objects.

first object is refering to "java" . We dont have any reference to this object.
second object is created because of the new operator in heap memory area whose content is "java" and reference is stored in str1.


I search about string to learn more and I find this:

http://www.coderanch.com/t/411637/java/java/Difference-between-String-java-String

1-Then, Every time we use new fro any object, Two objects will be created not for only sting, Right?
2-A code like this creates an object:
String S="123";
String class, Is the only class that we can create object of that without new operator
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Is the only class that we can create object of that without new operator?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

No, besides String literals there is also auto-boxing. Consider this code:

This code takes the int value 16807 and "boxes" it into an Integer object whose value is 16807. So it's equivalent to

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
1-Then, Every time we use new fro any object, Two objects will be created not for only sting, Right?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

When you use new, one new object will be created, not two. Why do you think there would be two objects created?


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Neko Singh
Greenhorn

Joined: Jan 25, 2011
Posts: 8
How long does "456" stay in memory, unreferenced?

If later you have


Is there going to be a second string "456" created in memory?

What is the reason for leaving these strings in memory?

Is this at all related to "memory leaks"? Seems like it would lead to some kind of bloating.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

The string objects for string literals in your code, like "456", will stay in memory until the JVM stops. They will not be garbage collected. That's because the string pool is referencing them.

When you have a second string literal "456" somewhere else in your code, there will not be another String object created - the one that is already in the string pool will be reused. That's the whole point of having the string pool - being able to reuse the strings that are in there.

Having literal strings in the string pool does not cause a memory leak. Literal strings are in the source code itself - they will not be created dynamically at runtime, it's not the case that more and more strings will be added to the string pool at runtime, which would be the cause of a memory leak. The number of literal strings in the source code is normally limited (you probably don't have thousands of string literals in your source code), so the amount of memory that the string literals will take up is limited.

Note that it is possible to explicitly put a string in the string pool by calling the intern() method on it. You should not normally do that, because that can certainly be a cause of memory leaks.
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


Why the first one occupied more sapace in memory?


Second question:

Objects are equal
Objects are equal


Str2 is a reference. Not the string itself. Right?. But as I see, String str3 = str2; this copy strings.May you explain more?






Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

abalfazl hossein wrote:Why the first one occupied more sapace in memory?

I already explained that in my posts above. Is there something specific you don't understand about my explanation?

abalfazl hossein wrote:Str2 is a reference. Not the string itself. Right?. But as I see, String str3 = str2; this copy strings.May you explain more?

In Java, all variables of non-primitive types are references. So yes, str2 is a reference to a String object.

No, the statement String str3 = str2; does not copy strings. It just makes str3 refer to the same object that str2 is already referring to.

The == method compares if two variables refer to the exact same object. Since str2 and str3 are referring to the same object, the comparison is true.

Ofcourse, str3.equals(str2) is also true, because you are comparing the String object with itself.
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Thanks Jasper



What about now?Are these tow orders make same occupation in memory?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

Let's analyze what happens in these two lines of code.

Line 1: There are two String objects involved here. First, there is a String object for the literal string "hi". That String object will be referenced by the string pool (because it's a literal). Then there's the String object that you create explicitly by calling new String(...). That String object will contain a copy of the first one that's in the string pool. Note that the copy will not be in the string pool. Variable name1 will refer to the copy.

Line 2: This is a completely separate statement that doesn't do anything with the two String objects of line 1. Here, you simply make variable name2 refer to the String object for the literal string "ye". Ofcourse that String object is referenced by the string pool, because it's a literal.
Jason Cupp
Greenhorn

Joined: Jan 28, 2011
Posts: 7
Jesper de Jong wrote:
Having literal strings in the string pool does not cause a memory leak. Literal strings are in the source code itself - they will not be created dynamically at runtime, it's not the case that more and more strings will be added to the string pool at runtime, which would be the cause of a memory leak. The number of literal strings in the source code is normally limited (you probably don't have thousands of string literals in your source code), so the amount of memory that the string literals will take up is limited.
I'm probably misunderstanding, but what you're saying makes it sound like Java is just using the memory space of the actual string literal that you have typed into your code, which means that it will never use more memory for strings than what is already taken up by your code.

So what about something like this?

That's not taking up much code space, but it appears that it would create a billion different string literals, each one twice as big as the last, and even though all of them but one are not referenced, they're still all in memory. I'm never going to use any of those other 999,999,999 string literals again, but they're still there. That seams like bloat and memory leak to me.

Maybe a more realistic example is that the user can input the name of his best friend, and the user decides to change his mind 1000 times, never choosing the same name twice.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3654
    
  15
Jason Cupp wrote:That's not taking up much code space, but it appears that it would create a billion different string literals, each one twice as big as the last, and even though all of them but one are not referenced, they're still all in memory. I'm never going to use any of those other 999,999,999 string literals again, but they're still there. That seams like bloat and memory leak to me.


Only the first line of your code will create a String literal in the string pool. All the strings created in the loop are created in normal heap memory, not the string pool. As such they are available for garbage collection.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

No, there's only one string literal in that program. It's the "Tim" created in line 1. Line 3 does create a billion string objects, it's true. But they aren't literals. A string literal, if you haven't already caught on, is a constant value which appears literally in the code.

And you're right that all but one of those billion string objects are unreferenced. That makes them available for garbage collection. There's no leaking going on there.
Jason Cupp
Greenhorn

Joined: Jan 28, 2011
Posts: 7
Well, that's good to know.

So about the other example, if I have a String called name that is assigned its value from user input, and the user changes its value a thousand times, all of that is available for garbage collection, too?

edit: I'm obviously new to Java coming from a C++ background.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

Any object that isn't referenced anymore (because all the variables that refer to the object have been reassigned or have gone out of scope) are available for garbage collection.
Jason Cupp
Greenhorn

Joined: Jan 28, 2011
Posts: 7
Well, that makes me feel better. I'm used to having to deal with memory management myself.

Thanks for your help.
Ed Connery
Ranch Hand

Joined: Mar 11, 2010
Posts: 70
Paul Clapham wrote:And you're right that all but one of those billion string objects are unreferenced. That makes them available for garbage collection. There's no leaking going on there.
If I understand correctly, while those objects are available for garbage collection, it's possible to run out of memory because we can't count on the garbage collector running at any given time, not even if we try to force it. True?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

Jason: Java has automatic memory management, the garbage collector is part of that. That makes it far easier to use than C++, because you don't have to think about cleaning up all your objects yourself and you'll not get memory leaks easily.

It is possible to have memory leaks in Java, but the cause of those is not forgetting to free things (which is the most frequent source of leaks in C++), but holding on to objects while you don't need them anymore.

Ed: No, not true - you will not run out of memory because there are too many objects waiting to be garbage collected. If there's not enough memory to allocate some more, the system will first try to free up some memory by garbage collecting before it throws an OutOfMemoryError. You will only get an OutOfMemoryError if you have too many "live" objects (objects that are referenced by live threads).

The garbage collector should be regarded as an internal thing inside the JVM, and it knows best when to clean up old objects by itself - you should not normally try to mess with it. Trying to force garbage collection at some point could even have a negative effect on the performance of your program. That's why Java makes no guarantees (especially with regard to the System.gc() method) that you can control yourself when garbage collection is done. There are ways to tune the garbage collector, but those are advanced things that you only need to look into when you know that there's a specific problem with garbage collection in your program.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String