【问题标题】:Are initialization and assignment names for the same thing in Java (the first time but not second time)?Java中的初始化和赋值名称是否相同(第一次但不是第二次)?
【发布时间】:2012-01-04 09:15:40
【问题描述】:

只是为了在 Java 中清楚地表达出来。

原始类型:

这是一个声明权:

int a;//declared but unitialized

初始化和赋值:

a = 1;//intialization and assignment

a = 2;//this is no longer intialization but still an assignment the 2nd time?

int b = 1;//declaration and intialization = assignment combined?

b = 2;//just assignment because 2nd time?

类类型:

String str;//declaration

str = "some words";//this is also an intialization and assignment?

str = "more words"; //since new object still both intialization and assignment even 2nd time?

【问题讨论】:

    标签: java initialization declaration assign


    【解决方案1】:

    当编译器知道已设置局部变量并且可以正确读取时,它会认为变量已初始化。

    考虑这种情况,编译器无法确定 a 变量已被初始化。

    int a;
    try {
        a = 1;
        // a is initialised and can be read.
        System.out.println(a); // compiles ok.
    } catch (RuntimeException ignored) {
    }
    // a is not considered initialised as the compiler 
    // doesn't know the catch block couldn't be thrown before a is set.
    System.out.println(a); // Variable 'a' might not have been initialized
    
    a = 2;
    // a is definitely initialised.
    System.out.println(a); // compiles ok.
    

    【讨论】:

    • 好的,但是 assignment = initalization 呢?
    • 初始化只是对给定变量的第一次赋值。
    • 所以在int a; System.out.println("hello"); a = 1; a = 2; 中赋值 1 也是一个初始化,即使它没有与声明结合。
    • 好的,那么当我说第一个赋值也是初始化而第二个赋值不是并且使用原始类型进行初始化时,我是对的。但是第一个字符串类型的赋值是初始化,第二个赋值也是初始化,因为它创建了一个新对象?
    • 使用字符串文字不会创建新对象。当你初始化一个引用时,它是被初始化的引用,而不是对象。
    【解决方案2】:

    初始化是第一次赋值。总是。

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2011-08-01
      • 2011-11-21
      相关资源
      最近更新 更多