It's not a secret anymore!
The moose likes Java in General and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic


PSV Kumar

Joined: Sep 20, 2003
Posts: 10
Plz look in to this code and clear my doubt...
final StringBuffer str_buf = new StringBuffer("abc");
here it is appending the string buffer eventhough it is final. But when i want to concat a string which is final with another string then it says 'cannot assign a value to final variable.
My question is how can stringbuffer append even though it is declared as final?
thanks in advance..

Joined: Sep 18, 2003
Posts: 17
u r right, object declared as fianl can not be referenced to other or new object. ie. when u concatinate two strings, it creats new object. but when u append StringBuffer, it changes object's state.
easy eg. to understand it would be
class ABC
String str;
ABC(String str)
class XYZ
final ABC obj1 = new ABC("Hello");
ABC obj2 = new ABC("Hi");

obj1 = obj2; // will not work, because obj1 is declared as final and value of ref., obj1, cannot be changed.
obj1.str = "Hi"; // will work, because u r not changing ref. but state (value of obj1's property).

Wish U Happiness,<br />Sanjeev.
PSV Kumar

Joined: Sep 20, 2003
Posts: 10
Thank u Sanjeev....ur explanation and example cleared my doubts..thank u once again
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

You have created a duplicate conversation here originally in the Servlet forum, I moved it to the JiG(beginner) forum.
Please don't post the same question to multiple forums. It creates duplicate converstaions and wastes the time of the poeple trying to help you.
I'm going to ask for this thread to be closed, anyone who wants to help should see the other thread.
jQuery in Action, 3rd edition
subject: StringBuffer
It's not a secret anymore!