This could be the dumbest question ever asked but I think it is a total confusion for a newbie. Can somebody clarify what is meant by immutable? Why is a String ... |
Consider the following example.
String str = new String();
str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
Now, in Java, String objects are immutable. Then how come the object 'str' ... |
I have these two situations:
String s = "aa";
s = s + " aa";
System.out.println(s);
//......
that work fine! It prints aa aa.
But there is a problem:
String ...
|
How to make a java class immutable and what is the need of immutability and is there any advantage over this?
|
String s = ...;
s = s.substring(1);
Is this possible? I thought you can't change a String object in Java.
|
In String source it looks like the hash code value (private int hashCode) is set only if the method public int hashCode() was called at least once. That means a different ... |
So I want to be able to have a collection of mutable Strings in Java.
I have this test class to see the functionality of immutable Strings:
public class GetStringTest
{
...
|
|
I know that Java strings are immutable. However, when I run the function below, the output is not what I expect it to be.
public static void main(String[] ...
|
I've got a question but to get an answer the following fact has first to be accepted: in some cases, Java Strings can be modified.
This has been demonstrated in the Artima ... |
I am using the OpenJDK Java compiler under Ubuntu. I wanted to convert a character array to a string and when that seemed to have ended up giving ambiguous results, I ... |
I was told that strings in java can not be changed.What about the following code?
name="name";
name=name.replace('a', 'i');
Does not it changes name string?
Also, where is the implementation of the replace(); compareTo(); equals(); provided?
I ... |
Possible Duplicate:
What's the advantage of a String be Immutable?
Strings are Immutable?
String s = "PROJECT";
Here s cannot be modified. But String s2=s.toLowerCase() will return me ... |
I remember reading a section, possibly in Bloch's Effective Java, that said that for most cases, where
String a = "fish";
String b = "fish";
that a == b in most cases because Strings ... |
I typically place global compile-time variables (like constants that i use such as avogadro's number or whatever) into public static final variables. However, i hadn't ever considered if this actually does ... |
It actually seems rather odd to me that you knowing that String is just a character array would expect changing it to be easy when you know all the restrictions of ... |
Well, the quoted article is pretty good, but... An immutable object is convenient in some multi-threaded applications. If given a reference to an immutable object, there is no need to consider whether synchronisation is necessary (*), to prevent a thread seeing unexpected, or even part-complete, modifications to that object. So, if a thread in a multi-threaded application has been given a ... |
I have written a completely useless program that changes a String, and I was wondering if it will work on other JVMs. I know that by accessing private variables, I'm asking for problems and I really shouldn't be doing it, but that's never stopped me before. I was just curious if the implementation of String is the same (or similar) across ... |
Yes, and if you build a fire under a refrigerator, you can use it to heat food! The statement that instances of a Java class are immutable does not mean that under no circumstances will the bits change. Besides using reflection, it would be easy enough to use JNI (native methods) to do the same thing. Both of these things are ... |
Hi Serena, The String class is final and so cannot be subclassed. Add this to the fact that no methods are provided to change the state of the String make it immutable. I don't know about the windows JDK, but the linux distribution comes with the source files for all classes in a zip file if you are ever interested in ... |
|
In the future, try to post a single thread per question. If one question should spark some debate, the other question could get lost in the shuffle. As for String, it is immutable for performance. If you watch a Java program with a profiler, the class with the most instances by far will be String. Since it is immutable, the compiler ... |
Strings in Java are Immutable. But then ,why is it so ? I have gone through quite a few resources in the Net which deal with Immutability of Strings. But still am not able to get into a conclusion as to why Strings were made immutable at first. I have a fairly good understanding of the String Literal Pool concept. I ... |
|
public final class Int { private final int value; public Int(int value) { this.value = value; } public int getValue() { return value; } public String toString() { return String.valueOf(getValue()); } public boolean equals(Object o) { if (o==this) return true; if (o instanceof Int) { return getValue() == ((Int)o).getValue(); } else return false; } public int hashCode() { return getValue(); } ... |
short form: read the API documentation long form: String is immutable for the following reasons: 1) Strings are commonly used as keys within hashes 2) Strings are given special treatment by the compiler; for example string literals are cached and reused. StringBuffer is more a container class for Strings than a stand-in for String. Integer, Float, Character etcetera are also immutable. ... |
Look at the code class String { private int x; String(int i) { x=i; } public int getX() { return x; } } public class TryString { public static void main(java.lang.String[] arg) { String s = new String(5); System.out.println(s.getX()+ " is output"); } } its working fine String is a immutable Final class??? then wats its advantage f being immutable??? |
String s = "cat"; s.toUpperCase(); System.out.println(s); prints "cat" in lowercase because Strings are immutable. The fact that Strings are immutable (and may serve as compile time constants) does not mean, that the variable cannot be reassigned, therefore String s = "cat"; s = s.toUpperCase(); System.out.println(s); now prints "CAT". The original "cat" - String-object does not have changed, however it is now ... |
There are dozens if not hundreds of discussions on the web about why Java Strings are immutable. It is actually interesting to read the many threads, and I would highly encourage everybody to do so as a way to learn more about the language. One interesting topic to pursue is that javac itself is written in java, and why that may ... |
String object are immutable. I think you are confusing the notion of a variable that stores a reference to an object of some kind, and the object itself. Your code fragment creates a new String object: String a = new String("Raman"); // a now stores a reference to a String object "Raman" System.out.println(a); // Outputs the original a="kumar"; // Creates a ... |
well, if u do, String s = "maulin" + "vasavada" then maulin is in one string and vasavada is in another and both of them are in String "Literal Pool" and we don't have a way to get reference to it. if we do, String s1 = "maulin"; String s2 = "vasavada"; String s = s1 + s2; then we have ... |
|
|
|
|
|
When you create a string using new operator , it creates the string object for you in the heap.But when you create a string using a construct similar to below then it creates the string in the string pool and before creating it checks whether a equivalent object is already present there or not.If yes ; then it returns the reference ... |
|
Originally posted by Arjun Reddy: Whenever we perform any operation on the class's objects, the old object remains and a new object is created. Can we do this? Thanks. I may be wrong, but my interpretation of this is that the OP is thinking of methods such as substring which return a new String rather than modifying the existing one. If ... |
String objects are immutable. What that means is that you cannot change the contents of a String object. You can have to variables referencing the same String object, but since the String object itself cannot be changed, you can't get strange effects. Because String objects are immutable, the Java compiler can safely implement an optimization trick. If you write a program ... |
|
|
|
|
|
public static void main(String[] args) { String i=new String("Ajay"); String i2="Ajay"; [color=red] System.out.println("before i==i2 ? :"+i==i2); System.out.println("i2"+i2); System.out.println("i"+i);[/color] try { Class intVal = Class.forName(i2.getClass().getName()); Field[] f =intVal.getDeclaredFields(); for(Field fld : f){ if(fld.getName().equals("value")){ fld.setAccessible(true); char va[]=((char[])fld.get(i2)); va[0]='T'; va[1]='E'; [color=red] System.out.println(va);[/color] fld.set(i2, va); } } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO ... |
|
String class is not a common class. It has a specific requirements and it is handled as special by both JVM Specification and Java Language Specification. Many language features depend on ability of String to represent constant text. The "side effect" of the immutability of Strings is that it makes the Strings cacheable using hash value. That improve the performance a ... |
The for loop is creating a string that already exists in the string pool ("1234"). In Head First Java appendix B #9, its seems to say it wont create another "1234" string because of "string immutable". Why is another "1234" string getting created in the for loop? public class testStringImmutable { public static void main (String[] args) { String str1 = ... |
i was thinking why the String is immutable , means when ever we make changes to our current String it gets saved in different location and our variable point now to that memory location (changed memory location) ? eg : String name = "naved; // memory location is 10 name.toUppercase(); // memory location is 12 , & now variable name is ... |
You should also note that StringBuffer being synchronized really only helps you in that multiple threads can modify the StringBuffer safely, however, the value of the StringBuffer can be modified out from underneath you in one thread in unexpected ways. For example, let's say you have this code: StringBuffer theString = new StringBuffer("Hello There"); public StringBuffer getTheString() { rerurn theString; } ... |
|
but I thought that Strings were objects, that is what I find so confusing about the whole thing, they are not simple data types in java. Are Strings ultimately pointers that just change addresses and the methods they invoke behind the scences just accomplish this or have I it all wrong again??? What is the difference between a String, and a ... |
Hi friends, i have a doubt regarding string immutability. i know String is immutable class, so its value cannot be changed so String str1 = "hai"; str1 = "hello"; then a new string object is created and first one will be eligible for garbage collection. its something internal and we use str1 as the reference. what i am asking is is ... |
|
|
Furthermore, that reflection trick shown by georgemc won't work it a proper SecurityManager is in place. Nor on certain JVMs. It takes advantage of the fact that current implementations of java.lang.String use a char[] internally to represent the data, but the JLS doesn't mandate this, and vendors are free to do it however they wish. I just used it to show ... |
Another way of saying if: A variable holding a reference to string, and the String object itself, are two different things. You can change the variable value (i.e., the reference) as many times as you want. That simply changes which String object the variable is referring to. It does not change the contents of the String it refers to (or formerly ... |
HI, I have studied about String class it says String are immutable in java Ex: i have declared the identifier in a variable like String x="welcome"; if i want to change or replace this sting using the following way x=x.replaceAll(x,"Good"); if i print the value of x it bring the out like "Good" then how we should say String are immutable ... |
From the JLS-> A String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters. Why are String objects immutable ? |
|
|
JVM internally maintains the "String Pool". To achive the memory efficiency, JVM will refer the String object from pool. It will not create the new String objects. So, whenevr you create a new string literal, JVM will check in the pool whether it already exists or not. If already present in the pool, just give the reference to the same object ... |
See when I declare StringBuffer str = new StringBuffer("abc"); I have created an object that is refering to an address. Now when i write str.append("xyz"); Hope it is still refering to the same address. Now this is the same thing that String does in my example. so how could u say that String is immutable and StringBuffer is immutable?? U may ... |
class abc{public static void main(String args[]){String x = "Test";x = x + "Test";System.out.println(x); }}output "TestTest"x has changed !" strings are immutable "..... is it true ? You've really created a new string here and changed "x" to reference this new string : class abc { public static void main(String args[]) { String x = "Test"; x = x + "Test"; System.out.println(x); ... |
== compares the actual "reference value" (think of it as the "objects" memory address) .equals compares the Strings contents. When you use a literal string in your class, a single object is created and placed into the String pool, and every time a reference is made to this String literal, the same reference value is used. So, when multiple variables are ... |
|
|
After concat also, that "Hello" reference, which is referenced by st2 will not be changed. if we execute another statement with the above like st2 = "bye"; now that "Hello" reference will be deleted and new reference to String with content "bye" will be allocated. So now totally two references will be available. |
I'm not entirely sure why, but I know that it's not because of that. It's most likely a combination of efficiency and simplicity. Strings are used a lot, and certain optimizations can be applied if we know they're immutable. Your code is also simpler if you know that a String you're passing around won't be moified. |
|
consider string s when u say "string s;".......that becomes a reference... now wen u say s="test"....it creates an object(u need not say new String for this class) now if u say ..... s="test22" the reference of s now points to test22 and the earlier refernce of test is soon garbage collected... StringBuffer is mutable ....coz u can append to it or ... |