[Java in NetBeans] Lesson 12. Arrays

时间:2022-04-15 04:28:41

这个课程的参考视频和图片来自youtube

主要学到的知识点有:

1. Array: container that holds a fixed number of values of the same type, can be access by index.

  • Create a string array and initialize the elements one by one. Index will be start from 0 to size -1.
String[] names = new String[3];
names[0] = "Tom";
names[1] = "Bob";
names[2] = "Joe";
// Below is a wrong comment
names[3] = "wrong!" // Will show error because out of the index.
  • Automatic detect the size of the array
String[] names = new String[]{"Tom", "Bob", "Joe"};

2. Go through the elements in the array.

  • for loop using index
for ( int i = 0; i < names.length; i ++){
System.out.printf("%s ", names[i]);
}
// the result will be like this
Tom, Bob, Joe
  • for loop using "foreach"
for ( String each : names){
System.out.printf("%s ", each);
}
// the result will be like this
Tom, Bob, Joe