您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java如何实现数组声明和初始化

2025/11/5 15:09:26发布14次查看
一维数组的声明方式:
type var[]; 或type[] var;
声明数组时不能指定其长度(数组中元素的个数),
java中使用关键字new创建数组对象,格式为:
数组名 = new 数组元素的类型 [数组元素的个数]
实例:
testnew.java:
程序代码:
public class testnew  {       public static void main(string args[]) {           int[] s ;           int i ;           s = new int[5] ;           for(i = 0 ; i < 5 ; i++) { s[i] = i ; } for(i = 4 ; i >= 0 ; i--) {               system.out.println( + s[i]) ;           }       }   }
初始化:
1.动态初始化:数组定义与为数组分配空间和赋值的操作分开进行;
2.静态初始化:在定义数字的同时就为数组元素分配空间并赋值;
3.默认初始化:数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐士初始化。
实例:
testd.java(动态):
程序代码:
public class testd  {       public static void main(string args[]) {           int a[] ;           a = new int[3] ;           a[0] = 0 ;           a[1] = 1 ;           a[2] = 2 ;           date days[] ;           days = new date[3] ;           days[0] = new date(2008,4,5) ;           days[1] = new date(2008,2,31) ;           days[2] = new date(2008,4,4) ;       }  }   class date  {       int year,month,day ;       date(int year ,int month ,int day) {           this.year = year ;           this.month = month ;           this.day = day ;       }  }
tests.java(静态):
程序代码:
public class tests     {          public static void main(string args[]) {              int a[] = {0,1,2} ;              time times [] = {new time(19,42,42),new time(1,23,54),new time(5,3,2)} ;          }     }      class time     {          int hour,min,sec ;          time(int hour ,int min ,int sec) {              this.hour = hour ;              this.min = min ;              this.sec = sec ;          }     }
testdefault.java(默认):
程序代码:
public class testdefault     {          public static void main(string args[]) {              int a [] = new int [5] ;              system.out.println( + a[3]) ;          }     }
以上就是java如何实现数组声明和初始化的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product