1、 聲明數組
語法: 數據類型[ ] 數組名;
或者 數據類型 數組名[ ];
其中,數組名可以是任意合法的變量名,如:
int[] scores;double height[];String[] names;2、 分配空間
簡單地說,就是指定數組中最多可存儲多少個元素
語法: 數組名 = new 數據類型 [ 數組長度 ];
其中,數組長度就是數組中能存放元素的個數,如:
scores = new int [5];height = new double[5];names = new String[5];3、 聲明數組的同時分配空間
int[] scores=new int[5]//習慣使用此法3、 聲明、分配、賦值 java 中提供了一種直接創建數組的方式,它將聲明數組、分配空間和賦值合并完成。如:
int[] scores={78,91,84,68};//等價于int[] ages=new int[]{15,18,22,25};應用舉例:
public class HelloWorld { public static void main(String[] args) { // 定義一個長度為5的字符串數組,保存考試科目信息 String[] subjects = new String[5] ; // 分別為數組中的元素賦值 subjects[0] = "Oracle"; subjects[1] = "php"; subjects[2] = "linux"; subjects[3] = "Java"; subjects[4] = "HTML"; System.out.新聞熱點
疑難解答