This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 8 years ago.
I have written this code in eclipse:
String[] s = {"a","b"};
String d = "a";
System.out.println(s[0]==d);
and it is giving "true" as output.
"==" checks for object reference, if both object refer to same object, but here in this case object "d" refers to different object and "s[0]" to different, then how come they are equal.
"a" will have been created in the string pool used by the JVM.
As an optimisation only one instance of that string will have been created. Java can do this since strings are immutable. That's why the references are referencing the same underlying object, so in this particular instances, the references compare equal.
Related
This question already has answers here:
A Set in java never allows duplicates, but it takes StringBuffer objects with the same argument. Why?
(6 answers)
String Vs Stringbuffer as HashMap key
(4 answers)
Can a StringBuffer be used as a key in a HashMap?
(4 answers)
Closed 5 years ago.
I have made a Hashset of StringBuilder.
The below code returns "true" even if that StringBuilder is present in Hashset:
if(!contains(sb_obj))
{
...
}
Also I have made a ArrayList of StringBuilder.
The below code returns "-1" even if ArrayList contains obj:
if(arr.indexOf(obj)==-1)
{
....
}
Why such behaviour?
I assume you are comparing different StringBuilder objects that have the same String values.
StringBuilder doesn't override equals and hashCode methods. This causes HashSet and ArrayList to use Object's implementation of them which compares by identity. Since you are comparing different objects they are different.
Please use String instead of storing StringBuilder object or if you want to store custom object override hashcode and equals methods whenever you are trying to add and search back that object.
Please read the concept of hascode and equals method, you can find many examples over internet.
This question already has answers here:
What is the difference between a variable, object, and reference? [duplicate]
(5 answers)
Closed 6 years ago.
Is there any difference between the two TreeSets ?:
Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();
Difference is s have acccess to method shared by s type (if you don't cast it). But the object real type is the same.
Calling new HashSet<String>() will always create an empty HashSet. While these are all different instances, they are equal, regardless of whether you assign them to a HashSet, a Set or even a plain old Object.
Note, however, that HashSet is not a SortedSet, and the second statement in the question will cause a compilation error.
Only their apparent type is different. Since their real type is the same, their behavior will be identical.
It's similar to:
Integer i = 42;
Object o = i;
String s1 = i.toString(); // "42"
String s2 = o.toString(); // "42"
This question already has answers here:
Java's final vs. C++'s const
(11 answers)
Closed 6 years ago.
I know that Java uses "final" to declare a constant and that c uses "const". Just wondering what the differences are between the two.
In java, making something final means that it can't be reasigned to another reference to another instance, but if it's a reference to a mutable class, the mutable values inside the class can still be modified.
For example, a final String is a constant because Strings are immutable in Java, but a final ArrayList means that you cannot assign it to another ArrayList, but you can still add and remove elements to that ArrayList
This question already has answers here:
Immutability of Strings in Java
(26 answers)
Closed 9 years ago.
From the oracle doc
String is immutable also Strings are constant; their values
cannot be changed after they are created. and because they are
immutable they can be shared. String buffers support mutable strings.
but I can always do the following:
String name="SO";
name="SE";
I can change the value so how can it be immutable and it is said that for security reason also like database connectivity etc..
Pardon me for asking such basic question but I need to understand.
name="SE" by doing this, you are changing the value of name variable, not the String object SO itself. String are immutable in the sense, String object SO can't be modified once created. By doing name = name+"TEST"; there will be a new String object SOTEST created in the memory, not existing String object SO will be modified.
For further details look here and here. There are lot of example and explanation.
Yes, you can change the string your name variable points to. But let's see what happens when you execute the following code sequence:
String name = "SO"; //line 1
name = "SE"; //line 2
At line 1: a new String object is created, that holds the value "SO";
At line 2: a new String object is created, that holds the value "SE"; your name variable value changes, in that it points to another reference, which is the second String object; the first String object ("SO") is still on the heap, but is not referenced anymore and is made available for future garbage collections, if any.
What you have to understand here is that, as soon as the String object containing the char sequence {'S', 'O'} is constructed, the char sequence wrapped by that String object could never change again. E.g. you cannot make that object wrap the char sequence {'S', 'E'}. That's what immutability is all about.
In the example you provide you have created two Strings. First a String SO is created and the reference is assigned to name. Then a new String is created, SE and that reference is assigned to name. You never actually modified the first String that was created.
String temp = "SO";
String name = temp;
name = "SE";
System.out.println(temp.equals("SO")); //prints true;
System.out.println(temp == name); //compares references prints false
When you change value of your String reference, you in fact create new object.And your reference now is linked to this new object.
String myValue = "old"; -> VM creates String object "old"
myValue = "new"; -> VM created String object "new"; "old" object still exists but any reference is linked to this, so we can say : "old" is lost
See for example the below image from the internet:
The big cloud is the heap where objects are being stored, s is the reference to the object (in your question you are using name as the reference)
When you do s = "abcd" a new object is created in the heap, and s is a reference to it. (Like the top arrow shows)
The important bit:
When you then do something like s = "abcdef" or s = s + "ef" the immutable string object "abcd" cannot be changed and so a new object is created and s loses it's reference to the old string (shown by dotted line) and now references the new String (Shown by the bottom arrow).
The old object I would assume is picked up by Garbage Collector at some point.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between “text” and new String(“text”) in Java?
Please explain the brief and detailed difference between following 2 statements:
String a= "somevalue";
String b = new String("somevalue");
I know that 2nd statement creates and provide memory to String Object b in heap. But why object a doesn't get memory and its still allowed to operate on string methods.
a and b are references to Objects, not Objects.
When you do a = b; it doesn't copy the Object, it copies a reference to an Object.
A String has a char[] inside it which is another object.
a gets an reference to an existing object so it may not need any extra memory.
b get a reference to a newly created object so that requires more memory.
its still allowed to operate on string methods.
This has nothing to do with how the object was created.
The first affects the literal String object "somvalue" to variable a. This literal String object is cached in a pool, as all literal Strings.
The second creates a new instance of empty String. Since String instances are immutable, it's equivalent to String b = "";, except it instantiates a new object for nothing.