Java數(shù)組聲明、創(chuàng)建、初始化基礎(chǔ)
一維數(shù)組的聲明方式:
type var[]; 或type[] var;
聲明數(shù)組時不能指定其長度(數(shù)組中元素的個數(shù)),
Java中使用關(guān)鍵字new創(chuàng)建數(shù)組對象,格式為:
數(shù)組名 = new 數(shù)組元素的類型 [數(shù)組元素的個數(shù)]
實例:
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.動態(tài)初始化:數(shù)組定義與為數(shù)組分配空間和賦值的操作分開進行;
2.靜態(tài)初始化:在定義數(shù)字的同時就為數(shù)組元素分配空間并賦值;
3.默認(rèn)初始化:數(shù)組是引用類型,它的元素相當(dāng)于類的成員變量,因此數(shù)組分配空間后,每個元素也被按照成員變量的規(guī)則被隱士初始化。
實例:
TestD.java(動態(tài)):
程序代碼:
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(靜態(tài)):
程序代碼:
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(默認(rèn)):
程序代碼:
public class TestDefault { public static void main(String args[]) { int a [] = new int [5] ; System.out.println("" + a[3]) ; } }
相關(guān)文章
java代碼獲取數(shù)據(jù)庫表里數(shù)據(jù)的總數(shù)操作
這篇文章主要介紹了java代碼獲取數(shù)據(jù)庫表里數(shù)據(jù)的總數(shù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08Spring Boot Actuator監(jiān)控器配置及使用解析
這篇文章主要介紹了Spring Boot Actuator監(jiān)控器配置及使用解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07springboot學(xué)習(xí)之Thymeleaf模板引擎及原理介紹
本文主要介紹一下SpringBoot給我們推薦的Thymeleaf模板引擎,這模板引擎呢,是一個高級語言的模板引擎,他的這個語法更簡單而且功能更強大,對springboot?Thymeleaf模板引擎相關(guān)知識感興趣的朋友一起看看吧2022-02-02