This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Immutability of Strings in Java
(26 answers)
Closed 5 years ago.
I have the following code
public static void main(String[] args) {
String word = "Super";
reverseString(word);
System.out.println(word);
}
public static String reverseString(String word) {
String helper = "";
int i = word.length() - 1;
while (i >= 0) {
helper += word.charAt(i);
i--;
}
return helper;
I do not understand why when I'm printing the "word" variable it still prints "Super" even though I changed it in the reverseString method. I understand that strings are passed by reference and not a copy like primitive values.
If I do word = reverseString(word) it prints the reverse what I expect, "repuS"
Thanks
You're not changing the string in reverseString, you're creating a new one and returning the new one (which you've called helper).
A second thing to note about strings in Java is that they're immutable - all string methods return a new string rather than modifying the one you're calling the method on.
Related
This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
How do I compare strings in Java?
(23 answers)
how equals method works in java
(1 answer)
String pool vs Constant pool
(3 answers)
Strange String pool behavior
(4 answers)
Closed 5 years ago.
public static void main(String[] args) {
String[] arr = new String[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = "aaa" + i;
}
System.out.println(arr[0] == "aaa0"); // false
String s = "aaa0";
System.out.println(s == arr[0]); // false
}
I have a few question regarding the topic could help me to understand
What are logins behind the fact that String from string arrays don't automatically go to Sting pool, unlike string literals?
Do I correctly understand that only string literals go to the String pool implicitly ?
Do I correctly understand that string array from public static void main ( public static void main(String[] args) ) is not go to the String pool too ?
The compiler transforms that for loop under the covers!
And the resulting bytecode will use a new StringBuilder for each loop iteration... Resulting in "newly" created string objects!
Meaning; in "reality; your loop looks "more" like:
for (int i = 0; i < arr.length; i++) {
StringBuilder builder = new StringBuilder("aaa");
builder.append(i);
arr[i] = builder.toString();
}
(see here on the theoretical background)
That is one of the reasons that using == to compare strings has such a bad reputation... As it tends to lead to unexpected results.
And regarding your comment: the point is not the array you are using (where: you should not be writing into the array passed to main - you can, but it is bad practice).
You can call the intern() method to enforce String pooling, i.e. to store only one copy of each distinct string value.
Check this out:
public static void main(String[] args) {
String[] arr = new String[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = ("aaa" + i).intern();
}
System.out.println(arr[0] == "aaa0");
String s = "aaa0";
System.out.println(s == arr[0]);
}
Use equals() if you want to compare THE CONTENT of two objects. Here are more of an explication
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it
checks to see if the objects refer to the same place in memory. In
other words, it checks to see if the 2 object names are basically
references to the same memory location.
The equals() method
The equals method is defined in the Object class, from which every
class is either a direct or indirect descendant. By default, the
equals() method actually behaves the same as the “==” operator –
meaning it checks to see if both objects reference the same place in
memory. But, the equals method is actually meant to compare the
contents of 2 objects, and not their location in memory.
System.out.println(arr[0].equals("aaa0")); // It give you True
System.out.println(s == arr[0]); // It give you false
This question already has answers here:
Immutability of Strings in Java
(26 answers)
Closed 6 years ago.
If a String object is immutable then why is it printing "Help"?
The String object s1 shouldn't be modified according to its immutability feature. I am confused for years, please help me understand this:
Code
public static void main(String[] args) {
String s1 = "Hello";
s1 = "Help";
System.out.println(s1);
}
Output
Help
Your second assignment actually is changing the String that s1 references.
There is still a String of "Hello" in existence (in the pool) which cannot be changed.
The behavior you described would be achieved by making s1 final - in which case you would get a compiler error if you tried to change the value the String s1 references.
This question already has answers here:
Java int to String - Integer.toString(i) vs new Integer(i).toString()
(11 answers)
Closed 6 years ago.
I enjoy CodeFights at the moment and at the end of my last fight i found something interesting. The code in those two cases (mine and the opponent) was said to be correct. Is there a difference between this source code:
return Integer.toString(Character.getNumericValue(ch1) + Character.getNumericValue(ch2));
and this one:
return new Integer(Character.getNumericValue(ch1)+ Character.getNumericValue(ch2)).toString();
What is the key that i am missing?
From javadoc https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
String toString()
Returns a String object representing this Integer's value.
static String toString(int i)
Returns a String object representing the specified integer.
Integer's toString method is implemented as Integer.toString(value), so the second answer merely has a redundant instantiation.
#Override
public String toString() {
return Integer.toString(value);
}
This question already has answers here:
What is Java String interning?
(8 answers)
Closed 6 years ago.
How does Java decide when a new String should be created?
I assume it depends on the specific JVM implementation/ compiler, but I thought the results of this test were interesting enough to ask the question:
class A { public String test = "test";}
class B { public String test = "test";}
...
public static void main (String[] args)
{
String test = "test";
System.out.println(test == "test"); // true
System.out.println(test == new String("test")); // false
System.out.println(new A().test == new B().test); // true
}
String literals are always interned, this is not directly platform-dependent.
Except when using the explicit initialization idiom through the constructor (new String(someString)).
In that case, a new Object is created, which causes the reference equality operator (==) to return false in your example.
Needless to say, always use equals for reliable String value comparison, but I suspect this falls out of your question's scope.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public static void main(String[] args) {
Integer i = new Integer(4);
System.out.println(i.toString());
if (i.toString() == i.toString()) {
System.out.println("true how");
} else {
System.out.println("false how");
}
}
While executing above code, I am getting output as "false how".
Can you explain how Jvm treats this object?
toString() creates a new string object every time and your code is actually checking if both references are the same, which is never the case so it runs the else case. If you try
i.toString().equals(i.toString())
you'll get the desired output.
You must compare objects with equals() method.
i.toString().equals(i.toString())