Shouldn't I do `String s = new String(a new string);` in Java, even with automatic string interning?
String a = "foo"; // this string will be interned
String b = "foo"; // interned to the same string as a
boolean c = a == b; //this will be true
String d = new String(a); // this creates a new non-interned String
boolean e = a == d; // this will be false
String f = "f";
String g = "oo";
String h = f + g; //this creates a new non-interned string
boolean i = h == a // this will be false
File fi = ...;
BufferedReader br = ...;
String j = br.readLine();
boolean k = a == j; // this will always be false. Data that you've read it is not automatically interned
What is the difference between text and new String(text)?
new String("text");
explicitly creates a new and referentially distinct instance of a String
object; String s = "text";
may reuse an instance from the string constant pool if one is available.
You very rarely would ever want to use the new String(anotherString)
constructor. From the API:
String(String original)
: Initializes a newly createdString
object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since strings are immutable.
Related questions
- Java Strings: “String s = new String(”silly“);”
- Strings are objects in Java, so why don’t we use ‘new’ to create them?
What referential distinction means
Examine the following snippet:
String s1 = "foobar";
String s2 = "foobar";
System.out.println(s1 == s2); // true
s2 = new String("foobar");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
==
on two reference types is a reference identity comparison. Two objects that are equals
are not necessarily ==
. It is usually wrong to use ==
on reference types; most of the time equals
need to be used instead.
Nonetheless, if for whatever reason you need to create two equals
but not ==
string, you can use the new String(anotherString)
constructor. It needs to be said again, however, that this is very peculiar, and is rarely the intention.
References
- JLS 15.21.3 Reference Equality Operators == and !=
class Object
-boolean Object(equals)
Related issues
- Java String.equals versus ==
- How do I compare strings in Java?
Java Different between String s1 = abc and String s1 = new String(abc)?
String s3 = "abc" String s4 = "abc"??
Those are literals. String
literals are stored in a common pool(shares of storage
for strings)
String objects creted via new operator are stored in the heap(no sharing).
s3==s4 //true
s3.equals(s4) //true
Read More:
How can a string be initialized using " "?
Where is the new Object of String created when we concat using + operator
First of all String s = new String("abs");
It will create two objects, one object in the pool area and another one in the non-pool area because you are using new and as well as a string literal as a parameter.
String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;
Till now you have five String objects, four in String Constant Pool and one in Heap. So your str4 is a new object altogether inside the String Pool,
Please check the below code also,
String str5="HelloWorld"; //This line will create one more String Constant Pool object because we are using the variable name as str5.
String str6="HelloWorld";////This line will not create any object, this will refer the same object str5.
For test
System.out.println(str3==str4); //false
System.out.println(str4==str5);//false
System.out.println(str5==str6);//true
What is the difference between ABC and 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.
Java: how to initialize String[]?
You need to initialize errorSoon
, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
You need to initialize the array so it can allocate the correct memory storage for the String
elements before you can start setting the index.
If you only declare the array (as you did) there is no memory allocated for the String
elements, but only a reference handle to errorSoon
, and will throw an error when you try to initialize a variable at any index.
As a side note, you could also initialize the String
array inside braces, { }
as so,
String[] errorSoon = {"Hello", "World"};
which is equivalent to
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
Related Topics
Reading a List from Properties File and Load with Spring Annotation @Value
Returning from a Finally Block in Java
Are Static Fields Open for Garbage Collection
How to Gracefully Handle the Sigkill Signal in Java
How to Find Files That Match a Wildcard String in Java
Regex Doesn't Work in String.Matches()
Generate/Get Xpath from Xml Node Java
Why Does Writeobject Throw Java.Io.Notserializableexception and How to Fix It
What Is an Outofmemoryerror and How to Debug and Fix It
Java: How to Start a Standalone Application from the Current One When Both Are in the Same Package
How to Create a Rest Client for Java
How to Get the File Extension of a File in Java
Which Is the Best Library for Xml Parsing in Java
.Toarray(New Myclass[0]) or .Toarray(New Myclass[Mylist.Size()])
How Will Java Lambda Functions Be Compiled
Jquery, Spring MVC @Requestbody and JSON - Making It Work Together