An array is a static data structure storing data of the same type. There are three types of arrays, but a three-dimensional array is used for machine learning or deep learning, so in this post, we will cover one-dimensional array and two-dimensional array. 

 

One-dimensional array

One dimensional array is used primarily when no value is defined to be stored in the array. 

 

To make a new array : format 

Datatype [] = new Datatype[Size of Array]. Here, the size of the array[] means how many rooms this array has. 

int[] score = new int[3];

There are two formats of one-dimensional array. 

First format

		int[] score = new int[3]; 
		
		System.out.println(score[0]); 
		System.out.println(score[1]);
		System.out.println(score[2]);
		
		// To assign a new value
		score[0] = 80;
		score[1] = 90;
		score[2] = 100;
		
		System.out.println(score[0]); 
		System.out.println(score[1]);
		System.out.println(score[2]);
        //Initial value : 0
		
		//double
		double[] d = new double[3];
		System.out.println(d[0]);
		System.out.println(d[1]);
		System.out.println(d[2]); 
        // Initial value : 0.0
		
		//char
		char[] c = new char[3];
		System.out.println(c[0]);
		System.out.println(c[1]);
		System.out.println(c[2]);
        // There is no initial value
		
		//boolean형
		boolean[] b = new boolean[3]; 
		System.out.println(b[0]);
		System.out.println(b[1]);
		System.out.println(b[2]);
		// Initial value : false

		//Reference type : String
		String[] str = new String[3];
		System.out.println(str[0]);
		System.out.println(str[1]);
		System.out.println(str[2]);
		// Initial value : null
		
		str[0] = "Jave";
		str[1] = "Oracle";
		str[2] = "Spring";
		
		System.out.println(str[0]);
		System.out.println(str[1]);
		System.out.println(str[2]);

Second format

This format is used when the declaration of the array and the value's initialization happen simultaneously. When there are certain values that you want to assign first, you can use this. 

The most important thing to remember when it comes to arrays is that you can't put different datatypes in the same array.

		int[] s1 = {80, 90, 100}; 
		int[] s2 = new int[] {80, 90, 100};
		System.out.println(s1[0]);
		System.out.println(s2[2]);
		System.out.println(s1[2]); 

		
		//double
		double[] dd = {3.14, 10.5, 42.195, 50}; // 50 will be changed to 50.0
		for(int i=0; i<dd.length; i++)
		System.out.print(dd[i]+"\t");
		System.out.println();
		
		//char
		char[] cc = {'j','v','P','h'};
		for(int i=0; i<cc.length; i++)
			System.out.print(cc[i]+"\t");
		System.out.println();
		
		//boolean
		boolean[] bb = {true, false, true};
		for(int i=0; i<bb.length; i++)
			System.out.print(bb[i]+"\t");
		System.out.println();
		
		//String 
		String[] str1 = {"Java", "is", "sometimes", "annoying", "but"};
		String[] str2 = new String[]{"it", "is", "mostly", "fun", "!!!"};

		//to print out
		for(int i=0; i>str1.length; i++) 
			System.out.println(str1[i]+"\t"); 
		
		}
	}

To know the size of the array

The array size can be easily explained as the number of rooms in the house(array).


		System.out.println("Size:"+ s1.length); //3
		for(int i=0; i<s1.length; i++) 
			System.out.print(s1[i]+"\t");
		System.out.println();

 

Here, we used the length property, not the length method. You will see the brackets"()" with the method to distinguish.

Please refer to my last post to understand better of the difference of the two constructs.

2022.09.02 - [Java] - Java) .length vs length()

 

Java) .length vs length()

In Java, two different length constructs have different roles. ".length", the length property is used with the String and Array class. It returns the number of characters in a text String or the siz..

www.agilemeadow.com

Example : Average

As you can see, array is a very efficient way to write a simple and clean code.

import java.util.Scanner;

public class ArrayEx03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] s = new int[5];
		
		System.out.println("Enter your scores of the 5 subjects.");
		Scanner sc = new Scanner(System.in);
				
		int sum = 0;
		for(int i=0; i<s.length; i++) {
			s[i] = sc.nextInt();
			sum += s[i]; 	
		}
		double avg = sum / 5.0;
		System.out.println("Sum:"+ sum);
		System.out.println("Avg:"+ avg);
	}

}

Example : Max and Min number

public class ArrayEx04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		double[] data = {9.5, 7.0, 13.6, 7.5, 10.5};
		
		double max, min;
		
		max = data[0];  
		min = data[0];
		
		for(int i=1; i<data.length; i++) {
			if(data[i] > max) max = data[i];
			if(data[i] < min) min = data[i];
		}
		 
		System.out.println("max:"+max);
		System.out.println("min:"+min);
	

}
}

 

Two-dimensional array

Two-dimensional array sounds more difficult, but the basic is same as one dimensional array. 

Let's check out the codes first.

So, let's say there are three five students who took exams of three subjects and we are arranging the scores in the two-dimensional array. 

public class ArrEx {

  public static void main(String[] args) {
    int  [][]score=new int [5][3]; // datatype [row] [col]

    score[0][0]=10;  score[0][1]=90;  score[0][2]=70;
    score[1][0]=60;  score[1][1]=80;  score[1][2]=65;
    score[2][0]=55;  score[2][1]=60;  score[2][2]=85;
    score[3][0]=90;  score[3][1]=75;  score[3][2]=95;
    score[4][0]=60;  score[4][1]=30;  score[4][2]=80;

    //For loop
    for(row = 0; row < 5 ; row++){ 
      for(col = 0; col < 3 ; col++){  
         System.out.print(" " +score[row][col]);
	  }
      System.out.println("");
    }
  }
}

Compare to not using array, it will be still clean but this code looks a bit too much work. 

Let us elaborate this little bit better.

public class ArrEx01 {

  public static void main(String[] args) {
   
    int [][]score = { { 85,  60,  70},   //row no.0
				      { 90,  95,  80},   //1
				      { 75,  80, 100},   //2 
                      { 80,  70,  95},   //3 
				      {100,  65,  80}    //4 
					};
    int [] subject = new int[3]; 
    int [] student = new int[5]; 
    int  r, c;  
	    
    System.out.println("Sum by each subjects. ");
    for(c = 0; c < 3 ; c++){ // subjects      
      for(r = 0; r < 5 ; r++){ // students   
        subject[c] += score[r][c];   
      }
      System.out.println(subject[c]);  
    }

    System.out.println("Sum by each studetns");
    for(r = 0; r < 5 ; r++){    // studnets    
      for(c = 0; c < 3 ; c++){  // sujects
        student[r] += score[r][c];  
      }
      System.out.println(student[r]);
    }

  }//main() end
}// class end

Type Conversion in array

In Java, type conversion is a very important thing to remember because it happends a lot everytime. We will talk about this in the other posts, but now, just take a peek of how they look like. 

public class ArrayEx07 {
	
	//Absolute value
	static int abs(int data) {
		if(data < 0)
			data = -data; 
		return data;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// args[0] = " -10", args[1] = "-20" => char
		System.out.println("args[0]:"+args[0]);
		System.out.println("args[1]:"+args[1]);
		
		//args[0] = "-10" ---> -10 : Type conversion
		int num = Integer.parseInt(args[0]);
		///Integer.parseInt (char -> num) 
		System.out.println("Absolute Value:"+abs(num));

		int num1 = Integer.parseInt(args[1]);
		///Integer.parseInt (char -> num)
		System.out.println("Absolute Value:"+abs(num1));
		
		}
	}

Array Copy

You can also copy the array that you already have, by using for loop.

public class ArrayEx08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] oldArray = {10, 20, 30}; //Original array
		int[] newArray = new int[5]; //New array
		
		for(int i=0; i<oldArray.length; i++) {
			newArray[i] = oldArray[i]; //for loop
		}

		for(int i : newArray) { 
			System.out.println(i+"\t");
		}// Initial value : 0.0
		
		
	}

}

 

'Java' 카테고리의 다른 글

Deleting attached files  (0) 2022.09.14
Java) .length vs length()  (0) 2022.09.02
Java) Conditional statements and loops  (0) 2022.08.30
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26

+ Recent posts