相同点:
for与while实现相同的功能基本可以互换。
不同点:
for语句初始化的变量只应用在for语句的代码块中,出了for循环变量就会被释放,外面的语句无法取到for循环中的值。
举例:
int x = 1;
while(x<3)
{
System.out.println("x="+x);
x++;
}
System.out.println("x====="+x);
for(int y = 1; y < 3; y++)
{
System.out.println("y="+y);
}
System.out.println("y===="+y);
程序运行会出现错误,因为y的值在for循环外边无法取值,只在for循环内部起作用。
这里记录一点小知识
for和while语句的无限循环表示:
while(true){}
for(;😉{}