Working with Arrays in Java - ProgrammerTech
Language:

Search

Working with Arrays in Java

  • Share this:
Working with Arrays in Java

Arrays in Java

Array in Java is a method for storing data of one type temporarily, called an Array in English. It is also known as a technique or tool for storing data of one type temporarily, which is divided into several cells, and each cell has an index address, so it is easy for us to process, arrange, sort, and search data using arrays.

During our programming work, we sometimes have some data and we want to store it and we want to store it in order to control it. In this case, we use arrays while working in the program so that we can process the data. It is inside the array and the data is stored in it of only one type, that is, either int, str, char...etc. We cannot store data of different types in one array, i.e. str and int, unless it is a type. The array String means if the data is of type string we do. By defining it has an array string and if it is an int we know it has an array int.

 

Benefits of using arrays in programming

  1. Store the data while we are working in the program so that we can process it.
  2. Sort and arrange the data.
  3. Search the data.
  4. Compare the data.
  5. Searching for a specific element, such as the largest or smallest element in the array, or finding the negative elements.

 

 

One-Dimensional Arrays 1D in Java

We can imagine the matrix as a rectangle divided into several cells, and the most important thing to know is that each cell has a different address to know and distinguish it. Like index in other languages, the first cell with its address is 0.

type[] ArrayName=new Type[size];

The type of the array is it numeric, text, char or any other data type.

And ArrayName is the name of the array.

and the new object to free up memory space for the array the same size as the array.

And size means the size of the array, that is, how many cells we want, for example, five or six cells.

int a=new int[5];

example 1

package javaapplication22;
public class JavaApplication22 {
    public static void main(String[] args) {
        int [] cs = new int [4];
        cs[0]=23;
        cs[1]=26;
        cs[2]=24;
        cs[3]=80;
        System.out.println(a[1]);
        System.out.println(a[3]);
    }
}

When the program is executed, it will print for us 23 and 80 because we have specified the cell whose data we want to display.

example 2

Write a program that defines a one-dimensional array of text type with a size of 5 cells, and then show it. A message to the user asking him to enter five names, then he will. Arrange these names in alphabetical order and print them in order.

package javaapplication22;
import java.utl.Scanner;
public class JavaApplication22 {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int i;
        String [] st=new String[5];
        System.out.println("Enter 5 Names");
        for(i=0;i<st.length;i++)
            st[i]=s.nextLine();
        Arrays.sort(st);
        for(i=0;i<st.length;i++)
            System.out.println(st[i]);
    }
}

We embed the input package via the java.utl.scanner command and go into the main program.

We define an object s from the input package class, and create an int scalar variable i in order to use it to start the loop.

Then we define a String text as required in the example text and its size is 5 cells.

We entered an iterative for loop in order to receive values ​​through it, and nextLine is the class responsible for entering the text value.

Then at the end we sort the array by sort and print it.

example 3

Write a program that displays a message prompting the user to enter the element he wants to search for in the array. Then search the array by the element the user entered. If the item is present, print a message stating that the item has been found. With printing the location of the element in the array, and if the element does not exist, printing a message stating that the element does not exist.

package javaapplication22;
import java.utl.Scanner;
public class JavaApplication22 {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int []a={1,5,69,-5,7};
        boolean f=false;
        int se=s.nextInt();
        for(int i=0;i<a.length;i++)
            if(se==a[i])
            {
                f=true;
                System.out.println("is found " + i);
                break;
            }
        if(f==false)
            System.out.println("Not Found");
    }
}

Inside the main program we have defined an object derived from the input package's class, which is s. And we created an array of type int and assigned the values ​​to it directly, and there is no need to specify the size of the array. After that we created a variable se that receives the input from the user and it is only numeric input. And we enter this number that the user entered in a for loop and we set conditions if the element is found, it prints that it has been found. And if he did not find it, he prints that he did not find it.

 

Array 2D in Java

It is a set of intersecting rows and columns formed by their intersection with so-called cells. And be as the following figure shows the shape of the matrix, rows and columns.

Array 2D java

The rows come horizontally and the columns come vertically, where the rows are denoted by the letter M and the number of columns is denoted by N. One of the most important things that we must know in the two-dimensional matrix is ​​that each matrix has an address and each address consists of two segments. The first syllable we call it “i” and the second syllable we call it “j.” This designation is not fixed or obligatory, but rather common. Where the cell in the previous table is 0,0, we note that it is composed of two segments, the first "i" and the second "j" and so on. Through the previous table, that the row is 0.0, 0.1, 0.2, and 0.3, we notice from this that the “i” part is constant and is 0, and the “j” part is the one that increases.

And if we look at it vertically, we notice that "i" is increasing and "j" is constant. We also notice that the matrix has two diagonals, the main diagonal in orange. We look at it from left to right. And the secondary diagonal in yellow we look at it from right to left and this table was a simple example of how to deal with an array and the addresses of cells in a two-dimensional array. And if we look at the major diameter, we find that "i" is equal to "j" and if we go to the minor diameter, we find that the relationship. between "i" and "j" that when we put them together the result will be. It is equal to the size of the matrix minus 1 where if we add for example 0 + 3 equals 3 and so on for all the elements inside the cell.

The general form of defining a two-dimensional array in Java

type[][]Array_name=new Type[m][n]

Since type is the type of the array and we open two squares [][] then the name of the array is optional, then it is equal to new. Clone or create an array in memory with the word new and then write the type of the array and give it the sizes M and N.

example 4

package javaapplication22;
public class JavaApplication22 {
    public static void main(String[] args) {
        int [][]a=new int[4][4];
        a[0][2]=19;
        a[1][3]=25;
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a.length;j++)
                System.out.print(a[i][j]);
            System.out.println();
        }
    }
}

At first we told him to store the value 19 in cell 0 and 2 and the value 25 in cell 1 and 3, then we put it in a for loop of i. And a second lobe for j and we used print at the beginning in order to print on the same row and we don't want to go down. For another line because it is a two-dimensional array and we want to print it as a square, not a one-dimensional array.

example 5

Create a two-dimensional array that receives values ​​from the user's keyboard, stores them inside the array, and prints them in an orderly 4*4 size.

package javaapplication22;
import java.utl.Scanner;
public class JavaApplication22 {
    public static void main(String[] args) {
        Scanner n=new Scanner(System.in);
        int [][]a=new int[4][4];
        int i,j;
        for(i=0;i<a.length;i++)
        {
            for(j=0;j<a.length;j++)
                a[i][j]=n.nextInt();
        }
        for(i=0;i<a.length;i++)
        {
            for(j=0;j<a.length;j++)
                System.out.print(a[i][j]);
            System.out.println();
        }
    }
}

At first we included the java.util.scanner input package and went into the main program and defined a derived object. From the Input Packet class, we define a 4-by-4 matrix and get in. In two lubes in the input pane and two loops in the print array elements pane.

How to print main diameter elements in array Array2D?

If we are asked to print only the main diameter elements, what mechanism will we use to deal with the two-dimensional array so that we can print the main diameter elements? We just mentioned at the beginning of the lesson that the main diameter elements that were misleading are orange. And we said that the relationship to the main diameter is "i" is equal to "j" if we want to print its elements. Here we have deduced a condition and we only write one condition when printing the elements of the array. Which is when "i" equals "j" print these elements so that we can only print the main diameter.

example 6

Only print main diameter elements from a 4*4 2-dimensional array.

package javaapplication22;
import java.utl.Scanner;
public class JavaApplication22 {
    public static void main(String[] args) {
        Scanner n=new Scanner(System.in);
        int [][]a=new int[4][4];
        int i,j;

        for(i=0;i<a.length;i++)
        {
            for(j=0;j<a.length;j++)
                a[i][j]=n.nextInt();
        }

        for(i=0;i<a.length;i++)
        {
            for(j=0;j<a.length;j++)
                System.out.print(a[i][j]+ " ");
            System.out.println();
        }
       
        for(i=0;i<a.length;i++)
        {
            for(j=0;j<a.length;j++)
                if(i==j)
                System.out.print(a[i][j])+ " ";
            System.out.println();
        }

    }
}

With the same explanation of the previous example 2, we only added another loop to it, which is to print only the main diameter elements, and the condition was that if "i" equals "j", execute the commands.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com