14. java 数组学习

我们来使用java的数组的例子,来学习一下java的数组使用。

例子1 数字数组

int[] stu = new int[2]

例子2 字符串数组

String[] str = new String[3]; //3 表示数组长度

例子3 二纬数组

String[][] tarr = new String[2][2];

建立文件JavaArray.java

/**
java-er.com
learn java is so easy
*/
import java.util.*;
public class JavaArray
{	
	public static void main(String[] args){		
		String[] arr = new String[3]; //initialize the array
		arr[0] = "a";
		arr[1] = "b";
		arr[2] = "c";
 
		for(int i = 0 ; i < arr.length;i++){
			System.out.println("arr["+i+"] " + arr[i]);
		}
 
		// another way to initialize the array and assign the value to the array
		System.out.println("--------------------------");
		String[] arr2 = new String[]{"a1","a3","a2"};
 
		for(int i = 0 ; i < arr2.length;i++){
			System.out.println("arr2["+i+"] " + arr2[i]);
		}
 
		System.out.println("--------------------------");
		Arrays.sort(arr2);// sort the array,you must import java.util.*
		for(int i = 0 ; i < arr2.length;i++){
			System.out.println("arr2["+i+"] " + arr2[i]);
		}
 
		//two-dimensional array
		System.out.println("--------------------------");
		String[][] tarr = new String[2][2];		
		tarr[0][0] = "x1";
		tarr[0][1] = "x2";
		tarr[1][0] = "x3";
		tarr[1][1] = "x4";
		for(int i = 0 ; i < tarr.length;i++){
			for (int j = 0 ; j < tarr[i].length ; j ++ ){
				System.out.println(tarr[i][j]);
			}
		}
	}
}

编译

javac JavaArray.java

执行

java JavaArray

输出

arr[0] a
arr[1] b
arr[2] c
--------------------------
arr2[0] a1
arr2[1] a3
arr2[2] a2
--------------------------
arr2[0] a1
arr2[1] a2
arr2[2] a3
--------------------------
x1
x2
x3
x4


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-array/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.
2020.03.24 评论已经全局关闭,有事加QQ聊天