题目:创建一个String对象数据,并为每一个元素都赋值一个String。用for循环来打印该数组。
public class test { public static void main(String[] args) { String []strs=new String[]{"1","2","3","4"}; for(String str:strs){ System.out.println(str); } } }
题目:创建一个类,他有一个接受一个String参数的构造器。在构造阶段,打印该参数。创建一个该类的对象引用数组,但是不实际去创建对象赋值给该数组。当运行程序时,请注意来自对该构造器的调用中的初始化消息是否打印了出来。
public class test { public void test(String str){ System.out.println(str); } public static void main(String[] args) { test []t=new test[10]; } }
运行之后什么都不会发生,因为
test []t=new test[10];
执行过后还只是一个引用数组,直到给它赋值才初始化结束。
题目:通过创建对象赋值给引用数组,从而完成前一个练习。
public class test { public test(String str){ System.out.println(str); } public static void main(String[] args) { test []t=new test[10]; for(int i=1;i<=10;i++){ t[i-1]=new test(""+i); } } }