为SCJP 认证考试而努力

JAVA二级考试已经通过了一年了,最近准备SCJP的认证考试,下载了一些资料,从最基础的开始复习。
 
/**
* @author 木炭
* 数组
*/

public class Array {

  /**
    * @param args
    */

  public static void main(String[] args) {
    //声明一个数组不需分配任何存储空间
    //int num1[5];];//错误,Syntax error on token "5", delete this token
    //一个数组的大小将在数组使用new 关键字真正创建时被给定,例如:
    int num2[];
    num2 = new int[5];
    //这个例子也可以使用一行语句完成:
    int num[] = new int[5];
    //下面的程序会引起一个 ArrayIndexOutOfBoundsException 异常。
    /*for(int i =0; i<6; i++){
    num[i]=i*2;
    }*/

    //访问一个Java 数组的标准习惯用法是使用数组的length 成员
    for(int i =0; i<num.length; i++){
    num[i]=i*2;
    System.out.println("num[i]="+num[i]);
    }
    
    //数组声明和初始化相结合
    int k[]=new int[] {0,1,2,3,4};
    //注意,你没有必要确定数组元素的数量。
    //int[] k=new int[5] {0,1,2,3,4}; //Cannot define dimension expressions when an array initializer is provided
    //你可以创建数组的同时确定任何数据类型
    String s[]=new String[] {"Zero","One","Two","Three","Four"};
    System.out.println("s[0]="+s[0]);//这句将会输出s[0]=Zero。
    
    //数组的默认值,整型的数组总是被置0,布尔值总是被置false
    int[] ai = new int[10];
    System.out.println("ai[0]="+ai[0]);
    
    int ia1[]= {1,2,3};
    int[] ia2 = {1,2,3};
    int ia3[] = new int[] {1,2,3};
    System.out.print("ia3.length="+ia3.length);
    
  }

}
 
问题 )怎样通过一个语句改变数组大小同时保持原值不变?
1) Use the setSize method of the Array class
2) Use Util.setSize(int iNewSize)
3) use the size() operator
4) None of the above
答案 4)你不能改变一个数组的大小。你需要创建一个不同大小的临时数组,然后将原数组中的内容放进去。
问题 ) 你想用下面的代码查找数组最后一个元素的值,当你编译并运行它的时候,会发
生什么?
public class MyAr{
public static void main(String args[]){
int[] i = new int[5];
System.out.println(i[5]);}
}
1) Compilation and output of 0
2) Compilation and output of null
3) Compilation and runtime Exception
4) Compile time error
答案 3) 会得到一个运行时错误。因为数组从0 开始索引,并且最后一个元素是i[4]而不是i[5]。
java.lang.ArrayIndexOutOfBoundsException:
问题 )一个多维数组的初始化,下面哪一个能工作?
1) int i =new int[3][3];
2) int[] i =new int[3][3];
3) int[][] i =new int[3][3];
4) int i[3][3]=new int[][];
答案 3) int[][] i=new int[3][3];
问题 )当你试着编译运行下面的代码的时候,可能会发生什么?
public class Ardec{
public static void main(String argv[]){
Ardec ad = new Ardec();
ad.amethod();}
public void amethod(){
int ia1[]= {1,2,3};
int[] ia2 = {1,2,3};
int ia3[] = new int[] {1,2,3};
System.out.print(ia3.length);}
}
1) Compile time error, ia3 is not created correctly
2) Compile time error, arrays do not have a length field
3) Compilation but no output
4) Compilation and output of 3
答案 4) Compilation and output of 3  所有的数组的声明都是正确的。
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章