This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How this program compiled & outputs after modifying variable with "final" prefix?

 
Pras Tiwari
Ranch Hand
Posts: 186
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i tried to run this class I got o/p as :- "Now original is modified"
Here I am modifying variable "style" in modify method which is of type "final".

public class TestQ24 {

public static final StringBuffer style =
new StringBuffer("original");
public static void main (String[] args){
TestQ24 tq = new TestQ24();
tq.modify( style );
System.out.println("Now " + style );
}
public void modify( StringBuffer sb ){
sb.append(" is modified" );
}
}

Please explain me why i am getting above o/p though i am modifying "final" variable.
Thank you.
Pras
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


when a reference variable is declared final ,it means that the same variable can not be re-assigned to refer to other object.
The internal state of the object refered by the final variable can be changed.
In //2 you are modifying the internal state of the object origianally refered by style.Reassigning style to other object would have given you the compilation choke.
 
John Johnson
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, I always wondered if there is a way to declare objects pointed to to be final. Something like const pointers to const variables in c++.
 
Kalpesh Jain
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Johnson:
By the way, I always wondered if there is a way to declare objects pointed to be final. Something like const pointers to const variables in c++.


Can't we declare an object final and refer to it with final variable ?
 
abhijit Ohal
Ranch Hand
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for object declared as final

we can't assign new instatnce of it.But we can change it 's parametrs value.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the object is mutable, one approach might be to clone the object, so that you can keep the original insulated from modification.

See Cloning objects from "Appendix A" of Bruce Eckel's Thinking in Java (3rd ed.).
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic