This question already has answers here:
When does the pool change?
(3 answers)
Closed 8 years ago.
public class D2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="java";
String s2="ja".concat("va");
System.out.println(s1==s2);
}
}
On concatenating two String constants in s2 doesn't result in a new String object(String objects are only created when new is used or a perm reference like s1 on concatenation). Kindly shed light on why the o/p is false.
On concatenating 2 String constants in s2 doesn't result in a new String object
That's true when it's performed with the string concatenation operator - but that's not what you're doing here. You're manually calling String.concat, so this is not a constant expression, and not evaluated at compile time.
If you used:
String s2 = "ja" + "va";
then the concatenation would be performed by the compiler, and s1 and s2 would refer to the same object.
JLS section 15.28 gives details around what leads to a constant expression, and that doesn't include method calls.
Related
This question already has answers here:
Immutability of Strings in Java
(26 answers)
Closed 6 years ago.
If a String object is immutable then why is it printing "Help"?
The String object s1 shouldn't be modified according to its immutability feature. I am confused for years, please help me understand this:
Code
public static void main(String[] args) {
String s1 = "Hello";
s1 = "Help";
System.out.println(s1);
}
Output
Help
Your second assignment actually is changing the String that s1 references.
There is still a String of "Hello" in existence (in the pool) which cannot be changed.
The behavior you described would be achieved by making s1 final - in which case you would get a compiler error if you tried to change the value the String s1 references.
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.
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.
This question already has answers here:
What is Java String interning?
(8 answers)
Closed 6 years ago.
How does Java decide when a new String should be created?
I assume it depends on the specific JVM implementation/ compiler, but I thought the results of this test were interesting enough to ask the question:
class A { public String test = "test";}
class B { public String test = "test";}
...
public static void main (String[] args)
{
String test = "test";
System.out.println(test == "test"); // true
System.out.println(test == new String("test")); // false
System.out.println(new A().test == new B().test); // true
}
String literals are always interned, this is not directly platform-dependent.
Except when using the explicit initialization idiom through the constructor (new String(someString)).
In that case, a new Object is created, which causes the reference equality operator (==) to return false in your example.
Needless to say, always use equals for reliable String value comparison, but I suspect this falls out of your question's scope.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Strings are objects in Java, so why don't we use 'new' to create them?
In Java, class objects are created like-
MyClass a=new MyClass();
then how String class objects are created like-
String a="Hello";
What does this "Hello" does to create new object?
String a = "Hello" doesn't actually create a new object. Instead, when the compiler sees a string literal like "Hello", it adds the string to the string literal pool, from which it will be loaded later.
Providing a String as a literal finally makes it in the String Literal Pool of the JVM. Quoting from this article:
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.For example:
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
}
}
The result is
true
Unfortunately, when you use
String a=new String("Hello");
a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2 + " ");
System.out.print(str1.equals(str2));
}
}
The result is
false true