aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes this reference problem is taking my life.........plz help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "this reference problem is taking my life.........plz help" Watch "this reference problem is taking my life.........plz help" New topic
Author

this reference problem is taking my life.........plz help

Harvinder Singh
Ranch Hand

Joined: Feb 14, 2003
Posts: 90
//2/6/2004
Why the output is true,true?Why “A”+”B” do not creates a new object in the following code?
And if u can mention some other point about the references then it will really be very helpfull for the SCJP.
class Orange {
public static void main(String args[]) {
String a = "A";
String b = "B";
String c = "AB";
System.out.print((("A"+"B")= ="AB") + ",");
System.out.print(("A"+"B")= =c);
}
}


Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
Dmitry Melnik
Ranch Hand

Joined: Dec 18, 2003
Posts: 328
Results of operations on constants like "A"+"B" are computed at compile time. Thus there is no difference between "A"+"B" and "AB"
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The reason is that String object are optimized somewhat in Java. Because String objects are immutable, you can safely use a reference to the same String object if two Strings contain the same data. Because of this, Java keeps a "String literal pool" which contains all of the String literals used in your program. Any time you'd try to create a new String which is identical to one of the Srtings already in the pool, you really get a reference to the one in the pool, not a brand new String.
In your example, the line String c = "AB"; causes a new String to be added to the literal pool: "AB".
When you then perform the action "A" + "B", Java sees that you're trying to create a new String with the contents "AB" so, rather than wasting memory and giving you a new one, it simply returns a reference to the one that already exists in the literal pool. Therefore, "A" + "B" == c returns true. They both reference the same object.
I hope that helps,
Corey


SCJP Tipline, etc.
Jason Cox
Ranch Hand

Joined: Jan 21, 2004
Posts: 287
When you create a String using the following -
String a = "A";
Java basically creates an object that points to a String reference with a value of "A".
So now if you create a String like so -
String b = "A";
Then a and b are actually referencing the same object. Get it?
So in this example you have -
String a = "A" // reference to object "A"
String b = "B" // reference to object "B"
String c = "AB" // reference to object "AB"
Since these are the first time these are called, you have just created three new objects. However, if you do the following -
"A" + "B"
It combines the values of object "A" and object "B" which is "AB" in the case of a string. Since "AB" already exists, the combination of "A" + "B" is just a reference to "AB".
Now, try this instead -
String d = new String("AB");
The output of c == d will be FALSE!
Although c and d both have values of "AB", there are now two different objects with a value of "AB". So when you created d, it did not reference the existing "AB" object but created a new one.
This is also why when you instantiate a String you do not want to say -
new String("")
because you're creating a new object everytime. It's inefficient!
Narasimha Rao B.
Ranch Hand

Joined: Aug 26, 2002
Posts: 205
Hi,
Did any one compile the above programme in 1.4. I am getting the below compiler errors. Please provide me the reson,
-------------
Orange.java:6: illegal start of expression
System.out.print((("A"+"B")= ="AB") + ",");
^
Orange.java:6: ')' expected
System.out.print((("A"+"B")= ="AB") + ",");
^
Orange.java:7: illegal start of expression
System.out.print(("A"+"B")= =c);
^
Orange.java:7: ')' expected
System.out.print(("A"+"B")= =c);
^
Orange.java:6: unexpected type
required: variable
found : value
System.out.print((("A"+"B")= ="AB") + ",");
^
Orange.java:7: unexpected type
required: variable
found : value
System.out.print(("A"+"B")= =c);
^
6 errors
---------
On the basis of above explanations, i.e., A new string object will not be created if that string object is already presents in the string pool.
On the same logic, please go through the below one,
public class D {
public static void main(String args[]) {
String s1 = "ABCD"; // 0
String s2 = " ABCD ";
System.out.println(s1==s2.trim()); // 1
}}
On the basis of above explanations, above programme should behave as explained below,
At line number 1, s2.trim() will try to create the string object, "ABCD' which already created at line number 0, so with out creating new string object at line number 2, s2 should point the string object created at line number 1. But it is not the case. Above print statement returns fase, that means s1 and s2 both are different string objects, both have the value "ABCD".
Please explain the above behaviour.
Thanks is Advance,
Narasimha.


Narasimha
Jason Cox
Ranch Hand

Joined: Jan 21, 2004
Posts: 287
The two Strings in your example are NOT the same.
"ABCD" is different than " ABCD "
Placing a .trim() method on a comparison operator does nothing. The .trim() method returns a String, but the comparison is against the actual object s2. Even though .trim() returns a String with the whitespace removed, it does not change s2's object reference.
s2 = s2.trim() actually returns a new String object, so it still will not be equal to s1 even though each object holds the same value.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
The rules about String references and objects discussed above refer to String *literals*. Since the trim() function isn't a literal, these rules don't apply. I suspect that internally it uses new to create a String object that isn't in the String literal pool mentioned earlier.


Java API Documentation
The Java Tutorial
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Rob Aught:
The two Strings in your example are NOT the same.
"ABCD" is different than " ABCD "
Placing a .trim() method on a comparison operator does nothing. The .trim() method returns a String, but the comparison is against the actual object s2. Even though .trim() returns a String with the whitespace removed, it does not change s2's object reference.

I think the . operator has precedence over the == operator, so
s1==s2.trim()
is evaluated as
s1==(s2.trim())
not
(s1==s2).trim()
In fact, if the later interpretation were applied, the compiler would complain since it isn't legal to use the . operator on a boolean value.
My point is that the comment about applying the .trim() to a comparison operator doesn't apply here (pun intended). Rather, s2.trim() is evaluated first, which returns a reference to a new String object, as I mentioned in my previous post. This reference is compared with s1. Since they reference different objects, the whole expression evaluates as false.
HTH
Layne
Jason Cox
Ranch Hand

Joined: Jan 21, 2004
Posts: 287
the compiler would complain since it isn't legal to use the . operator on a boolean value.

Mine didn't flinch a bit.
But you're right, I didn't mention that. The . operator does have precedence over ==. I seem to have taken that for granted in my explanation and should have mentioned it.
To be honest, I didn't think about it. I just did it in my head that way without thinking of the rules of precedence at all.
Kadiyala Naga Sai
Greenhorn

Joined: Feb 11, 2004
Posts: 20
Hi Harvinder,
I would like to clear a small part besides the info given here...
If u write code with out the String reference variable, the output will be same.
In your System.out.println method, you are passing the simple strings and using the concatination(+) operator.This is just doing addition of the strings.Coincidently you have created the similar refernce variable pointing to the same value.
Other forum members explained the other logics of the program concepts to make the matter clear on other way and I do not want to repeat again.


Kadiyala S Naga Sai<br />Petronas Ammonia Sdn Bhd<br />Kerteh,Malaysia 24300
Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello all,
Regarding the concept for this discussion, I tried out some codings and found out this kind of a logic.
String str1 = "ABC";
String str2 = " ABC "; // Leading white space
System.out.println(str1==str2.trim());
Here the str2.trim() discards the whitespaces and returns a new string. Even though the returning value is already there in the string pool, it returns a new reference. So the result is "false".
String str1 = "ABC";
String str2 = "ABC"; // No white spaces
System.out.println(str1==str2.trim());
Since there is nothing to be trimed, str2.trim() returns the same reference, which is equal to str1 reference. So this code prints "true".
String str1 = "ABC";
String str2 = " ABC "; // Leading white space
System.out.println(str1==str2.trim().intern();
Even though trim() method returns a new reference because of the intern() the controller checks if the returning string is already there or not. Becuase it is already there in the string pool the result of the above code snippet is true.
Hope the concept is clear and what I got is correct too.
Please do analyze and suggest your views regarding this.
Thank you very much......


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Bijesh Krishnadas
Ranch Hand

Joined: Aug 08, 2002
Posts: 31
Originally posted by narasimha rao bandlamudi:
Hi,
Did any one compile the above programme in 1.4. I am getting the below compiler errors. Please provide me the reson,
-------------
Orange.java:6: illegal start of expression
System.out.print((("A"+"B")= ="AB") + ",");

Hi,
Did u notice the space between the '='s in the '=='?
'==' reads as '= ='. I guess u directly copied the code.
Bijesh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: this reference problem is taking my life.........plz help