What is the difference between "ABC" and new String("ABC")? [duplicate] - java

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 8 years ago.
What is difference between String str = "ABC" and String str = new String("ABC")?

String
In Java String is a special object and allows you to create a new String without necessarily doing new String("ABC"). However String s = "ABC" and String s = new String("ABC") is not the same operation.
From the javadoc for new String(String original):
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; [...]
Unless an explicit copy of original is needed, use of this constructor
is unnecessary since Strings are immutable.
In other words doing String s = new String("ABC") creates a new instance of String, while String s = "ABC" reuse, if available, an instance of the String Constant Pool.
String Constant Pool
The String Constant Pool is where the collection of references to String objects are placed.
String s = "prasad" creates a new reference only if there isn't another one available. You can easily see that by using the == operator.
String s = "prasad";
String s2 = "prasad";
System.out.println(s == s2); // true
Image taken from thejavageek.com.
new String("prasad") always create a new reference, in other words s and s2 from the example below will have the same value but won't be the same object.
String s = "prasad";
String s2 = new String("prasad");
System.out.println(s == s2); // false
Image taken from thejavageek.com.

Related

java "== " unusual behaviour [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
== and .equals() not working in java [duplicate]
(1 answer)
Closed 6 years ago.
import java.lang.String;
public class Test {
public static void main(String[] args) {
String a1="ka";
String a2="ka";
System.out.println("a1==a2? "+(a1==a2));
String a3="k";
String a4=new String("k");
System.out.println("a3==a4? "+(a3==a4))
System.out.println("a3==a4? "+(a3==a4.intern()));
String a5="k";
String a6=a4+"a";
System.out.println("a1==a6? "+(a1==a6));
}
}
Output that i got:
a1==a2? true
a3==a4? false
a3==a4? true
a1==a6? false
a1===a2 is true as line 5 will not create new String literal in string pool area.Only reference to previously created string is returned.
a3==a4? false as a4 will have refernce to the String object instead of the string in the string in string pool area. My question is if a3 is referencing the string constant instead of the String object, how is it able to use the methods of the String class?
a4.intern() will return the reference to the string in the string pool which happens to be same as a3
a6=a4+"a" will create a new string "ka". But this actually make use of StringBuilder class and its append method . It is then converted to string using toString(). Does this process store the newly created string "ka" in the string pool area? Since the string is already in the pool the code at line 12 should return the reference to it. So the a1==a6 should be true.rt?
I am new to java. Please guide me where i am doing the mistake?
You are comparing the Strings wrongly (because you are in fact comparing references)
String Class in java is defined in java.lang package and it is exactly that, a class and not a primitive like int or boolean.
String is immutable and final in Java and in this case JVM uses String Pool to store all the String objects.
What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes (literal assignment) to create a String object.
To your Question:
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
So when you do
String s1 = "abc";
String s2 = "abc";
those are checked in the StringPool and since s1 already exist there, s2 will take the same reference, hence, s1 ==s2 is true.
but when you do:
String s3 = new String("abc");
String s4 = new String("abc");
you are using the new operator, therefore the JVM is not checking if there is an string already in the heap, it will just allocate a new space for s4, so is s3==s4 ??? of course no.
Please take a look at the image below for a more illustrative example.

Java Strings Confusion [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
if (s1 == s2) is giving true
while (s3 == s4) is giving false.
Can somebody give a detailed explanation onto what is String pool, heap, how many objects are created in each line and how many objects created in total.
Why s3==s4 is giving false?
A detailed explanation will be much appreciated.
When you do new String(...), it is evaluated at runtime and hence creates two different instances and you end up getting s3 == s4 as false. Same thing happens when you use StringBuilder and do something like sb.toString() which is again evaluated at runtime.
For Example,
StringBuilder sb = new StringBuilder();
String foo = sb.append("abc").toString();
String bar = new String("abc");
String foobar = "abc";
Here foo, bar and foobar are all different objects and hence foo == bar or foo == foobar will evaluate to false.
On the other hand s1 == s2 returns true because abc one declared, already exists in the String Pool and in this case both the objects points to the same reference in the pool.
String Class in java is defined in java.lang package and it is exactly that, a class and not a primitive like int or boolean.
Strings are developed to offer operations with many characters ans are commmonly used in almost all the Java applications
Some interesting facts about Java and Strings:
String in immutable and final in Java and in this case JVM uses String Pool to store all the String objects.
What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes (literal assignment) to create a String object.
There are too several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilderetc etc.
To your Question:
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
So when you do
String s1 = "abc";
String s2 = "abc";
those are checked in the StringPool and since s1 already exist there, s2 will take the same reference, hence, s1 ==s2 is true.
but when you do:
String s3 = new String("abc");
String s4 = new String("abc");
you are using the new operator, therefore the JVM is not checking if there is an string already in the heap, it will just allocate a new space for s4, so is s3==s4 ??? of course no.
Please take a look at the image below for a more illustrative example.

why strings are showing different behaviour during concatenation? [duplicate]

This question already has answers here:
How to Compare strings in java [duplicate]
(6 answers)
Closed 7 years ago.
String a = "x";
String b = "x";
System.out.println(a==b);
It prints "true" as it shares the same memory in String constant pool. But when I write the following code,
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);
Its printing false.
I know '==' compares the instances.
My Question is - why instance is not same in the second scenario. When creating a new String, It always checks whether the same string is available in the pool or not. Then after creating String b i.e. "xy" is available in the pool. So when I'm trying to create String c with the same "xy", it should not create new instance. It should share the same memory rather than creating a new instance. Then, Why in the second scenario the instances are different??
here, a + "y" creates a new String object hence, == returns false. It checks for object references and not object equality.
When comparing strings, you should use the equals method.
== operator checks whether both references variable refer to same object
equals() method checks there the contents of objects are same
Learn the difference between == operator and equals method in case of strings
Problem is String is immutable, every update operation on string results into new string, and the == check the instance and not its value in case of class types.
Try final:
final String b = a + "y";
or use equals():
System.out.println(b.equals(c));
Edited:
String literals are directly available in string pool it is not same in this case String b = a + "y", here its in heap. You can use intern() to make it available in string pool.
String b = (a + "y").intern();
System.out.println(a==b);//true
This might work, and the explanation for why can be found here.
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b.equals(c));

java string with new operator and a literal

Suppose we create a String s as below
String s = new String("Java");
so this above declaration will create a new object as the new operator is encountered.
Suppose in the same program if we declare a new String s1 as below :
String s1 = "Java";
Will this create a new object or will it point to the old object with Java as it is already created with new operator above.
Well, the second line won't create a new object, because you've already used the same string constant in the first line - but s1 and s will still refer to different objects.
The reason the second line won't create a new object is that string constant are pooled - if you use the same string constant multiple times, they're all resolved to the same string. There still has to be a String object allocated at some point, of course - but there'll only be one object for all uses. For example, consider this code:
int x = 0;
for (int i = 0; i < 1000000; i++) {
String text = "Foo";
x += text.length();
}
This will not create a million strings - the value of text will be the same on every iteration of the loop, referring to the same object each time.
But if you deliberately create a new String, that will definitely create a new object - just based on the data in the existing one. So for example:
String a = new String("test");
String b = new String("test");
String x = "test";
String y = "test";
// Deliberately using == rather than equals, to check reference equality
System.out.println(a == b); // false
System.out.println(a == x); // false
System.out.println(x == y); // true
Or to put it another way, the first four lines above are broadly equivalent to:
String literal = "test";
String a = new String(literal);
String b = new String(literal);
String x = literal;
String y = literal;
String myString = new String("Java");
creates two objects.
String myString = "Java";
creates one object.
In order to create a new object we use new keyword, Object cannot be created without using new.
As per the declaration in the first instance a new Object is created but in the second instance you are only declaring a variable with a value.
So its not an Object.
String s1="foo"; literal will be created in StringPool.
String s2="foo"; this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal as s1.
String s3=new String("foo"); "foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.
When you create a String with literal (e.g. String str = "Hello";) the Object is not created in Heap it will be available in StringPool only, however when you create a String using 'new' operator (e.g. String str = new String("Hello")) then the Object in StringPool is created along with one more object in Heap. So we are creating two objects unnecessarily. So string creating with literal is preferred way.

Diff bet new String("xyz") and "xyz" in Java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
difference between string object and string literal
Hello,
Foremost, let’s come up with Java facts with String
Strings are immutable
My Question - If Strings are immutable then below statement should have compilation error!
String str = "xyz";
or
String str = new String("xyz");
str = "abc"; //COMPILATION ERROR
or
str = new String("abc"); //COMPILATION ERROR
What is the difference between below instantiation ?
String str = "xyz";
and
String str = new String("xyz");
Amit.
Strings are immutable means you can't do something like str[1] = 'x' i.e you cannot change the content of the string.
This will answer your second question.
Strings are immutable, so you cannot change the contents of a string.
In the following code:
String str = "xyz";
str = "abc";
you're not changing the contents of a String instance, but rather assigning a new String instance to the variable str. That is, if you do:
String str = "xyz";
String otherStr = str;
String str = "abc";
Then otherStr will remain the same. So you're not actually changing the object that str points to.
As for your second question
String str = "xyz";
takes the a String-object with value "xyz" from the String pool, while
String str = new String("xyz");
instantiates a new object.
That is, if you do
String a = "xyz", b = "xyz";
you will have a == b, while if you do
String a = new String("xyz"), b = new String("xyz");
this will not be the case.example
For more information, see:
What is String literal pool?
Questions about Java's String pool
Strings are immutable. String references are not. That's the distinction.
So:
String str = "abc";
str is a variable, referring to an immutable string "abc". Now if I do:
str = "def";
str is still a variable, referring to a different immutable string ("def"). I can change what str points to all I want, str is a variable. I can't change the actual content of any string (because Java's strings are immutable, by design). Whenever you do something that would seem to modify the string (say, toUpperCase), what it's actually doing is creating a new string with a copy of the old string's contents, modified in the way described.
The point of having strings be immutable is that I know that if I have a reference to a string, that string can never change. This is a very useful guarantee when passing strings around. If we didn't have this guarantee, we'd be copying strings all the time just to protect ourselves from someone modifying them. For instance, consider a standard setter function for a name property:
void setName(String n) {
this.name = n;
}
If strings weren't immutable, we'd have to do this:
void setName(String n) {
this.name = new String(n); // Blech, duplication
}
...so that we know our copy of the string won't change in ways we don't expect it to. This would result in a lot of duplication of string data in memory, most of it unnecessary, and so the designers of Java quite intelligently decided that strings would be immutable, and any changes you might want would create a new string rather than modifying the old one in-place. (You can get modify-in-place behavior for those situations that really warrant it by using char[] instead.)
Regarding your separate question about the difference between str = "abc"; and str = new String("abc"), the difference is that the latter (using the constructor) is guaranteed to return a new reference, whereas the former is not. E.g.:
String a = "abc";
String b = "abc";
String c = new String("abc");
a == b (checking whether the references match, not the strings) will be true, because literal strings are interned. a == c is guaranteed to be false, because we used the constructor for c. a.equals(b) and a.equals(c) will both be true, because a, b, and c all refer to equivalent strings.
If Strings are immutable then below
statement should have compilation
error!
You are misunderstanding the immutability concept. Look at Prasoon's answer.
String immutability means you cannot alter the contents inside the string.
String a = "hello";
String b = "hello";
System.out.println(a==b); // returns true.
Here both a and b both string literals refer the same object.
What is the difference between two
instantiations ?
String a = "hello";
String b = "hello";
System.out.println(a==b); // returns true.
Both refer to same String literal.
String a = new String("hello");
String b = new String("hello");
System.out.println(a==b); // returns false.
Two different String Objects are created.
String str = "xyz";
is an internal cached string instance.
String str = new String("xyz");
is a new object not instanciated from the cache
As side fact notice the following behaviour ...
"xyz" == "xyz" evals true
new String("xyz") == new String("xyz") evals false
new String("xyz").equals(new String("xyz")) evals true
notice also that == in Java compares object references.

Categories