Java assign value within inner class

To be resolved

import org.junit.jupiter.api.Test;

public class TestFinal {

    @Test
    public void testFinalVar() {
        System.out.println("This is the beginning of the test.");
        final String str;
        Thread t = new Thread() {
            public void run() {
                for (int x = 1; x <= 3; x ++) {
                    System.out.println("This is the " + x + " round of the thread.");
                }
                str = "This is the end of thread.";
                System.out.println(str);
            }
        };
        t.start();
        System.out.println(str);
    }
}

It shows error:

str = "This is the end of thread.";
Cannot assign a value to a final variable "str"

------------------------------------------------------------------------------------------

While:

import org.junit.jupiter.api.Test;

public class TestFinal {

    @Test
    public void testFinalVar() {
        System.out.println("This is the beginning of the test.");
        final String[] str = new String[1];
        Thread t = new Thread() {
            public void run() {
                for (int x = 1; x <= 3; x ++) {
                    System.out.println("This is the " + x + " round of the thread.");
                }
                str[0] = "This is the end of thread.";
                System.out.println(str[0]);
            }
        };
        t.start();
        System.out.println(str[0]);
    }
}

Prints:

This is the beginning of the test.
null
This is the 1 round of the thread.
This is the 2 round of the thread.
This is the 3 round of the thread.
This is the end of thread.

------------------------------------------------------------------------------------------

And

public class TestFinal02 {
    public static void main(String[] args) {
        final int[] i = new int[1];
        Thread thread = new Thread() {
            public void run() {
                for (int x = 1; x <= 3; x ++) {
                    i[0] = x;
                    System.out.println("In: " + i[0]);
                }
            }
        };
        thread.start();
        System.out.println("Out: " + i[0]);
    }
}

Prints:

Out: 0
In: 1
In: 2
In: 3

你可能感兴趣的:(Java assign value within inner class)