Object Creation JAVA [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between “text” and new String(“text”) in Java?
Please explain the brief and detailed difference between following 2 statements:
String a= "somevalue";
String b = new String("somevalue");
I know that 2nd statement creates and provide memory to String Object b in heap. But why object a doesn't get memory and its still allowed to operate on string methods.

a and b are references to Objects, not Objects.
When you do a = b; it doesn't copy the Object, it copies a reference to an Object.
A String has a char[] inside it which is another object.
a gets an reference to an existing object so it may not need any extra memory.
b get a reference to a newly created object so that requires more memory.
its still allowed to operate on string methods.
This has nothing to do with how the object was created.

The first affects the literal String object "somvalue" to variable a. This literal String object is cached in a pool, as all literal Strings.
The second creates a new instance of empty String. Since String instances are immutable, it's equivalent to String b = "";, except it instantiates a new object for nothing.

Related

What is benefit of creating a duplicate String object in heap if the same string literal is created(or already present) in string constant pool area?

String str = new String(“my literal”);
In above statement ,two objects would be created ,one as String literal “my literal” in string constant pool (If it's not present in string pool) and other in heap area as object String(“my literal”)
Q-1 I know the benefit of putting the string literal in string pool area but I am not able to think of about the benefit of creating a duplicate object in heap?
Q2- As I read in some stack over flow link: If use of new String("my literal") is almost always bad because you will be creating 2 Strings one on String constants pool and another on heap with the same value ,then my question is why does Java creates duplicate object in heap? Why not java just ignore creating in heap?
There is almost no benefit to calling the String(String) constructor with a literal string. There used to be a significant benefit to calling the String(String) constructor with a different string expression.
The literal is already a String, and String objects are immutable. More generally, for any String expression passed to the String(String) constructor, the constructor is usually unnecessary, because the argument is already an immutable String.
From the String(String) constructor documentation:
public String(String original)
Initializes a newly created String 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.
With older versions of Java (prior to 1.7.0_06), the String(String) constructor was more useful. A String created by String.substring() could refer to the larger original String, and prevent it from being garbage collected. The String(String) constructor cut the ties to the larger String.
You asked:
Q-1: ... The benefit of creating a duplicate object in heap?
Usually there is none. However, if you're using a String object in a context where object identity matters, you might want a different object. For example:
You're using String objects as keys within a IdentityHashMap, and want only your own String objects to match.
You want to synchronize on a string value provided by external code. You don't want any other code synchronizing on the same String object; it could lead to unexpected interference and deadlock. [This example provided by #biziclop in a comment below.]
Q-2: ... why does Java creates duplicate object in heap?
Because you explicitly asked it to with new String("my literal"). If you use the new operator, you get a new object.

what is benefit of creating two object using new operator in string

what is benefit of creating two object using new operator in string. Why two objects are created and what is their importance .
String s=new String("abc");
//creates two object
//why 2 object creation is required.
If you perform the following test:
String a = "foo";
String b = new String(a);
System.out.println(a == b);//returns false
So it means a and b are not the same object (this is probably mandatory because the new operator is used).
This can be useful if you would use the == to check if you are talking about the same string (thus not an equivalent string).
There is in this case however little use to do so, especially because String objects are immutable, as you can read in the manual:
Initializes a newly created String 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.
The only situation where it can be useful I think, if you would attach some kind of "message" aspect to the String, where a messageboard only accepts different object Strings. If you in that case want to insert the same message twice, you will need to make a copy of the String.

Object equality(object referece "==") [duplicate]

This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 8 years ago.
I have written this code in eclipse:
String[] s = {"a","b"};
String d = "a";
System.out.println(s[0]==d);
and it is giving "true" as output.
"==" checks for object reference, if both object refer to same object, but here in this case object "d" refers to different object and "s[0]" to different, then how come they are equal.
"a" will have been created in the string pool used by the JVM.
As an optimisation only one instance of that string will have been created. Java can do this since strings are immutable. That's why the references are referencing the same underlying object, so in this particular instances, the references compare equal.

Memory allocation of Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
If I declare array of Strings like,
String []str = new String[3]; //line 1
It creates one reference(pointer) in stack for string array, but still I need to do str[0] = new String(); to initialize String in array.
I understand that line 1 just allocates memory to pointers that will be used to point to Strings in array.
My doubt is, are these references(pointers) allocated memory in heap(most probably yes, because new is used), if yes, than why?
When you declare an array of strings like, String[] str = new String[3];, you are not just creating a single reference to the array. Rather you are creating an array of references for each string. In the above example, an array of three references will be created. All these three references will be created in the stack itself. Note that in JAVA, all primitive types and references will be created in stack itself. After the above statement, all the three string references will be pointing to a special null object.
Now, when you start creating the actual string objects using str[0] = new String();, then the new string object itself will be created in the HEAP. And the first reference in the array of references points to the newly created string object.
Instead, if you just say new String(), with out any assignment on the left side, the new string object will be created in the HEAP, and there will not be any reference to it. That means, we can not access the newly created string object in subsequent steps.
Let us say, you again do something like str[0] = null;, then the reference again points back to null, and we will not have any reference to the string object that we created earlier. In other words, we can not access the string object any more.
Java has no pointers. But if you had used an Object with a default toString(), like an array!, you'd get something like a reference address
int[] test = new int[] {1};
int[] test2 = new int[] {1};
System.out.printf("%s %s%n", test, test2);
Which outputs (here but your's will have two different address, very probably, every time)
[I#15db9742 [I#6d06d69c
The reference to the array will be on the stack. The array will be on the heap. If you add new references to the array, then the references will be on the heap (as the array itself is on the heap). Provided there are no other references pointing to the same String.
PS : Since the introduction of Escape Analysis from Java6U23, the allocation could be done / moved to the stack itself.
Generally speaking, primitive objects (int, long, byte, etc) along with array references (String[], int[], etc) would be on the stack. Any complex objects (ex. String, ArrayList, Cat, Dog, Foo, Double, Long (notice the capitalised D and L in Double and Long vs the smaller ones) etc), would reside on the heap.

String confusion in java [duplicate]

This question already has answers here:
Immutability of Strings in Java
(26 answers)
Closed 9 years ago.
From the oracle doc
String is immutable also Strings are constant; their values
cannot be changed after they are created. and because they are
immutable they can be shared. String buffers support mutable strings.
but I can always do the following:
String name="SO";
name="SE";
I can change the value so how can it be immutable and it is said that for security reason also like database connectivity etc..
Pardon me for asking such basic question but I need to understand.
name="SE" by doing this, you are changing the value of name variable, not the String object SO itself. String are immutable in the sense, String object SO can't be modified once created. By doing name = name+"TEST"; there will be a new String object SOTEST created in the memory, not existing String object SO will be modified.
For further details look here and here. There are lot of example and explanation.
Yes, you can change the string your name variable points to. But let's see what happens when you execute the following code sequence:
String name = "SO"; //line 1
name = "SE"; //line 2
At line 1: a new String object is created, that holds the value "SO";
At line 2: a new String object is created, that holds the value "SE"; your name variable value changes, in that it points to another reference, which is the second String object; the first String object ("SO") is still on the heap, but is not referenced anymore and is made available for future garbage collections, if any.
What you have to understand here is that, as soon as the String object containing the char sequence {'S', 'O'} is constructed, the char sequence wrapped by that String object could never change again. E.g. you cannot make that object wrap the char sequence {'S', 'E'}. That's what immutability is all about.
In the example you provide you have created two Strings. First a String SO is created and the reference is assigned to name. Then a new String is created, SE and that reference is assigned to name. You never actually modified the first String that was created.
String temp = "SO";
String name = temp;
name = "SE";
System.out.println(temp.equals("SO")); //prints true;
System.out.println(temp == name); //compares references prints false
When you change value of your String reference, you in fact create new object.And your reference now is linked to this new object.
String myValue = "old"; -> VM creates String object "old"
myValue = "new"; -> VM created String object "new"; "old" object still exists but any reference is linked to this, so we can say : "old" is lost
See for example the below image from the internet:
The big cloud is the heap where objects are being stored, s is the reference to the object (in your question you are using name as the reference)
When you do s = "abcd" a new object is created in the heap, and s is a reference to it. (Like the top arrow shows)
The important bit:
When you then do something like s = "abcdef" or s = s + "ef" the immutable string object "abcd" cannot be changed and so a new object is created and s loses it's reference to the old string (shown by dotted line) and now references the new String (Shown by the bottom arrow).
The old object I would assume is picked up by Garbage Collector at some point.

Categories