• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

what is the diff? (Strings again)

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q. What will be the result of executing the following code
public class MyClass
{
public static void main (String args[])
{
String str = "SCJP";
String str2 = ""; // There is no space
// between double quotes
System.out.println(str == str + str2);
}
}
Will print false
--------------------------------------------------------------------------------
Q. What will be the result of executing the following code
public class MyClass
{
public static void main (String args[])
{
String str = "SCJP";
String str2 = str.concat(""); // There is no space
// between double quotes
System.out.println(str == str2);
}
}
Will print true

why ?
what is the diff between "+" and concat()?
2]
How many String objects are created when we run the following code.
String s1,s2,s3,s4;
s1 = "Hello";
s2 = s1;
s3 = s2 + "Pal";
s4 = s3;
ans is 3 but i don't agree.
what do all say?

[This message has been edited by shilpa gupta (edited March 05, 2001).]
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Don't know about second answer because I think 2 but I can help you with the first question. The difference between concat and + is that concat is smarter. Inside the method concat:

If you send in empty string you get original reference pointer back! Using "+" will always result in new memory location because compiler handles that case.
Regards,
Manfred.
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI Shilpa,
Your first question about + and concat -
concat and + are the same thing, but implementation is a bit different. Quoting from Java documentation-
QUOTE
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
UNQUOTE
So, the difference which appears to you due to the true and false results you are getting is because -
In the 1st code, you have declared 2 different String handles - str and str2. By declaring 2 handles and assigning objects to them, you have created 2 String objects - with values "SCJP" and "". In the expression (str==str+str2), you are first concatenating 2 string objects, which will create a 3rd String object. Hence str the result of the expression str + str2, cannot reference the same object. Hence result is false.
This is because String objects cannot be changed or modified once they are created. If you modify any String, a new String object is created and the handle is assigned to reference the newly created object.
In the 2nd code, you are concatenating str object with a null String using the concat() method, which will return the same object if the argument length is 0. Thus, no new object is being created. So, str == str2 is true.
Your second question regarding how many objects are created -
Every String object that we create is a reference to an instance of class String. You have also asked what is intern in strings. Basically, when we create a new String, Java checks if any String of that value exists already. If a String exists, then it does not create a new object, but just sets the declared String handle to the previously created String. This is done irrespective of the place from where the 1st String object was created. This is "interning" of strings.

If a String "hello" was created in a package pkg1 and a class - class1 and we create another String "hello" in another package pkg2 and class - class2, still the handle in class2 will reference the same object created in class1 and no new class will be created. There is one point to note that, this is only applicable to strings which are values of constant expressions at compile time. Thus, the above will NOT be applicable to strings created at runtime.
To explain this, if you create strings -
String s = "hello";
String t = "hello";
String u = new String("hello");
Here, handle t will reference the 1st "hello" object created and assigned to handle s. So, handles s and t reference the same object. But, handle u creates a new object "hello", even though the value of the string is same as that of s and t.
So, now going back to your 2nd question,
s1 creates the 1st object "Hello"
s2 = s1, means s2 is assigned to s1 and no object is created. Both reference the same object "Hello".
s3 = s2 + "Pal"; means 2 objects are being created. First the object "Pal" is created and then a new object s3 which contains "HelloPal" is created.
s4=s3; s4 handle is assigned to s3 object "HelloPal".
So, total 3 objects are created.
Hope this clears all doubts.
Niraj
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all in:
String str = "SCJP";
This is a reference to a String literal and is resolved at compile time and the literal is created in the Constant Pool at class load time.
Hoewever when you print (str == str + str2) the concatenate of two literals causes a String object to be created on the heap at runtime. Of course the reference to the literal is not the same as the reference to the object. However if you say "str == (str + str2).intern())" then it would return true because they would both point at the same literal in the constant pool.
Both Leonard and niraj correctly explianed the .concat method. It is the same as asking "does str contain the same reference as str". Of course that is true.
niraj explained the third one well.
FYI: from the JVM Specification:


5.4 String Resolution
A constant pool entry tagged as CONSTANT_String (�4.4.3) represents an instance of a string literal (�2.3), that is, a literal of the built-in type java.lang.String.
The Unicode characters (�2.1) of the string literal represented by the CONSTANT_String entry are found in the CONSTANT_Utf8 (�4.4.7) constant pool entry that
the CONSTANT_String entry references.
The Java language requires that identical string literals (that is, literals that contain the same sequence of Unicode characters) must reference the same instance of class
String. In addition, if the method intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as
a literal. Thus,
("a" + "b" + "c").intern() == "abc"
must have the value true.3
To resolve a constant pool entry tagged CONSTANT_String, the Java Virtual Machine examines the series of Unicode characters represented by the UTF-8 string
that the CONSTANT_String entry references.
If another constant pool entry tagged CONSTANT_String and representing the identical sequence of Unicode characters has already been resolved, then the
result of resolution is a reference to the instance of class String created for that earlier constant pool entry.
Otherwise, if the method intern has previously been called on an instance of class String containing a sequence of Unicode characters identical to that
represented by the constant pool entry, then the result of resolution is a reference to that same instance of class String.
Otherwise, a new instance of class String is created containing the sequence of Unicode characters represented by the CONSTANT_String entry; that class
instance is the result of resolution.


ANd from the JLS


This example illustrates six points:
Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
Literal strings within different classes in the same package represent references to the same String object.
Literal strings within different classes in different packages likewise represent references to the same String object.
Strings computed by constant expressions (�15.27) are computed at compile time and then treated as if they were literals.
Strings computed at run time are newly created and therefore distinct.
The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.


edited by Cindy to correct Cindy.definition(literal)

[This message has been edited by Cindy Glass (edited March 05, 2001).]
 
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic