定义程序块 例如: int a=1; if(a==1){ //程序块代码 } 指明a==1时运行的才代码
public class Test { { int a = 1; System.out.println (a); } public static void main(String[] args) throws Exception { Test t = new Test(); int[] x = new int[100]; int sum = 0; for (int i = 0; i < 100; i++) { x[i] = i+1; sum += x[i]; } System.out.println("Sum = "+ sum); } }花括号中的代码是这个类在实例化之前所做的一些操作 可以看作是构造方法之前的初始化方法 上面的代码输出的结果是1 Sum = 5050System.out.println (a);这是在Test t = new Test();之前输出 一般这种代码块都写成static,用于封装数据库操作 例如 public class DBUtil { static { try { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
例如:
int a=1;
if(a==1){
//程序块代码
}
指明a==1时运行的才代码
int a = 1;
System.out.println (a);
}
public static void main(String[] args) throws Exception {
Test t = new Test();
int[] x = new int[100];
int sum = 0;
for (int i = 0; i < 100; i++) {
x[i] = i+1;
sum += x[i];
}
System.out.println("Sum = "+ sum);
}
}花括号中的代码是这个类在实例化之前所做的一些操作
可以看作是构造方法之前的初始化方法
上面的代码输出的结果是1
Sum = 5050System.out.println (a);这是在Test t = new Test();之前输出
一般这种代码块都写成static,用于封装数据库操作
例如
public class DBUtil { static {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
String uri = "jdbc:microsoft:sqlserver://localhost:1433;database=BrightBlog";
try {
return DriverManager.getConnection(uri, "sa", "sa");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
应该是一样的道理的呀,就是一门语言的开始与结束,有自己的标识呀,一样的!这样说,你明白吗!如果你写多啦,也许可以问一个SUN呀!
时就会不同,和普通写在外边的代码没区别。
但如果是static{代码}那就是静态代码块,是在程序加载是执行,执行在main方法之前
语句块;
}语句块的作用域不能作用于{}外。
例如:
{
int i=0;
i++;
}
if(i==1) //试图在{}外访问i,错误!因为i生命周期只在{}内,{}外不可到达。
语句块;
}语句块的作用域不能作用于{}外。
例如:
{
int i=0;
i++;
}
if(i==1) //试图在{}外访问i,错误!因为i生命周期只在{}内,{}外不可到达。