Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable r might not have been initialized

Tags:

java

final

There's a very simple program:

public class A {
    public static void main(String[] p) {
        final Runnable r = new Runnable() {
            public void run() {
                System.out.println(r);
            }
        };
        r.run();
    }
}

And this gives:

$ javac A.java 
A.java:6: variable r might not have been initialized
                System.out.println(r);
                                   ^
1 error
  1. Why?
  2. How can a Runnable reference a variable pointing to it?

(In the real code, there is one more level (a listener), and referencing via this does not work)

like image 314
18446744073709551615 Avatar asked Nov 12 '13 14:11

18446744073709551615


People also ask

What does it mean when a variable might not have been initialized?

Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).

What happens when the local variable is not initialized?

If the programmer, by mistake, did not initialize a local variable and it takes a default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize it with some value before they access the variable to avoid the usage of undefined values.

What does it mean to initialize a variable?

To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.


1 Answers

In this case, you can use "this" to avoid the compilation error:

    final Runnable r = new Runnable() {
        public void run() {
            System.out.println(this); // Avoid compilation error by using this
        }
    };
like image 139
david m lee Avatar answered Oct 17 '22 14:10

david m lee