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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 展会结束回去,不等我,直接走了。没有团队意识。还是新员工给我打电话才知道。看在你等别人不等的份上,我不说什么,可是...
    徐州闪电阅读 183评论 0 0
  • 如何收获想要的人生? 就是放下所有不想要的,全然忠诚于自己要走的路。
    启绚呀阅读 163评论 0 0
  • 積弱百年起華夏 縱橫砥柱出南昌 綿長流水歸於海 浩蕩征途源自光 救族圖存除勁虜 立國衛道掃頹蔣 復興之日再回首 不...
    玄水青云阅读 141评论 0 1