String objects and storage [duplicate] - java

This question already has answers here:
String s = new String("xyz"). How many objects has been made after this line of code execute?
(21 answers)
Closed 3 years ago.
How many objects will be created in the following code and where they will be stored?
String s = "abc"; // line 1
String s1 = new String("abc"); // line 2
String str1 = new String("efg"); //line 3

Total 3 objects will be created.
Line 1 : Object will be created in string pool,
Line 2 : Object will be created in Heap,
Line 3 : Object will be created in Heap.
Reason is :
a) By string literal : Java String literal is created by using double quotes like in line 1. It is always created in String pool,
b) By new keyword : Java String is created by using a keyword “new” like in line 2 and 3. It is always created in Heap memory.
For reference:
https://www.geeksforgeeks.org/string-initialization-java-string-literal-vs-string-object/

Related

java strings inmutable but the code doesn't shows that [duplicate]

This question already has answers here:
Immutability of Strings in Java
(26 answers)
String is immutable. What exactly is the meaning? [duplicate]
(19 answers)
Closed 4 years ago.
I was learning string concepts, so wrote a code,expected a different output but got something very unexpected.
class stringmute
{
public static void main(String[] args)
{
String s1="Hello "; //string one.
System.out.println("Str1:"+s1);
String s2= s1+"world"; //New String.
System.out.println("Str2="+s2);
s1=s1+"World!!"; //This should produce only Hello right?
System.out.println("Str1 modified:"+s1);
}
}
when I execute the above code i get the output as:
Str1:Hello
Str2=Hello world
Str1 modified:Hello World!!
if i've done something wrong please let me know.
Since strings are immutable, which implies we should get the output of the "Str1 Modified" as "HELLO" instead of "HELLO WORLD!!".
When you assign s1 as :
s1=s1+"World!!";
New String created in jvm string pool and assigned to s1.
So it's value became "Hello World!!"

Build a String with String Operators [duplicate]

This question already has answers here:
String Constant Pool
(5 answers)
Closed 7 years ago.
In this example I thought that the result was true. I thought that the variable stored in the string pool.
The answer was: returns false because the two String objects are not the same in memory. One comes directly from the string pool and the other comes from building using String operations.
String a = "";
a += 2;
a += 'c';
a += false;
if ( a == "2cfalse") System.out.println("==");
I do not understand where the variable a was stored
Okay, so two responses to this. First, the ethically correct one, do never test strings with ==, always use .equals() or .equalsIgnoreCase().
Secondly, it's true that indeed, "a" == "a" because the strings are stored in, as you call it, the same pool. The problem here is that you append to it. Appending to a string causes it to become a different string, which is not stored in the string pool. The string pool is only generated on-compile, and as the second string is calculated on runtime, it won't match the one generated on-compile.
Imagine a string-pool to work like this:
a = "test";
b = "te";
c = "st";
d = "test";
The compiler translates this into
sp1 = "test";
sp2 = "te";
sp3 = "st";
a = sp1;
b = sp2;
c = sp3;
d = sp1;
Now == will check if two variables refer to the same sp. If you run b + c java will not go back and check if any of the sp's is the same as that. It only does that on compile.

Is a valid scenario for assigning string from string pool?

I have been given the following condition?
String A="a";
String B="b";
String c="a"+"b";
My question is is the String c created newly or is assigned from the string pool the value "a" and "b" and total how many strings are formed according to above question?
Yes c is created newly. Strings in Java are effectively immutable (i.e. once created, they never change). One of the consequences of this is that, whenever you do a manipulation that changes a string, you get back a new, different object.
So in your example, 3 strings are created.
Take these two String objects:
String a = "a";
String b = "b";
String c = "a" + "b";
String d = "ab";
The compiler creates and pools three String objects. A line by line explanation follows.
Line 1: One String object is pooled for "a"
Line 2: One String object is pooled for "b"
Line 3: "a" + "b" is computer at compile time and treated as a literal. Therefore, one String object is pooled for "ab"
Line 4: "ab" is already in the pool
Following the same guidelines, your example produces 3 String objects.

How are the == operator and .equals for strings in java the same? [duplicate]

This question already has answers here:
String comparison and String interning in Java
(3 answers)
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 10 years ago.
I'm new to this site and didn't realize there were other questions that answered what I'm asking. I've figured it out and I will delete this post as soon as it lets me. Thank you.
I just started learning java again and I have a quick question.
Usually, using == to compare strings would not work and you would have to use .equals instead.
But now while coding, I found they are doing the same thing when they are not supposed too and I'm trying to figure out why.
Here's the code.
String s = "Hello";
String x = "Hello";
if (x == s){
System.out.println("It is working!");
}//end if
else {
System.out.println("It is not working");
}//end else
if (x.equals(s)){
System.out.println("Match");
}//end if
else {
System.out.println("No match");
}//end else
Basically you're seeing the result of string interning. From section 15.28 of the JLS:
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
So your two variable values actually refer to the same strings. If you use:
String s = new String("Hello");
String x = new String("Hello");
... then you'll see the behaviour you expect.
Reason is that your vars x and s have the same reference hence == behaves same as .equals.
When Java compiler optimizes your string values (literals), it determines that both x and s have same value and hence you need only one String object. As result, both x and s point to the same String object and some little memory is saved. It's safe operation since String is an immutable object in Java.
well, In this particular case there is only one string object created and cached in the string constant pool and both of the reference variables refer to the same string object which is stored in the string constant pool . thus you == test passes
String s = "Hello"; Line 1
String x = "Hello"; Line 2
When line 1 is executed one string object (Hello) is created and cached in String Constant pool .
**String Constant Pool:** {s--->"Hello"}
when line 2 is executed, it first checks if there is any object with the same value in string constant pool, if there exists one. it simply points the reference to the already created object in the pool.
**String Constant Pool:** {s,x--->"Hello"}

Java String object creation [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?
Hi,
1) What is difference in thers two statements:
String s1 = "abc";
and
String s1 = new String("abc")
2) as i am not using new in first statement, how string object will be created
Thanks
The first will use a fixed String that will be compiled in the code. The second variant uses the fixed String and creates a new String by copying the characters. This actually creates a new separate object in memory and is not necessary, because Strings are immutable. For more information, you can read this thread.
The main advantage of having internalized strings is that the performance is better (e.g. through caching etc.).
As a programmer there is no real upside to creating a new String, unless you come by the following example:
String sentence = "Lorem ipsum dolor sit amet";
String word = sentence.substring(5);
Now the word has a reference to the sentence (substring does not copy the characters). This is efficient while the sentence is also used, but when this one is thrown away you use a lot more memory than needed. In that case a new String can be created:
word = new String(word);
In the first case, the compiler knows the value of the String s1. Thus, all strings with the same value will use the same memory locations:
String s1 = "abc";
String s2 = "abc";
Although there are two String references (s1 and s2), there is only one "abc" sequence in memory. The new operator is not needed because the compiler does the job.
In the second case, the compiler doesn't perform the evaluation of the String value. Thus, the sentence will generate a new instance of String, at runtime:
String s1 = "abc";
String s2 = new String("abc");
The constant "abc" in line 1 references the same memory as the constant "abc" in line 2. But the net effect of line 2 is the creation of a new String instance.

Categories