« XCode 1.2 out with Guard Malloc | Main | Free scoop night »

Java 'final' trivia

Here's some Java trivia.

On a stock Java install, I have an app. That app has a reference to a Java class that has a member variable marked as static final. And my app can change that variable's value at will.

No, I did not write any JNI code.

How is that?

Comments

The static final variable is a mutable object. Final only means that the reference must remain the same. The objecs intrisic value can still change if it is mutable...

Nice try, but no. The variable's content is not necessarily a mutable object. Put another way,

{
Object o1 = // that static final member variable
// ... change the value of that variable
Object o2 = // that same variable
assert(o1 != o2)
}

It's not the same mutable object with different values. It's _two_different_objects_.

You're not supposed to be able to change the value of a 'final' variable. But in this case we can. How?

Well, since I haven't seen any posts here on this topic since 2004, I'm going to guess nobody figured out your little teaser.

Instead of being so circumspect about your scenario, why don't you post the shortest possible WORKING code example and ask us why *that* works? Because it's apparent that your description is vague enough that it could mean almost anything, as evidenced by the first respondent -- nonya's idea was perfectly valid, but obviously not what you had in mind.

We can't read your mind. I can think up any number of scenarios that *might* apply, but might not be what you mean. And the pseudocode snippet you provided doesn't really clarify anything, I'm sorry to say.

!*!*! SPOILER ALERT !*!*!

Robert—

My code is not pseudocode. It's literally the Java that I want to work.

Take a look at the memory model papers that they wrote for the new memory model they introduced in Java 5. They punch a hole in the meaning of "final" for System.out (and in and err). System.out is a final variable. Its content thus should not be changeable.

But it is. System.setOut().

Those are the only three final variables whose values you can legally change.

Post a comment