[英]New to java; how do I make the String static within conditionals?
public class testing {
public static void main(String[] args)
{
boolean a = true;
if (a) {
public static String word = " ";
}
else if (a == false) {
public static String word = "not";
}
System.out.println(word);
}
}
Instead of printing the value, it tells me "Illegal modifier for the variable word; only final is permitted. I tried to use public static final String word = "not";
but I still got an error saying that it is wrong.它没有打印值,而是告诉我“变量词的非法修饰符;只允许使用 final。我尝试使用
public static final String word = "not";
但我仍然收到错误消息,说这是错误的。
The variable should be created outside of your main
:该变量应该在您的
main
之外创建:
public class Testing {
public static String word;
public static void main(String[] args)
{
boolean a = true;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}
Alternatively you can create a variable inside you main
as well.或者,您也可以在
main
中创建一个变量。
public class Testing {
public static void main(String[] args)
{
boolean a = true;
String word;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}
When variables, blocks or methods are made static , they are made available during load time.当变量、块或方法被创建static时,它们在加载期间可用。 Rest all reserves memory during run time.
Rest 在运行时全部保留 memory。 All the local variables created inside a static method are present in the method stack, which as a package is already present during load time.
在 static 方法中创建的所有局部变量都存在于方法堆栈中,而 package 在加载时已经存在。 So creating a static variable inside method, be it be static or non-static method, is not allowed.
因此,不允许在方法内部创建 static 变量,无论是 static 还是非静态方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.