java array initialization

来源:互联网 发布:淘宝网牛仔半身裙 编辑:程序博客网 时间:2024/06/08 07:45

the method of initialization 

1 static

type[] name;

name=new type[]{e1,e2,,};

or:

type[] name={e1,e2,,};

2.dynamic

type[] name;

name=new type[n];

or

type[] name=new type[n];




1.1

public class helloworld 
{
public static void main(String[] args) 
{
String[] app;
app=new String[]{"hello","world"};

int count=0;
while (count<app.length)
{
System.out.println(app[count]);
count++;
}

}
}

1.2

public class helloworld 
{
public static void main(String[] args) 
{
String[] app={"hello","world"};
int count=0;
while (count<app.length)
{
System.out.println(app[count]);
count++;
}

}
}

1.3

public class helloworld 
{
public static void main(String[] args) 
{
int[] app;
app=new int[5];

int i=0;
while (i<app.length)
{
app[i]=i;
System.out.println(app[i]);
i++;
}

}
}

1.4

public class helloworld 
{
public static void main(String[] args) 
{
int [] app=new int[5];
int i=0;
while (i<app.length)
{
app[i]='a'+i;
System.out.println(app[i]);
i++;
}

}
}



2.

public class helloworld 
{
public static void main(String args[]) {  
         Date days[] ;  //Date[] days;is preferable
         days = new Date[3] ;  

         days[0] = new Date(2015,3,20) ;  
         days[1] = new Date(2008,2,31) ;  
         days[2] = new Date(2008,4,4) ;
int i=0;
while (i<days.length)
{
System.out.println(days[i].year+"\\"+days[i].month+"\\"+days[i].day);
i++;
}
     }  
}  
 
class Date  
{  
         int year,month,day ;  
         Date(int year ,int month ,int day)
{  
         this.year = year ;  
         this.month = month ;  
         this.day = day ;  
        }  
}



3.

public class helloworld 
{
public static void main(String args[]) 
{
Date days[]={new Date(2009,10,25),new Date(2010,3,23),new Date(2001,2,5)};// Date[] days=....
 
int i=0;
while (i<days.length)
{
System.out.println(days[i].year+"\\"+days[i].month+"\\"+days[i].day);
i++;
}
}
}  
 
class Date  
{  
int year,month,day ;  
Date(int year ,int month ,int day)
{  
this.year = year ;  
this.month = month ;  
this.day = day ;  
}  
}

 



 

0 0
原创粉丝点击