This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?
I know that String s = new String("Hello World") should be avoided as it will create extra space for "Hello World" which is unnecessary in most cases.
Related question explaining why String s = new String("Hello World")should be avoided is here:
What is the difference between "text" and new String("text")?
But when do we need to use String s = new String("Hello World"), instead of String s = "Hello World"? This is a interview question I experienced.
If String s = new String("Hello World")should be avoided in most cases, why Java still allows that?
1) String s = "text";
This syntax will allocate memory for "text" in heap. and each time when you will assign this "text" to other variable it will return the same memory reference to each time.
for Exp -
String aa = "text";
String bb = "text";
if(aa == bb){
System.out.println("yes");
} else {
System.out.println("No");
}
will print - Yes
but
String s = new String("text");
Always create a new location in memory and returns a new reference each time.
for Exp -
String aa = new String ("text");
String bb = new String ("text");
if(aa == bb){
System.out.println("yes");
} else {
System.out.println("No");
}
will print - No
Related
This question already has answers here:
What is the purpose of the expression "new String(...)" in Java?
(9 answers)
Use of the String(String) constructor in Java [duplicate]
(6 answers)
Closed 4 years ago.
What is the difference between
String name1 = "some name";
and
String name1 = new String("some name")
Which is better and good for use?
thanks
Generally use String name1 = "some name";
But, if you want that strings to has different references, use new initialization.
Java has some optimization about strings. = "" initilizations checks string pool if same value initialized before.
String s1 = "test";
String s2 = "test";
String s3 = new String("test");
s1 == s2 // this is true because of string pool
s1 == s3 // this is false because of s3 is new instance
In the above example, s1 and s2 placed at string pool s3 is outside of java string pool.
Using new String causes creation new instances and more memory consuption.
Take a look for more information about string pool : https://www.journaldev.com/797/what-is-java-string-pool
This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 8 years ago.
String a = "Hello";
String b = new String("Hello World");
Can someone please tell me how many objects are created and elaborate.
Thank you.
String greeting = "Hello world!";
In this case, "Hello world!" is a
string literal—a series of characters in your code that is enclosed in
double quotes. Whenever it encounters a string literal in your code,
the compiler creates a String object with its value—in this case,
Hello world!.
String a = "Hello"; // 1 object
String b = new String("Hello World");
// 1 object with new String(),
// 1 object with "Hello World"
in total you created 3 objecs.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I know that we shouldn't compare Strings with == and its better to use equals.
For so far I learned this should all be false.
So why does the first method return true?
private String ab = "AB";
private String ab2 = "A" + "B";
private String a = "A";
private String b = "B";
private String ab3 = a + b;
public void test () {
System.out.println("ab == ab2" + ab==ab2);
System.out.println("ab == ab3" + ab==ab3);
System.out.println("ab == a+b" + ab==(a+b));
}
Because the concatenation of literal Strings are compiled into a single String, which will also be interned in the String pool. This code:
private String ab2 = "A" + "B";
is compiled to
private String ab2 = "AB";
ab and ab2 point to the same literal String "AB", thus they're ==s.
Still, you should not trust comparison of Strings with ==, you should always compare their equality using equals method.
It is called String interning:
http://en.wikipedia.org/wiki/String_interning
To summarize, since strings are immutable in Java, JVM optimizes by creating only one object for two string literals that are equal. Therefore, comparison returns true.
This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed 9 years ago.
Java Question: Suppose str is a String variable. The statement str = new String("Hello World"); is equivalent to ?
Here are my choices...
a.
new String = "Hello World";
c.
str = "Hello World";
b.
String new = "Hello World";
d.
"Hello World";
It's equivalent to declaring and initializing it at once:
String str = new String("Hello World");
You don't need to do new String("...") though. You already have a String literal. You can just do:
String str = "Hello World";
Otherwise, you're taking the first, canonical String object ("Hello World") and unnecessarily using it to initialize a second object (new String(...)) with the same text.
Edit: According to the choices you've posted now, it's not exactly equivalent to any of them. As explained in more detail by the other answers, "Hello World" has a subtle (yet important) difference to new String("Hello World"), so it is not exactly equivalent to str = "Hello World". On the other hand, the other three options don't compile at all, so that is certainly the intended answer.
Lots of answer get it right about internalization. Take this program:
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
String str4 = "He";
System.out.println(str1 == str2); // true
System.out.println(str1 == str3); // false
System.out.println(str1 == str3.intern()); // true
str4 = str4.concat("llo");
System.out.println(str1 == str4.intern()); // true
}
The interesting issues are point 2 and 3. new always creates a new object (as per JLS 12.5), so str1 != str3. What happens with internalization is that the new object points to the internalized one, which you can retrieve with String.intern(). Similarly, another String created in a form completely unrelated to the original literals (str4) also gets "interned".
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java String concatenation
Sources tell us that concat is implemented as follows:
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
Does + implementation differ when it comes to Strings? How? Is there a performance difference between + and concat. When should one be chosen over another?
This is a test I just made:
I created a class with those 3 instructions:
String s1 = "foo";
String s2 = "bar";
String s3 = s1 + s2;
Then I took the generated .class file and I decompiled using JAD decompiler.
This is how the code show up in the regenerated source:
String s = "foo";
String s1 = "bar";
String s2 = (new StringBuilder()).append(s).append(s1).toString();
So: this is the difference between + and concat.
I guess concat() is always better than StringBuilder, because it requires less objects to be created. You may chose StringBuilder if you want to append string repeatedly in a loop; in this case concat may create a new String each time, while StringBuilder may just expand the internal buffer. But, if StringBuilder is best in this last scenario, we can say that still concat() is better than +, in loops.