Java String declaration [duplicate] - java

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 2 years ago.
What is the difference between String str = new String("SOME") and String str="SOME"
Does these declarations gives performance variation.

String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.

There is a small difference between both.
Second declaration assignates the reference associated to the constant SOMEto the variable str
First declaration creates a new String having for value the value of the constant SOME and assignates its reference to the variable str.
In the first case, a second String has been created having the same value that SOME which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare transformed into the same instance, which uses far less memory.
As a consequence, always prefer second syntax.

String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable

First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.
Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.

Related

String Literal vs String Object [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 6 years ago.
I read a lot about String Literal vs String Object. I read that String literal is stored in a String pool and String object will create an object in the heap. I'm quite confused in an instance variable of a class that is initialized using "".
class A {
private String aStr = "ASTRING";
}
Will aStr will be added to String pool or will it create an object in the heap?
Whenever new Keyword is used then object is created in heap.
Here new Keyword is not used so string object is created in string pool.
For example:
String s1= new String("string object");
In the above example two objects are being created one is string object in string pool since it is in double quotes another is s1 which is created in heap as new keyword is used.
As Gaur93 said its true, but i would like to add some more points.
Lets take an example:
String s = "hello";
String s1 = new String("hello");
String objects are basically wrappers around string literals. Unique string objects are pooled to prevent unnecessary object creation, and the JVM decide to pool string literals internally.
When you use a literal, say
String str = "hello"
the object in the pool is used. If you use String str = new String("hello"); , a new object is created, but the existing string literal may be reused on either the JVM level or bytecode level (at compile time).
You can check this by using .equals() method of java .

Every time I use String, does it create a new String object?

Let's say that I need to iteratively retrieve a value of the same key from a Java hashmap.
for(int i=0; i<INTEGER.MAX; i++)
map.get("KEY");
In this case, is the "KEY" string created every time I call map.get("KEY")? I was wondering if it's always better to have a String constant, or it doesn't matter.
No. String constants are interned automatically, so any identical string literals all reference the same object in memory.
Some more information on this: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3
An example of this:
String s1 = "Test";
String s2 = "Test";
String s3 = new String("Test");
s1 == s2;//Evaluates to true, because they are the same object (both created with string literals)
s1 == s3;//Evaluates to false, because they are different objects containing identical data
Yes/No Answer depends on how you create String Objects. Below are the four scenarios I can think of as of now.
Yes Cases
new String() always creates new Object. It is not internedn(Doesn't go to String pool) so you
can not take it back from memory.
Concatenation ( "a" + "b" ) always creates new String Object and it is not interned (Doesn't go to String pool).
No Cases
String a ="aa"; if already available it retrieves from the pool, when not available it creates a new object which is interned also (Goes to String pool as well)
new String().intern() or "aa".intern(); if already available it retrieves from pool , when not available it creates new object which
is interned also (Goes to String pool as well).
is the "KEY" string created every time I call map.get("KEY")?
No.
Java Strings are immutable, which allows the Java compiler to use a single instance for all string literals.
That is: all identical string literals in your program will reference a single string object.
In the rare cases you need identical strings to be wrapped in two separate objects, you must explicitly
instantiate a String object:
String s1 = "bla";
String s2 = "bla";
// s1 == s2
String s3 = new String ("bla");
// s1 != s3

difference between two java String assignment types [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Difference between string object and string literal [duplicate]
(13 answers)
Closed 8 years ago.
what is the difference between these two implementations :
String s1 = "java";
and
String s2 = new String("java");
is s1 is able to perform all the functions that s2 will do?? like to uppercase, append etc..
The only Difference is String s1 = "java" will create a String Literal and it will be stored in a String Pool And for String s2 = new Sting("java") an Instance object will be created plus a String Literal in String pool.
For Second part Yes you can, Since its a Variable and variable can access library function using dot operator. so s1.toUpperCase() and s2.toUpperCase().
Ex.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = new String("java");
System.out.println(s1.toUpperCase());
String s2 = "java";
System.out.println(s2.toUpperCase());
}
}
Result : JAVA JAVA
For the first part of question, it has been asked many times and answered many times like here and I don't think we need a better answer there
For the second part of your question,
is s1 is able to perform all the functions that s2 will do?? like to
uppercase, append etc..
Absolutely yes! Try "hello".toUpperCase()
String s = "abc"; // creates one String object and one reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the poo
String s1="java" // will store in string pool
String s2=new String("java"); //will store in heap
so s1==s2 results in false.
if You want s2 also in pool then u have to call s2.intern(). After that s1==s2 results in true.

understanding the difference between java.lang.String s = new String("hello") and String hold = "hello" [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 9 years ago.
I came across this code and got a bit confused
java.lang.String s = new String("hello");
Im not sure what variable s is being initialized as java.lang.String , and what is the purpose of this vs String hold = "hello". I tried to look through some some documentation but could not find anything.
This is really bad programming style
java.lang.String s = new String("hello");
Remember that all classes in java.lang are imported automatically. If you have a class called String in the same package, it will also be imported but shadow the java.lang.String class. That might be a reason to fully qualify the type like
java.lang.String s;
But in this case, you could only ever assign a java.lang.String reference to it since that class is final and therefore cannot be extended. The conventional thing to do would be
java.lang.String s = new java.lang.String("hello");
If you were asking about
java.lang.String s = new String("hello");
vs
java.lang.String s = "hello";
then check out the other answers or the duplicate.
Doing this:
String s = "hello";
is better than doing this:
String s = new String("hello");
The second method creates a string object when you do "hello", passes it to the String constructor, and then creates another identical String object. The first method only creates one object.
Ok you need to know about constants pool (String literal pool)
When you do
String s = "hello";
you are actually setting up the variable in the constant pool
where as when you do
String s = new String("hello");
it creates a separate object in the constant pool.
read more about it here
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html
First thing you must look about is the immutable feature of String in java.
http://javarevisited.blogspot.in/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html
String hold = "hello" uses the immutable nature of the string. So when you do,
String hold2 = "hello"
both hold and hold2 refer to the same instance of "hello" string from the string pool. It means both refer to the same memory location.
But with
String hold2 = new String("hello");
there is a new string "hello" at a new location and hold and hold2 objects refer to different memory locations.
The first thing you should know is that Strings in java are immutable read THIS. Next when you do String s = "hello" behind the scene what happens is that compiler looks into the String Pool (a place where strings are saved in java) and checks if there is a hello string already there. If it is, it points reference s to same string object and returns(Read THIS). Now if you do String hold2 = new String("hello"); none of the above mentioned things happens. Even if you have hello string in String Pool it would still create a new string hello and point reference hold2 to it.

string instantiation vs stringbuffer instantiation

I am not able to figure out that if
String ab = "hello"; //straight initialization
String ab_1 = new String ("hello_1"); //initializing using new
both work, but
StringBuffer bfr = new StringBuffer("hi"); //works only with new
works only if created with new.
Why it is that String can be instantiated directly but StringBuffer needs new operator. Can someone explain me the main reason please.
All objects need to be instantiated with new. Only primitives can be instantiated from a literal (int i = 0;).
The only exceptions are:
strings, which allow a special initialisation construct:
String s = "abc"; //can be instantiated from a literal, like primitives
null instantiation: Object o = null;
It is defined in the Java Language Specification #3.10:
A literal is the source code representation of a value of a primitive type, the String type, or the null type.
Note: arrays also have a dedicated initialisation patterm , but that's not a literal:
int[][] a = { { 00, 01 }, { 10, 11 } };
Using String s1 = "hello"; and String s2 = new String("hello"); have a subtle difference.
public static void main(String[] arg ) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1==s2); //true
System.out.println(s1==s3); //false
StringBuilder sb = new StringBuilder(25); //initial capacikacity
sb = new StringBuilder(10);
sb.append(s1).append(" uses immutable strings.");
sb.setCharAt(20, 'S');
System.out.println(sb);
}
In the above code, "Java" is known as a String literal. In order to save memory, both times this appears in the code, it is the same String literal, so s1 and s2 actually refer to the same object in memory. While s1.equals(s3) would be true, they do not reference the same object in memory as shown above.
In practice, we always use .equals to compare Strings and they are immutable, so we cannot change the data s1 refers to (at least not easily). But if we were able to change the data referenced by s1, then s2 would change along with it.
StringBuilder does let you modify the underlying data: we often use it to append one String to another as illustrated above. We can be glad that StringBuilder sb2 = "what?" is illegal because in the case of StringBuilders, having two of them reference the same data (meaning sb1==sb2) is more likely to lead to problems where a change in sb1 causes an unexpected change in sb2.
String ab = "hello"; //straight initialization
String ac = "hello"; // create one more reference ac
String is a special case when you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.The string pool is like a cache.
It is like this because Strings are something heavily used by java and creating String objects using new key word is expensive also that's why java has introduced StringPool concept.
If you declare one variable ac with same value , java will not create new object(String) it will simply refer to the same object(hello) which is already there in pool.
String ab_1 = new String ("hello_1"); //initializing using new
It will simple create object in memory and ab_1 will refer to that object.
Strings are quite a special case in Java (this is not really a good thing in my opinion, but that doesn't matter).
Strings, unlike other objects, can be instantiated directly like they were constants.
When you do this, the String constant is added to the String constant pool, and handled like it was a primitive. Let me give an example.
String a = "abc";
String b = "abc";
When you instantiate a as a "primitive" string, it gets added to the pool, when you instantiate b, the same object is returned from the pool, so if you do this:
a == b;
You'll get... true, since it's actually the same object. If you instantiate both with new, you'll get false, since you're comparing the references of two different Objects (new forces the creation of a distinct object).
Strings are handle specially by java compiler. When you type a string literal such as "hello", the compiler creates a new String object for you internally.
No such thing is performed for StringBuffers (although Java uses StringBuffers internally for another purpose - for implementing string concatenation).
See Difference between string object and string literal for more details.
Other pointers:
String, StringBuffer, and StringBuilder
+ operator for String in Java
There is also one more difference based on 'where' strings are 'stored' - memory or string constant pool.
To make Java more memory efficient, the JVM sets aside a special area
of memory called the "String constant pool." When the compiler
encounters a String literal, it checks the pool to see if an identical
String already exists. If a match is found, the reference to the new
literal is directed to the existing String, and no new String literal
object is created. (The existing String simply has an additional
reference.)
String s = "abc"; // creates one String object and one reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects, and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
String is a mutable class and has in-build constructors which can create String object from the string literal.
There is no exception in case of String also (like creating it like primitive .e.g int i =0). String also executes constructor to initialize following (just difference is its abstract and not directly visible) :
String str = "ABC";
Becuase here "ABC" also represent one String object which can not be used directly by programmer but it resides in the String pool. And when this statement will be executed JVM will internally call the private constructor to create object using the "ABC" object which resides in the pool.
Basically, since Strings are used so much, Java offers a shorthand solution to instantiating a String.
Instead of always using this,
String str = new String ("hello");
Java makes it able to do this:
String str = "hello";

Categories

Resources