【问题标题】:Errors with simple String object in JavaJava中简单字符串对象的错误
【发布时间】:2018-07-17 17:07:06
【问题描述】:

我正在尝试编译以下代码:

public class Test {

    public static void main(String[] args) {
        String final = new String("");
        final = "sample";
        System.out.println(final);
    }
}

显然,编译器向我显示以下错误:

Test.java:5: error: not a statement
    String final = new String("");
    ^
Test.java:5: error: ';' expected
    String final = new String("");
          ^
Test.java:5: error: illegal start of type
    String final = new String("");
                 ^
Test.java:6: error: illegal start of type
    final = "sample";
          ^
Test.java:7: error: illegal start of expression
    System.out.println(final);
                       ^
Test.java:7: error: illegal start of type
    System.out.println(final);
                            ^

我尝试将String final = new String(""); 替换为String final;,但编译器仍然显示这些错误。知道是什么原因造成的吗?

【问题讨论】:

  • final 是 java 中的保留关键字。您不能将其用作变量名

标签: java string declaration declare


【解决方案1】:

finalreserved Java keyword。您不能将其用作变量名。阅读有关naming of variables in Java 的更多信息。这样做:

String string = new String("");
string = "sample";
System.out.println(string);

但是,这是可能的,因为它仍然遵守分配值一次的规则:

final String string;
string = "sample";
System.out.println(string);

另一方面,如果你的意思是让Stringfinal,不是作为变量名,而是作为特征,你必须把它放在String定义的左边。但是,第二行无法编译,因为您无法修改标记为final 的变量。

final String string = new String("");
string = "sample";                // not possible, string already has a value
System.out.println(string);

变量final 的行为是你只能初始化一次。阅读更多How does the “final” keyword in Java work?

【讨论】:

    【解决方案2】:

    finaljava 中的关键字(保留字)。您不能使用关键字作为变量名。换个名字试试。

    试试这个代码:-

    public class Test
    {
      public static void main(String[] args)
      {
        String Final = new String("");
        Final = "sample";                 // final is keyword so use Final or some other names
        System.out.println(Final);
       }
     }
    

    输出:-

    sample
    

    【讨论】:

      【解决方案3】:

      final 是 Java 中的保留关键字。重命名变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 2015-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多