数组属于引用数据类型,其默认值为null,暂时没有任何的堆内存空间
一维数组的格式
数据类型 数组名[]=null;//声明一维数组
数组名=new 数据类型[长度];//分配内存给数组
或者:数组类型[] 数组名=null;
数组的动态初始化:先声明数组之后为数组的每个内容赋值
public class 第一个 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int score[]=null;
score=new int[3];
System.out.println("数组长度"+score.length);
for(int x=0;x<3;x++) {
score[x]=x*2+1;
}
for(int x=0;x<3;x++) {
System.out.println("score["+x+"]="+score[x]);
}
}
}
结果:数组长度3
score[0]=1
score[1]=3
score[2]=5
数组的静态初始化:在数组声明时就制定其内容
public class 第一个 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int score[]= {91,92,93,94,95,96};
System.out.println("数组长度"+score.length);
for(int x=0;x<score.length;x++) {
System.out.println("score["+x+"]="+score[x]);
}
}
}
结果:
数组长度6
score[0]=91
score[1]=92
score[2]=93
score[3]=94
score[4]=95
score[5]=96
一维数组实例演示:
求出数组中的最大最小值
public class 第一个 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int score[]= {23,42,33,87,56,34,97,65};
int max=0;
int min=0;
max=min=score[0];
for(int x=0;x<score.length;x++) {
if(score[x]>max) {
max=score[x];
}
if(score[x]<min) {
min=score[x];
}
}
System.out.println("最大值"+max);
System.out.println("最小值"+min);
}
}
结果:最大值97
最小值23
对整数型数组按照从小到大的顺序排列,并显示每一次排序结果
public class 第一个 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int score[]= {23,42,33,87,56,34,97,65};
for(int i=1;i<score.length;i++) {
for(int j=0;j<score.length;j++) {
if(score[i]<score[j]) {
int temp=score[i];
score[i]=score[j];
score[j]=temp;
}
}
System.out.println("第"+i+"次排序的结果:\t");
for(int j=0;j<score.length;j++) {
System.out.print(score[j] +"\t");
}
System.out.println("");
}
System.out.println("最终的排序结果为:\t");
for(int i=0;i<score.length;i++) {
System.out.print(score[i] +"\t");
}
}
}
结果:第1次排序的结果:
23 97 33 42 56 34 87 65
第2次排序的结果:
23 33 97 42 56 34 87 65
第3次排序的结果:
23 33 42 97 56 34 87 65
第4次排序的结果:
23 33 42 56 97 34 87 65
第5次排序的结果:
23 33 34 42 56 97 87 65
第6次排序的结果:
23 33 34 42 56 87 97 65
第7次排序的结果:
23 33 34 42 56 65 87 97
最终的排序结果为:
23 33 34 42 56 65 87 97