变量:
数据类型 变量名[=初始值];
成员变量和局部变量
package helloworld;
public class helloworld {
int x; //成员变量
public static void main(String[] args) {
// TODO Auto-generated method stub
int y; //局部变量
System.out.println("Hello World!");
}
}
常量:
final 数据类型 变量名=初始值;
常量有三种类型:静态常量、成员常量和局部常量。
静态常量,在final之前用public static修饰,用来替代保留字const。public static修饰的常量作用域是全局的。
代码如下:
package helloworld;
public class helloworld {
public static final double PI=3.14; //静态常量
final int x=10; //成员常量
public static void main(String[] args) {
// TODO Auto-generated method stub
final int y=20; //局部常量
System.out.println("Hello World!");
}
}
本文介绍了Java编程中的变量和常量的使用。变量包括成员变量和局部变量,如int x和int y。成员变量在类中定义,而局部变量在方法内部声明。常量则分为静态常量和成员常量,如public static final double PI和final int x,其中静态常量全局可见。代码示例展示了如何声明和使用这些概念。
906

被折叠的 条评论
为什么被折叠?



