This question already has answers here:
String can't change. But int, char can change
(7 answers)
Closed 9 years ago.
String s1 = "ABC";
s1.replace("ABC","abc");
print(s1); // prints ABC as output
s1 = s1.replace("ABC","abc");
print(s1); //prints abc
What's the difference between two replace statements?
What happens internally when the first replace statement is called?
String.replace(CharSequence first, CharSequence second) returns a new String reference and this is why the output is different.
In the first replace line you're not assigning the resulting String to anything, whereas in the second you're replacing the reference of s1 with the result of the replacement.
s1.replace("ABC","abc"); doesn't replace on s1. It gives output of the replaced string.
$s2 = s1.replace("ABC","abc");;
print($s1); // prints ABC
print ($s2); // prints abc
Strings are immutable. It means changes are not made directly into them instead a copy of the string is created and it is changed and the reference of the changed one is returned. If you do not accept the new reference you will find the old string unchanged.
Read the API and the Java tutorials... String can NEVER be changed. That means all its methods will return a new object and your reference will still point to the old one. To assign the return to your reference, you have to assign it as in
s1 = s1.replace("ABC","abc");
Be careful with that! Quite tricky ;)
If you will change the String a lot, use StringBuffer instead... There your appends, replaces, etc have effect in the object referenced by your variable.
String.replace() Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Code of String.replace
When you do s1.replace("ABC", "abc") imagine that in that place new string abc is created and not assigned to anything. But with s1=s1.replace("ABC", "abc") you create new string abc and assign it to the s1 variable replacing old value.
Related
This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 6 years ago.
In my computer science class we were discussing null and values when we came across a predicament. We could not figure out the value of simply 2 quotes with no space as "". Just wondering if anyone would know what the exact value of "". Thanks
It's the empty String. JLS-3.10.5. String Literals says A string literal consists of zero or more characters enclosed in double quotes. And, then includes this example
The following are examples of string literals:
"" // the empty string
As Java String(s) are immutable, it has a constant length of 0 and stores a sequence of 0 characters.
When you initialize it with null like this:
String s1 = null;
It means that no object is assigned to variable s1. However, when you initialize it with empty String like this:
String s2 = "";
It means that a String object is assigned to s2 (although empty).
Now if you want to perform any operation, let's say you want to call the .equals(..) method of string, then it will throw NullPointerException in the former case as there is not String object. However, it will work fine in latter because there is an object there, it doesn't matter whether it's empty or not
s1.equals("something"); // throws NullPointerException
s2.equals("something"); // works fine
I am reading from a file line by line and then I want to check if that string contains another string so I use String.contains method but it returns always false.
I have tried to split the input line (and then using String.contains or String.equals) since the word to be checked is the first of the line.
The string I want to check is <now> and doing the splitting I have noticed that even when the line contains it I get false.
The strange fact is the string is printed out correctly but its length is bigger than the string <now>(even if I used replace to be sure there were no spaces) and I guess that is my problem. I am thinking it depends on the encoding of file but if so, is there any solution?
The file is the output of another Program (Praat) so I can not save it in another way.
line = inFile2.nextLine();
String[] w = line.split("[\t\\s]");
String checking = w[0];
checking.replace(" ","");
checking.replace("/t","");
String st ="<now>";
System.out.println(!checking.equals(st)); //returns always true
System.out.println(st.length()); //returns 5
System.out.println(checking.length()); //returns 11
System.out.println(checking); //it prints <now> correctly
The string in input is like: <now> 236 62 elena information-relation
Strings are immutable :
Note: The String class is immutable, so that once it is created a
String object cannot be changed. The String class has a number of
methods, some of which will be discussed below, that appear to modify
strings. Since strings are immutable, what these methods really do is
create and return a new string that contains the result of the
operation.
So it should be :
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
Or even better (method chaining) :
Checking = Checking.replace(" ","").replace("/t","");
Also please respect naming conventions.
String is immutable so you need to assign.
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
To make it shorter you can also do this:
String Checking = W[0].replace(" ", "").replace("/t", "");
Of course this depends on your preferences.
I solved re-saving the text file using UTF-8 encoding.
Say I have a string, String x = "oncetherewasaboy";
I want to replace "there" with "". I tried x.replace("there",""); But this does not remove it. This is not the best example but I am doing it for an array of strings and want to clean and filter some of the information inside each index with "". Thanks!
Strings are immutable. Calling replace() doesn't change the string. It creates a new one, and returns it. You need to save the reference to it in a variable, or else you can't access it. You need:
x = x.replace("there", "");
String is an immutable Type. An immutable object is an object whose state cannot be modified after it is created. So you can not modify the string x.
So as you can not modify the string, the replace method returns a new string with the new changes. So as jlordo has already suggested you need to use like following
x = x.replace("there", "");
I have some question that I wonder about. I know that string are immutable in Java and therefore a new string object is created rather than changed when for example assigning to a existing string object.
Now to my question. Let's suppose that I have the following piece of code:
String a = "Hello World";
String b = "Hello World";
String res = a.substring(0,4) + b.substring(6,10);
How many string objects will be created by the code at line 3 ? Will each call to substring create a new string object ? Will my code above generate 3 new string objects ?
Thanks in advance
Strings in Java are immutable. Basically this means that, once you create a string object, you won't be able to modify/change the content of a string. As a result, if you perform any manipulation on a string object which "appears to" change the content of the string, Java creates a new string object, and performs the manipulation on the newly created one.
Based on this, your code above appears to create five string objects - two are created by the declaration, two are created by calls to substring, and the last one is created after you concatenate the two pieces.
Immutability however leads to another interesting consequence. JVM internally maintains something like a string pool for creating string literals. For saving up memory, JVM will try to use string objects from this pool. Whenever you create a new string literal, JVM will loop into the pool to see if any existing strings can be used. If there is, JVM will simply use it and return it.
So, technically, before Java 7, JVM will create only one string object for your whole code. Even your substring calls won't create new string objects in the pool, it will use the existing "Hello World" one, but in this case it will only use characters from position 0 to 3 for your first call to substring, for example. Starting from Java 7, substring will not share the characters, but will create a new one. So, total object count will be 4 - the last one will be created with the concatenation of the two substrings.
Edit
To answer your question in the comment, take a look at Java Language Specification -
In the Java programming language, unlike C, an array of char is not a
String, and neither a String nor an array of char is terminated by
'\u0000' (the NUL character).
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.
So, no, char arrays are not immutable in Java, they are mutable.
Literal a is created newly and kept in the pool.Literal b refer the a, it will not create new one instead.
The line 3 will create 3 new String since substring creates a new string and concatenate creates new Strings every time.
String substring(int beginIndex,int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
OK, this is the line I am working on:
newstring.charAt(w) += p;
trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?
Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.
If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.
Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.
Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -
str = str.substring(0, w) + "p" + str.substring(w);
But, of course, using StringBuilder as specified in #biziclop's answer is the best approach you can follow.