为什么需要初始化String变量,有时在java中声明它们时不需要初始化?

时间:2017-05-09 15:52:03

标签: java string initialization applet paint

我正在编写一个简单的applet程序,它从用户那里获取输入并显示它们。 `

EXPSPACE & EXPTIME

` 在paint()方法中为什么必须将str变量声明为null,而在没有初始化的情况下声明另一个字符串变量s1是否正常? 如果没有初始化str变量,IT就不会编译。

3 个答案:

答案 0 :(得分:3)

因为你只在保证有值的地方使用s1的值,但你在一个地方(str处理程序)使用catch所在的地方如果你没有将它初始化为某个值,那么> 保证没有值,因为毕竟在分配给try之前,str中可能会抛出异常

如果您将g.drawString(str,75,75); 的呼叫移至 try,则不需要= null初始值设定项。

旁注:s1已经是一个字符串,因此无需执行str = String.valueOf(s1)。只需在s1行中使用g.drawString(str,75,75);

答案 1 :(得分:0)

Java编译器允许未初始化的变量,只要它们在被用于某些东西时保证具有值。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "additionalProperties": true,
  "patternProperties": {
    "[a-z]": {}
  },
  "maxProperties": 1,
  "minProperties": 1
}

由于上一行已初始化String s1,str = null; // s1 is not set g.drawString("input in the box",10,50); try{ s1=text1.getText(); // s1 is set str=String.valueOf(s1); // s1 is used } catch(Exception e){} g.drawString(str,75,75); ,因此可以安全地将其传递给s1

String.valueOf的问题是它在try-catch块之后使用,它可能会跳过它设置的行。

str

只要在初始化之前有可能使用变量,编译器就会拒绝它。在这种情况下,您可以将String s1,str; // str is not set g.drawString("input in the box",10,50); try{ s1=text1.getText(); // if this throws an exception... str=String.valueOf(s1); // ...this is never reached } catch(Exception e){} // the exception is caught and ignored, so we continue g.drawString(str,75,75); // str is still not set - error! 设置为catch块中的默认值,或者将catch块设置为strreturn,以便只有throw行才能到达try块完成无例外。

答案 2 :(得分:0)

实例变量不需要初始化,只需要初始化局部变量(在函数或构造函数内)