Final Variable changed on runtime...

Hello, I recently did a test with my program, which involved the use of 32 clients connecting to a server from a single application, however on runtime, the some final variables had their values changed, for example
private static final Point point1 = new Point(100,100);
had changed values to 480,360, and the default Point in my Point class had changed it's value from 0,0 to another value as well. How is this possible? The only methods used on the finalized point was equals/distance, which both do not affect the private fields of point, yet they were changed after logging in about 29 clients or so.
    public int distance(Point p2)
        return Math.max(Math.abs(p2.x - x), Math.abs(p2.y - y));
    public boolean equals(Point p)
        return (p.x == x && p.y == y);
    public boolean equals(Object obj)
        if (obj instanceof Point)
            return (((Point) obj).x == x && ((Point) obj).y == y);
        return false;
    }And here is where they are used
    private static final Point mine = new Point(167, 105);...
                    if (!cLoc.equals(mine))
                        if (cLoc.distance(mine) <= 18)
                            Player.jump(mine);
                            Player.Mine();
                            lastMineTime = 0;
                    }Any idea why this happened?

Sorry, I was not clear enough
Here is my Point class
http://pastebin.com/m6075a9d8
Now, after logging on about 38 clients (about 204 threads lol....), the constant fields get changed, for example within the point class, the "DEFAULT" gets changed to a random variable (which never happened before when logging on 10-20 only)
Same goes for my other constant variables, their values get changed.
For Example these Points:
    private static final Point sellPoint = new Point(417, 357);
    private static final Point mineExit = new Point(156, 90);
    private static final Point mineExitPoint = new Point(53, 399);
    private static final Point mineEntrance = new Point(45, 397);
    private static final Point mine = new Point(167, 105);Would get changed to something totally different, while the only functions used on those points are equals/distance.
Here is an image of the Point instance while in debug mode:
http://img193.imageshack.us/img193/6774/javaerror.jpg
As you can see , mineExit takes the place of mineExitPoint (however I don't know why..), and mineExitPoint remains the same.....
Another image:
http://img6.imageshack.us/img6/9088/javaerror2.jpg
Edit: Could it be the fact that around 30 threads are checking the same static/final variable at once?
Edited by: Naki on Jul 1, 2009 6:43 PM

Similar Messages

  • Defining a FINAL Variable?

    1. What is the advantage of defining a variable as final.?
    For example:
    In the System class,which is a final class,the static
    field variable 'out' is final.
    public final class System{
    public static final PrintStream out;
    2.Do we ever need to define a final variable ?
    3.Can a class which is not final have a final variable?

    This should not happenI've been tripped up by precisely this happeningon
    occasion.I haven't, at least not as far as public finalstatic
    variables are concerned.andyba,
    I'm about to bet my right hand on the fact that you
    are wrong. Just look at the compiled classfiles (in a
    disassembler, or decompiler). The original class that
    held the constant isn't referenced.
    You can read more on this in this article:
    http://www.javaworld.com/javaworld/javaqa/2003-03/02-qa
    0328-constant.html
    "According to the Java Language Specification, any
    static final field initialized with an expression that
    can be evaluated at compile time must be compiled to
    byte code that "inlines" the field value. That is, no
    dynamic link will be present inside class Main telling
    it to obtain the value for A from InterfaceA at
    runtime. "
    /KajOk, I admit that the JLS enforces inlining of references to final static fields that are initialised by an expression that is evaluable at compile time means I was wrong on that count.
    One reason why I am rarely, if ever, caught out by this is because I don't make regressive API changes, in this instance that means static final initialized field values do not change once they are fixed.
    Note I did say that API changes of any nature do not "require" a recompilation, I said that it is recommended and therefore a sensible thing to do.
    It is practically a golden rule in Software Development that once an API becomes public no
    regressive/subtractive changes to that API should be made. This is one reason why the Java APIs are
    becoming cluttered with deprecated annotations all over the place and why, to date, you rarely see
    regressive/subtractive API changes in Java.
    This rule has to be treated as "golden" simply because you will not always have the chance to recompile your code when deploying your application.
    This can be especially problematic when deploying Remote or Web/EJB Applications to container platforms that are not known at development time.

  • Problem with final variables and inner classes

    variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
    Is there any solution to this?
    Exception is:
    java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
         at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
         at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
         at java.awt.Component.processMouseEvent(Component.java:5131)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • Why only final variables can be accessed in an inner class ?

    Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
    1. Why should i declare them as final ? What's the reason?
    2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.

    (Got an error posting this, so I hope we don't end up with two...)
    But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
    Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
    If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
    Or is there any alternate way?Any alternate way to do what?

  • HELP: Cannot refer to non-final variable inside inner class

    Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
    Can anyone offer any advice how to fix this?
    static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
         boolean bDone = false;
         Element e;
         SAXReader sax          = new SAXReader();
         FileInputStream fis     = new FileInputStream( args.getInputFile() );
         Document document     = sax.read( fis );
         Element root = document.getRootElement();
         if( root.getName().equals( "Sheet" ) )
              XMLParser.iterateElements( root,     new XMLElementCallback()
                                                      public void onElement( Element element )
                                                           XMLParser.iterateAttributes( element,     new XMLAttributeCallback()
                                                                                                   public void onAttribute( Element element, Attribute attribute )
                                                                                                        if( attribute.getName().equals( "guid" ) )
                                                                                                             e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
                                                                                                             // WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
                                                                                                             for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
                                                                                                                  Attribute a = (Attribute)it.next();
                                                                                                                  if( a.getName().equals( "randOffset" ) )
                                                                                                                       Integer i = new Integer( resolver.getTotalPermutations() );
                                                                                                                       a.setValue( i.toString() );
                                                                                                                       bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
              if( ( !bDone ) && ( e != null ) )
                   Integer i = new Integer( resolver.getTotalPermutations() );
                   e.addAttribute( "randOffset", i.toString() );                                                                                                                                            
         FileOutputStream fileOut     = new FileOutputStream( args.getInputFile() );          
         OutputFormat format               = OutputFormat.createPrettyPrint();          
            XMLWriter xmlWriter               = new XMLWriter( fileOut, format );
            xmlWriter.write( document );
            fileOut.close();
    }PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
    Thanks in advance.

    It is already set to that - it does look correct in Eclipse, honest.
    It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
    I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Non-final variable inside an inner class - my nemisis

    I have an issue with accessing variables from an inner method. This structure seems to allow access to the text objects but not to the button object. This comes from a bit of example code that just illustrates a simple form window with text fields and buttons that read them.
    At the start of the class I have text objects defined like this:
    public class SimpleGUI extends Composite {
    Text nameField;
    Text junkField;
    // Constructors come next, etc...
    Later within this class there is a method to create some GUI stuff, and then to create a button and when pressed access and print the text to the console
    protected void createGui(){
    junkField = new Text(entryGroup,SWT.SINGLE); //Ross
    junkField.setText("Howdy");
    Button OKbutton = new Button(buttons,SWT.NONE);
    OKbutton.setText("Ok");
    OKbutton.addSelectionListener(
    new MySelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
    System.out.println("Name: " + nameField.getText());
    System.out.println("Junk: " + junkField.getText());
    And that all works fine. So within the inner class, the object junkField can be accessed nicely.
    However if I try to do the same with the button (I want to change the label on the button after it's pressed) I get errors for trying to access a non-final object in an inner class.
    I tried to handle the button similar to the text, adding this after the text defs:
         Button myButton;
    and under the println's in the inner class I wanted:
    if OKbutton.getText.equals("OK") {  OKbutton.setText("NotOK")}
    That's when I get an issue with "cannot refer to a non-final variable inside an inside class defined in a different method"
    Now, if I move the button declaration into the createGui method, and declare it with "final Button myButton" it works.
    Why does the button need different treatment than the text?
    Is this a suitable method to make my button change it's label when pressed, or is this sloppy?

    Button is a local variable. The anonymous inner class object you create can continue to exist after the method ends, but the local variables will not. Therefore, as the error message says, you must make that local button variable final if you want to refer to it inside the anon inner class. If it's final, a copy of its value can be given to the inner class--there's no need to treat it as "variable."

  • Final variables

    Hello All
    I have a question and this contradicts what I have learned so I will like to have a good explanation for this.
    public class Foo {
    private final int x = 5;
    private byte b = x;
    will this compile? The answer is YES it will compile. Now if you take out the final keyword from int x will it compile? The answer is NO it will not.
    Why is this???????
    Thanks in Advance for your help!!!!

    sorry, but my compiler (jdk1.3) compiles the code :
    public class test
    private int x = 5;
    private int b = x;
    There is one thing you are missing is that it is instead of int b it should be byte b, now let see if you can make the above code compile under the jdk1.3 compiler. Now change the private int x to private final int x and compile your code...
    I think the compiler inserts an implicit (invisible)
    constructor that is called before any other explicitly
    defined constructor. And this implicit constructor
    makes the assignments, and thus you can use any
    non-static and non-final expression for
    initialization. Even this :
    class a
    int x;
    class b
    int y = x;
    And this really makes sense !!!
    When class a instanciates class b (if there was an
    explicit constructor), the implicit constructor first
    assigns x to y and after that the explicit constructor
    is called.
    also think of that :
    public class test
    int x;
    int y = x;
    this also compiles, because all variables are always
    (implicitly) initialized with 0 (and corresponds like
    false and null).
    enough ?I think you are right the compiler might insert an implicit(invisible) constructor, but the above explanation still doesn't explain why it treats final variable differently then non-final variables??? Thanks for replying!!!!

  • Synchronize on objects held in non-final variables?

    [This thread|http://forums.sun.com/thread.jspa?messageID=10775877#10775877] and post got me thinking:
    linuxisbest.eric wrote:
    I have noticed in my textbook that it creates a String in two ways:
    String a = new String("Hello");and
    String a = "Hello";Which one should I use? Is there any practical difference?
    YoungWinston wrote:Pick door number two linux ... unless you plan on synchronizing on it, that is.
    WinstonIs it best practice to only synchronize on objects held in final variables?
    Edited by: Encephalopathic on Jul 26, 2009 5:46 AM

    gnat wrote:
    Is it best practice to only synchronize on objects held in final variables?
    Above [best practices|http://en.wikipedia.org/wiki/Best_practices] apply to cases when lock is not intended to change.
    I think that there could be cases when lock is actually intended to change and therefore shouldn't be final. Here's an example of caching code I've seen recently:
    private final ConcurrentMap<Integer, Object> pendings
    = new ConcurrentHashMap<Integer, Object>();
    public Object loadEntity(int entityId) {
    Object lock = new Object(); // shouldn't be final, see below
    Object prev = pendings.putIfAbsent(entityId, lock);
    if(prev != null) {
    // without using prev lock, there would be a chance
    //  for concurrent threads to perform redundant invocation
    //  of retrieveEntityFromSomewhereSlowly for same entityId
    lock = prev;
    Object res;
    synchronized (lock) {
    res = getEntityFromCacheQuickly(entityId);
    if (res == null) {
    // cache miss - retrieve entity slowly:
    res = retrieveEntityFromSomewhereSlowly(entityId);
    pendings.remove(entityId);
    gnat,
    Huh? Please could you try to talk me through that code... At first glance, I don't follow it... I think it's still got "unprotected race conditions", but after reading it through several times (in the course of trying to frame a post saying basically "I don't think that will work, and here's why" I now think I understand how it does work (almost all the time), but I'd just really really like some validation of my mis/understanding.
    So... Here's how I think that works... please could you verify or repudiate my understanding.
    package forums;
    import java.util.Random;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.ConcurrentHashMap;
    class GnatsThreadsafeCache
      private static final Random random = new Random();
      // pending locks := entityId --> lock
      private final ConcurrentMap<Integer, Object> pendingLocks = new ConcurrentHashMap<Integer, Object>();
      // cache := entityId --> entity
      //          1        --> "1"
      private final Map<Integer, Object> cache = new HashMap<Integer, Object>();
      public Object loadEntity(int entityId) {
        Object lock = new Object(); // shouldn't be final, see below
        // putIfAbsent: If the specified key is not already associated with a value,
        //  associate it with the given value. Returns the previous value associated
        //  with the specified key, or null if there was no mapping for the key.
        Object previousLock = pendingLocks.putIfAbsent(entityId, lock);
        if(previousLock != null) {
          // without using previousLock lock, there would be a chance
          //  for concurrent threads to perform redundant invocation
          //  of retrieveEntityFromSomewhereSlowly for same entityId
          lock = previousLock;
        Object entity;
        synchronized (lock) {
          entity = getEntityFromCacheQuickly(entityId);
          if (entity == null) {
            // cache miss - retrieve entity slowly:
            entity = retrieveEntityFromSomewhereSlowly(entityId);
            addEntityToCache(entityId, entity);
        pendingLocks.remove(entityId);
        return entity;
      private Object getEntityFromCacheQuickly(int entityId) {
        DEBUG("> getEntityFromCacheQuickly("+entityId+")");
        Object entity = cache.get(entityId);
        DEBUG("< getEntityFromCacheQuickly returns "+entity);
        return entity;
      private Object retrieveEntityFromSomewhereSlowly(int entityId) {
        DEBUG("> retrieveEntityFromSomewhereSlowly("+entityId+")");
        try{Thread.sleep(random.nextInt(1000));}catch(InterruptedException e){System.err.println(e);}
        Object entity = Integer.toString(entityId);
        DEBUG("< retrieveEntityFromSomewhereSlowly returns "+entity);
        return entity;
      private void addEntityToCache(int entityId, Object entity) {
        DEBUG("| addEntityToCache("+entityId+", "+entity+")");
        cache.put(entityId, entity);
      public static void main(String[] args)
        final GnatsThreadsafeCache cache = new GnatsThreadsafeCache();
        for (int i=0; i<10; i++) {
          new Thread(
            new Runnable() {
              @Override
              public void run() {
                int i = random.nextInt(4);
                Object entity = cache.loadEntity(i);
                DEBUG("~ "+i+"-->"+entity);
          , "Thread"+i).start();
      private static void DEBUG(String message) {
        System.err.println(Thread.currentThread().getName()+": "+message);
    }How it works:
    1. create a new lock object.
    2. check if entityId exists in the previousLock list... that's a ConcurrentMap so the putIfAbsent operation is atomic (i.e. syncronised on the previousLock object).
        ~  This operation is "garanteed fast"; ergo it involves no heavy "business object" creation/retrieval.
    3. Now, if the entityId already exists in the previousLock list we syncronize on it, allowing one-thread-at-a-time to traverse "the crytical block" where we check if the-entity associated with the-given-entityId is allready cached, and retrieve it, otherwise create a new one (which will take an arbitrary "long time").
    So what? Well I think it means that we've reduced contention to the individual entity level, as apposed to the "collection level"; as you would get if you just used a "standard" ConcurrentMap as the cache... which means that we've (probably) increased the throughput because each thread is blocked only upon those other threads which definately would stuff-them-up (waiting for the heavy "business object" creation routine to complete); as apposed to those that just might stuff them up (but won't because they're actually retrieving different entities).
    In short: It's a way of blocking on distinct keys?
    Is that correct?
    Thanx in advance for your thoughts.
    Cheers. Keith.
    Edited by: corlettk on 1/08/2009 11:05 ~~ Removed extranious cache.get from retrieveEntityFromSomewhereSlowly.

  • Final variables and try blocks

    If you tried to initialize a final variable within a try block, you would get a compile-time error.
    Here's an example class:
    class Example {
        private final String example;
        public Example() {
            try {
                example = "Example";
            } catch (Exception e) {
                // Just an example.
    }Obviously you wouldn't need to try-catch something like this (it's a stupid example - I know) , but the point is, the code wouldn't compile, and would return an error saying something like "example may not have been initialized".
    So I've got two questions. Why is this, and is there any way around it?
    Thanks in advance :)

    Why is thisThe actual error message is "The blank final field example may not have been initialized". The Java compiler insists that all the fields have some actual value when a constructor has done its thing. Nonfinal fields will have the "default" value of null, but this is not so for final fields: if they had a default value, you couldn't change them from that default because they're final!
    Once you enter a try block the compiler has no way of knowing that the assignment line will ever get carried out. Some exception might occur and the example field would be left uninitialised ie having no value whatsoever, not even null.
    is there any way around it?In the catch part you could throw the exception and let the caller deal with it.
    Or you could try and assign some value to example within the catch part. Now the compiler will complain "The final field example may already have been assigned". Supposing you wanted it to end up as null in this case (it's not clear why though... But you may have a sensible "default" if for example a file can't be written to or some other exceptional state has occured)
    class Example {
        private final String example;
        public Example() {
            String str;
            try {
                str = "Example";
            } catch (Exception e) {
                str = null;
            example = str;
    }

  • Local final variables

    Hi!
    I suppose this topic pops up from time to time in forums (I've found some threads after google-ing some), but I couldn't find any authentic answers to this.
    According to the standard coding guidelines, how on Earth should you write local final variables?
    The java coding guidelines don't explicitly mention this case, only class-level final (static final) variables and some "ANSI" constants. (I don't have any idea what "ANSI constant" is supposed to mean, anyway).
    Thanks!

    public int getSomeValue(final String parameter) {
    final int length = parameter.getLength();
    // do something
    }Would you call "length" a constant here? Obviously
    not, so why do we declare it final? Because it
    doesn't change during the execution of this method
    and to avoid accidentally assigning a different value
    to it.I'm not sure I wouldn't. For several years I've been pretty satisfied with C++'s notion of "const" (in fact, I really miss real "const" functionality in Java, but that's another story).
    You could write the equivalent in C++:
    int getSomeValue(const std::string parameter) {
    const int length = parameter.length();
      // or .size()? I don't remember, but doesn't matter... :)
    }You could even write things like this:
    for(int i=0;i<5;++i) {
    const int j = 2*i;
    std::cout << j << endl;
    }So, C++ says: if a variable is "const", its value won't change after it's created. The way I see it, the const variable is "recreated" every time you step into the block where it's defined from the outside. (I don't know whether it looks like the same from the implementation point of view, but that doesn't matter.)
    And whatever C++ says, it's so, because it is a correct language. :)
    Anyway, what you're saying makes sense, and if there's a more explicit way of saying "this is a constant" -as you suggested-, I'm going to use it.
    But about the naming convention, I see there's a pretty good unison here, so thanks! :)

  • "Manipulating final variables"

    Hi,
    I was going through a Java book, where I came across this statement:
    "Final variable can be manipulated unless it's immutable."
    What do this mean? If it can be manipulated can you give an example?
    Thanks.

    final  int[] fred = {0,1,2,3,4};
    fred[2] = 7;The reference is final and cannot be changed but the
    object it points to can be internally modified.That's why, in this cases, you should make defensive copies:
    public class A {
         private final int[] fred = {0, 1, 2, 3, 4};
          * @return the fred
         public int[] getFred() {
              return fred.clone();
         public A(){
         }Now, even if you do something like this
    public static void main(String[] args) {
              A a = new A();
              System.out.println(a.getFred()[2]);
              a.getFred()[2] = 3;
              System.out.println(a.getFred()[2]);
         }the output is
    2
    2Manuel Leiria

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • AS3 in timeline - variable changes value on its own

    I've just started working with Flash CS4 and Actionscript 3 after being away from Flash for almost 10 years.
    I've set up a menu that allows users to select from five sections. When users select an option, flow goes to the corresponding section of the timeline and a movieclip plays. Stop actions prevent flow from continuing past the current section. A home button takes users back to the menu in the first frame. This works just fine.
    The client wants to provide a 'next' button which should play through all sections in sequence when the learner clicks it. I've defined a variable which I set to true when the user clicks 'next'. I've added if...else logic to the stop actions:
      trace("nextClicked "+nextClicked);
      if (nextClicked == true)
          play();
      else
          stop();
    This should stop flow unless the play button has been pressed setting the variable nextClicked to true. That's not what happens - flow stops even if when I click the 'next' button. I added the trace to verify the variable has the correct value and discovered that the variable value resets to false from true before it gets to this script.
    What am I missing about ActionScript 3 that might account for this behaviour? I have tried to read the Actionscript 3 materials but I get bogged down in the complexity of the programming requirements and the lack of depth in the examples provided. I'm sure the examples are perfectly adequate if you're trying to do what they illustrate but I haven't found an example that fits what I'm trying to do here.
    Thanks.

    Thank you for your suggestion:
    I have declared the variable at the beginning. This is a sample of the code in the first frame:
    //define variable
    var nextClicked:Boolean;
    //define event listeners and the corresponding functions for menu buttons
    //Me
    btn_me.addEventListener(MouseEvent.CLICK, gotome);
    function gotome(event:MouseEvent):void {
        //set var to false to indicate Next has not been clicked
        var nextClicked = false;
        trace("Me selected "+nextClicked);
        gotoAndPlay("me");
    [.....more code defining more listeners...]
    //define listener for Next button
    btn_next.addEventListener(MouseEvent.CLICK,gonext);
    function gonext(event:MouseEvent):void {
        //set var to true to indicate Next has been clicked
        var nextClicked=true;
        trace("Clicked next "+nextClicked);
        play();
    This seems very similar to what you suggested except you also included this line:
    Button1.label = "show Var";
    and I'm not sure what that line does. Does it set a label for the button? Since I've already set these explicitly, I don't see that this would be necessary. More importantly, I don't understand why leaving this out would cause the problem I'm having - the value of the variable changes from true to false without any code being executed.
    I'm still in the dark - and I still need to solve this.
    Thanks.

Maybe you are looking for

  • Video Capture: is this a good idea?  Also RAID 1 vs. 2 separate HDs

    Family videos on VHS. Original idea was to copy them all to DVD before the tapes degrade. Now thinking to capture the video on hard drives at the same time. This by taking video out of vhs/dvd combo unit (RCA connectors) into Canopus box, then via fi

  • Pdf file wont add to itunes

    Hi, I tried to add a pdf file to itunes and it wont work.  I tried selecting "Add File" and it let me selcet it and acted like it was adding, but wasnt in my library under books, or any other tab.  I tried this several times to no previal.  Then I tr

  • Setup seems right but still TNS-12535: TNS:operation timed out

    I have Oracle express Edition installed on Fedora 4. I know the listener is started and believe the tnsnames.ora is configured properly but still get a timout when I try to connect with SQL*Plus. I am able to get into SQL with tue GUI tools but want

  • Alter table partition based on date and status

    Hi! I have a strange scenario where in 100,000 to 500,000 records are created every day and records are to be maintained for 3 yrs. So to manage this table we have it partitioned based on date (so every day one new partition is created). And any part

  • Polling IMS-DB using the IMS-DB Adapter

    Has anyone used the IMS-DB adapter to poll for changes within an IMS table? Essentially the logic would go as follows: Select all records where status is New For each record Mark as Pending Validation (in IMS DB) Submit to other system End for Wait 1