I am currently studying for the Java Silver exam. During my studies, I often mistakenly remembered or confused the for sentence, so I will summarize it from the basics in my own words.
for (initialization statement; conditional statement; update statement) { /// Iterative processing }
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
① Initialization sentence ② Conditional statement ③ Iterative processing ④ Update ⑤ Finish
for (type variable name: set) { /// Iterative processing }
int[] array = {1, 2, 3}
for(int num : array) {
System.out.println(num);
}
An image of taking out the contents of the set one by one from the beginning to the end.
break Example: for (initialization statement; conditional statement; update statement) { if (conditional statement) { break } /// Iterative processing }
for(int i = 0; i < 10; i++) {
if (i = 5) {
break;
}
System.out.println(i);
}
When it breaks, it exits the iterative process (ends). In this case, System.out.println (i); after i = 5 is not executed.
continue Example: for (initialization statement; conditional statement; update statement) { if (conditional statement) { continue } /// Iterative processing }
for(int i = 0; i < 10; i++) {
if (i = 5) {
break;
}
System.out.println(i);
}
skips the one-time iteration process that was continued. In this case, only System.out.println (i); when i = 5 is not executed, and everything else is executed.
I have summarized the for statements that are often used in business. Personally, when I was a student, I was studying the basics of C language, and it was difficult to grasp the feeling of extended for sentences, so I would like to grasp it firmly.
Reference: Sumito Shiga "Thorough Strategy Java SE 8 Silver Problem Collection [1Z0-808] Compatible Thorough Strategy Series", Sokius Japan Co., Ltd., 2016
Recommended Posts