GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How this program compiled & outputs after modifying variable with 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 "How this program compiled & outputs after modifying variable with "final" prefix?" Watch "How this program compiled & outputs after modifying variable with "final" prefix?" New topic
Author

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

Pras Tiwari
Ranch Hand

Joined: Nov 07, 2005
Posts: 186
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


********Deserve Before You Desire********
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381


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.


~Sanjeev Singh<br />SCJP 1.5
John Johnson
Ranch Hand

Joined: Nov 05, 2006
Posts: 39
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

Joined: May 29, 2006
Posts: 30
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 ?


Its a j a v a
abhijit Ohal
Ranch Hand

Joined: Mar 10, 2006
Posts: 64
for object declared as final

we can't assign new instatnce of it.But we can change it 's parametrs value.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.).


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
GeeCON Prague 2014
 
subject: How this program compiled & outputs after modifying variable with "final" prefix?