java数组声明定义初始化实例与内存分析



java数组的概念是非常重要的,几乎每门编程语言都有数组的概念的。java 数组的英文为array,java数组声明定义初始化实例与内存分析。数组是相同数据类型的有序集合,数组要是对象,数组元素相当于数组的成员变量。数组长度是确定的不可变的,如果越界就会报错:ArrayIndexOutOfBoundsException。

先是声明数组的方法

int[] s ;//数组的声明

s = new int[5] ;  //数组的初始化,这说明数组也是一个对象

//需要注意的是数组的下标是从0开始的,因此数组s的第一个元素是s[0],而最后一个元素的s[4],而不是s[5]

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]) ;
}
}
}

java数组初始化:

1.动态初始化:数组定义与为数组分配空间和赋值的操作分开进行;
2.静态初始化:在定义数字的同时就为数组元素分配空间并赋值;
3.默认初始化:数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐士初始化。
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 ;
}
}

 

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数组内存分析实例:

package cn.bjsxt.array;

public class Car {
String name;

public Car(String name){
this.name= name;
}
}

package cn.bjsxt.array;

/**
* 数组的基本概念
* @author dell
*
*/
public class Test01 {
public static void main(String[] args) {
/**
* 1. 数组是相同数据类型(数据类型可以为任意类型)的有序集合
* 2. 数组也是对象。数组元素相当于对象的成员变量(详情请见内存图)
* 3. 数组长度的确定的,不可变的。如果越界,则报:ArrayIndexOutofBoundsException
*/
int[] a = new int[3];
a[0] = 23;
a[1] = 28;
a[2] = 32;

Car[] cars = new Car[4];
cars[0] = new Car(“奔驰”);
System.out.println(a.length);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}

}
}

 java 数组内存分析图:

JAVA数组基本概念以及内存分析

JAVA数组基本概念以及内存分析