JavaJava · Chapterبەش 9 · Lectureوانە 9.1

Arrays in One and Two Dimensionsڕیزەکەکان لە یەک و دوو ڕەهەنددا

Java arrays: many values of one type under one name, with a fixed length. Create them with { } or new (and their default values), read and change elements by index from 0, loop with for and for-each, the ArrayIndexOutOfBoundsException and NullPointerException, printing with Arrays.toString, two names for one array and real copies, == versus Arrays.equals, sort and fill, arrays in methods (removing an element into a new, shorter array, and five more practice methods) and String[] args, and two-dimensional arrays with nested loops.

Java: چەندین یەک جۆر لە ژێر یەک ناودا، بە درێژییەکی جێگیر. دروستکردنیان بە ⁦{ }⁩ یان new (و )، خوێندنەوە و گۆڕینی بە لە 0ـەوە، سووڕانەوە بە for و ، ArrayIndexOutOfBoundsException و NullPointerException، چاپکردن بە ⁦Arrays.toString⁩، دوو ناو بۆ یەک و کۆپیی ڕاستەقینە، == بەرامبەر ⁦Arrays.equals⁩، sort و fill، لە (لابردنی بۆ نوێی کورتتر لەگەڵ پێنج تری ڕاهێنان) و ⁦String[] args⁩ و بە .

25 min read21 خولەک خوێندنەوە · 24 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Create arrays with { } and with new, and know their default values.
  • Read, change and loop over elements by index, and avoid the index and null errors.
  • Explain why an array variable holds a reference, and copy and compare arrays correctly.
  • Use Arrays.toString, sort, fill, equals and copyOf, and pass arrays to and from methods.
  • Write methods that build new arrays: remove an element, merge, rotate, add two arrays and drop duplicates.
  • Store a table in a two-dimensional array and process it with nested loops.
  • بە ⁦{ }⁩ و بە new دروست بکەیت و بزانیت.
  • بە بخوێنیتەوە، بگۆڕیت و بەسەریاندا بسووڕێیتەوە و خۆت لە هەڵەکانی و null بپارێزیت.
  • ڕوون بکەیتەوە بۆچی هەڵدەگرێت و بە دروستی کۆپی و بەراورد بکەیت.
  • ⁦Arrays.toString⁩، sort، fill، equals و copyOf بەکار بهێنیت و بنێریت بۆ و لێیانەوە وەربگریت.
  • بنووسیت کە نوێ دروست دەکەن: لابردنی ، یەکخستن، سووڕاندن، کۆکردنەوەی دوو و لابردنی دووپاتەکان.
  • خشتەیەک لە هەڵبگریت و بە کاری لەسەر بکەیت.

Many values, one nameچەندین نرخ، یەک ناو

Five students sat a Java test. With what you know so far, five marks need five variables, and every calculation must name each one:

پێنج قوتابی تاقیکردنەوەیەکی Javaـیان کرد. بەوەی تا ئێستا دەیزانیت، پێنج نمرە پێنج پێویستن و هەموو ژمێرکارییەک دەبێت ناوی یەک بە یەکیان بهێنێت:

FiveMarks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class FiveMarks {
    public static void main(String[] args) {
        int mark1 = 90, mark2 = 75, mark3 = 88, mark4 = 62, mark5 = 95;
        int total = mark1 + mark2 + mark3 + mark4 + mark5;
        System.out.println("Total: " + total);
    }
}

For a class of 40 that is hopeless. An keeps many values of one type under one name, in numbered places. Each value is an , and its place number is its :

بۆ پۆلێکی ⁦40⁩ کەسی ئەمە ناکرێت. چەندین یەک جۆر لە ژێر یەک ناودا هەڵدەگرێت، لە شوێنی ژمارەداردا. هەر و ژمارەی شوێنەکەی :

The line int[] marks = {90, 75, 88, 62, 95}; above five boxes in a row holding 90, 75, 88, 62 and 95. The name marks points at the row. Under the boxes are the indexes 0, 1, 2, 3 and 4. The box with index 2 is highlighted as one element: marks[2] is 88. A bracket under the row says length 5: marks.length is 5. Note: five marks in one variable, marks[0] to marks[4]; the length never changes.دێڕی int[] marks = {90, 75, 88, 62, 95}; لە سەرووی پێنج سندووقی ڕیزکراوەوە کە 90، 75، 88، 62 و 95یان تێدایە. ناوی marks ئاماژە بە ڕیزەکە دەکات. لە ژێر سندووقەکاندا ئیندێکسەکان 0، 1، 2، 3 و 4 هەن. سندووقی ئیندێکسی 2 وەک یەک دانە نیشان کراوە: marks[2] دەکاتە 88. کەوانەیەک لە ژێر ڕیزەکەدا دەڵێت درێژی 5: marks.length دەکاتە 5. تێبینی: پێنج نمرە لە یەک گۆڕاودا، marks[0] تا marks[4]؛ درێژییەکە هەرگیز ناگۆڕێت.
One name, five numbered places: marks[0] to marks[4]یەک ناو، پێنج شوێنی ژمارەدار: ⁦marks[0]⁩ تا ⁦marks[4]⁩CêIT

Creating an array and reading an elementدروستکردنی ڕیزەکێک و خوێندنەوەی دانەیەک

int[] marks declares a variable whose type is array of int (the brackets belong to the type). Values in braces, {90, 75, 88, 62, 95}, create the array and fill it. marks[2] reads the element at index 2:

int[] marks دەناسێنێت کە جۆرەکەی intـە (کەوانە چوارگۆشەکان بەشێکن لە جۆرەکە). لە ناو کەوانەدا، {90, 75, 88, 62, 95}، دروست دەکەن و پڕی دەکەنەوە. marks[2] 2 دەخوێنێتەوە:

Marks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Marks {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        System.out.println("First mark: " + marks[0]);
        System.out.println("Third mark: " + marks[2]);
        System.out.println("Last mark:  " + marks[4]);
        System.out.println("How many:   " + marks.length);
    }
}
Five boxes 90, 75, 88, 62 and 95. Above them their positions: 1st, 2nd, 3rd, 4th, 5th; below them their indexes 0, 1, 2, 3, 4. The third box is highlighted: marks[2] -> 88, the third mark has index 2. Note: last index = length - 1 = 4.پێنج سندووق 90، 75، 88، 62 و 95. لە سەرەوەیان شوێنەکانیان: یەکەم، دووەم، سێیەم، چوارەم، پێنجەم؛ لە خوارەوەیان ئیندێکسەکانیان 0، 1، 2، 3، 4. سندووقی سێیەم نیشان کراوە: marks[2] -> 88، نمرەی سێیەم ئیندێکسی 2ـی هەیە. تێبینی: دوایین ئیندێکس = length - 1 = 4.
The third mark has index 2; the last index is length - 1نمرەی سێیەم 2ـی هەیە؛ دوایین length - 1ـەCêIT

Java counts from 0, like Python and C (Indexes in notation); MATLAB counts from 1 (Reaching one element). int marks[] also compiles, a leftover from C, but Java programmers write int[] marks.

Java لە 0ـەوە دەژمێرێت، وەک Python و C (ئیندێکسەکان لە نیشانەکاندا)؛ MATLAB لە 1ـەوە دەژمێرێت (گەیشتن بە یەک دانە). int marks[]ـیش کۆمپایل دەبێت، پاشماوەیەکی Cـیە، بەڵام بەرنامەسازانی Java دەنووسن int[] marks.

Changing an element; the lengthگۆڕینی دانەیەک؛ درێژی

An element is used like a variable: assign to it with =, or read it in a calculation. cities.length gives the number of elements, so the last index is cities.length - 1:

وەک بەکار دێت: بە = تێ بخە، یان لە ژمێرکارییەکدا بیخوێنەوە. cities.length ژمارەی دەدات، بۆیە دوایین cities.length - 1ـە:

ChangeMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ChangeMark {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        marks[1] = 80;                    // Shilan's paper was marked again
        marks[3] = marks[3] + 5;          // a bonus of 5 for the fourth student
        System.out.println(marks[1] + " " + marks[3]);
        String[] cities = {"Hawler", "Duhok", "Halabja"};
        cities[2] = "Zakho";
        System.out.println(cities[0] + ", " + cities[1] + ", " + cities[2]);
        System.out.println(cities.length + " cities, last index " + (cities.length - 1));
    }
}

length is a field of the array, written without brackets. A String uses the method length() with brackets (length). Mixing them up gives cannot find symbol:

length خانەیەکی و بەبێ کەوانە دەنووسرێت. String length() بە کەوانەوە بەکار دەهێنێت (length). تێکەڵکردنیان دەدات cannot find symbol:

Outputدەرئەنجام
$ javac LengthCall.java
LengthCall.java:5: error: cannot find symbol
        System.out.println(marks.length());
                                ^
  symbol:   method length()
  location: variable marks of type int[]
LengthCall.java:6: error: cannot find symbol
        System.out.println(name.length);
                               ^
  symbol:   variable length
  location: variable name of type String
2 errors

Visiting every element with forسەردانی هەموو دانەیەک بە for

A counting for loop (The for loop) visits the indexes 0, 1, 2 … one after another. With i < marks.length as the condition it works for an array of any length:

ژماردن (خولی for) 0، 1، 2 … یەک لە دوای یەک سەردان دەکات. بە i < marks.length وەک بۆ بە هەر درێژییەک کار دەکات:

SumMarks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SumMarks {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        int sum = 0;
        for (int i = 0; i < marks.length; i++) {
            sum += marks[i];
            System.out.println("i = " + i + "  mark = " + marks[i] + "  sum = " + sum);
        }
        double average = (double) sum / marks.length;
        System.out.println("Average: " + average);
    }
}
An animation. The code int sum = 0; for (int i = 0; i < marks.length; i++) { sum += marks[i]; } next to the array 90, 75, 88, 62, 95. A pointer i moves from box 0 to box 4; the visited boxes turn blue, and the variable sum grows 90, 165, 253, 315, 410. In the last frame i is 5, the test 5 < 5 is false and the loop ends: average = 410 / 5 = 82.0.
An animation. The code int sum = 0; for (int i = 0; i < marks.length; i++) { sum += marks[i]; } next to the array 90, 75, 88, 62, 95. A pointer i moves from box 0 to box 4; the visited boxes turn blue, and the variable sum grows 90, 165, 253, 315, 410. In the last frame i is 5, the test 5 < 5 is false and the loop ends: average = 410 / 5 = 82.0.
i walks from 0 to length - 1 while sum collects the marksi لە 0ـەوە تا length - 1 دەڕوات و sum نمرەکان کۆ دەکاتەوەCêIT

The cast (double) sum makes the division exact (Where the cast goes). Use <, not <=: with <= the loop also asks for index 5 and the program stops (Off by one).

کاستی (double) sum دابەشکردنەکە ورد دەکات (کاست لە کوێ دادەنرێت). < بەکار بهێنە، نەک <=: بە <= داوای 5ـیش دەکات و دەوەستێت (یەکێک زیاتر یان کەمتر).

The for-each loopخولی foreach

When you need every element but not its index, the is shorter (A first look). Read for (int mark : marks) as "for each int mark in marks":

کاتێک پێویستت بە هەموو هەیە بەڵام نەک بە ، کورترە (یەکەم سەیرکردن). for (int mark : marks) وا بخوێنەوە: «بۆ هەر int markـێک لە ناو marks»:

ForEachMarks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ForEachMarks {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        int sum = 0;
        for (int mark : marks) {
            sum += mark;
        }
        System.out.println("Sum: " + sum);
        String[] names = {"Aram", "Shilan", "Karwan"};
        for (String name : names) {
            System.out.println("Hello, " + name);
        }
    }
}
Two panels. Left: for (int mark : marks) { mark = mark + 5; } with the array 90, 75, 88 and a separate box mark; a dashed arrow copies 90 into mark, which becomes 95, but the array stays 90, 75, 88. Right: for (int i = 0; i < marks.length; i++) { marks[i] = marks[i] + 5; } and the array becomes 95, 80, 93. Note: read with for-each; to change the elements, use the index.دوو بەش. چەپ: for (int mark : marks) { mark = mark + 5; } لەگەڵ ڕیزەکی 90، 75، 88 و سندووقێکی جیای mark؛ تیرێکی پچڕپچڕ 90 کۆپی دەکات بۆ mark، کە دەبێتە 95، بەڵام ڕیزەکەکە هەر 90، 75، 88 دەمێنێتەوە. ڕاست: for (int i = 0; i < marks.length; i++) { marks[i] = marks[i] + 5; } و ڕیزەکەکە دەبێتە 95، 80، 93. تێبینی: بە خولی foreach بخوێنەرەوە؛ بۆ گۆڕینی دانەکان، ئیندێکس بەکار بهێنە.
The for-each variable is a copy: changing it leaves the array alone کۆپییە: گۆڕینی ئەو، ناگۆڕێتCêIT

The loop variable gets a copy of each element, so changing it changes nothing in the array. This program shows both loops:

کۆپییەکی هەر وەردەگرێت، بۆیە گۆڕینی هیچ شتێک لە ناگۆڕێت. ئەم هەردوو نیشان دەدات:

ForEachCopy.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class ForEachCopy {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88};
        for (int mark : marks) {
            mark = mark + 5;              // changes only the copy in mark
        }
        System.out.println(Arrays.toString(marks));
        for (int i = 0; i < marks.length; i++) {
            marks[i] = marks[i] + 5;      // changes the array itself
        }
        System.out.println(Arrays.toString(marks));
    }
}

new: an array of a given lengthnew: ڕیزەکێک بە درێژییەکی دیاریکراو

When the values come later (from the keyboard, a file, a calculation), create the array with new and a length: int[] counts = new int[5];. Java fills every place with a at once:

کاتێک دواتر دێن (لە ، ، ژمێرکارییەک)، بە new و درێژییەک دروست بکە: int[] counts = new int[5];. Java یەکسەر هەموو شوێنێک بە پڕ دەکاتەوە:

Defaults.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class Defaults {
    public static void main(String[] args) {
        int[] counts = new int[5];
        double[] prices = new double[3];
        boolean[] answers = new boolean[3];
        String[] names = new String[3];
        System.out.println(Arrays.toString(counts));
        System.out.println(Arrays.toString(prices));
        System.out.println(Arrays.toString(answers));
        System.out.println(Arrays.toString(names));
        char[] letters = new char[2];
        System.out.println((int) letters[0]);
    }
}
Four rows. new int[5] gives 0, 0, 0, 0, 0; new double[3] gives 0.0, 0.0, 0.0; new boolean[3] gives false, false, false; new String[3] gives null, null, null, drawn as grey empty slots: an empty slot, no String yet. Note: numbers 0, boolean false, char \u0000, objects such as String null.چوار ڕیز. new int[5] دەدات 0، 0، 0، 0، 0؛ new double[3] دەدات 0.0، 0.0، 0.0؛ new boolean[3] دەدات false، false، false؛ new String[3] دەدات null، null، null، وەک شوێنی چۆڵی خۆڵەمێشی کێشراون: شوێنی چۆڵ، هێشتا هیچ Stringـێک نییە. تێبینی: ژمارە 0، boolean false، char \u0000، ئۆبجێکتەکان وەک String null.
Every new array starts full of default valuesهەموو نوێ پڕ لە دەست پێ دەکاتCêIT

A char starts as '\u0000', the character with code 0, which prints as nothing, so the program prints its number. The length is fixed when the array is made: it can be a variable (new int[n]), but it never changes afterwards. A new object starts with the same default values (Default values of an object).

char بە '\u0000' دەست پێ دەکات، ئەو کۆدەکەی 0ـە و هیچ چاپ ناکات، بۆیە ژمارەکەی چاپ دەکات. درێژی لە کاتی دروستکردنی جێگیر دەبێت: دەتوانێت بێت (new int[n])، بەڵام دواتر هەرگیز ناگۆڕێت. نوێش بە هەمان دەست پێ دەکات (نرخە بنەڕەتییەکانی ئۆبجێکتێک).

new: an array of a given lengthnew: ڕیزەکێک بە درێژییەکی دیاریکراو

An empty slot: nullشوێنی چۆڵ: null

In a String[] the default is null: an empty slot with no String in it yet. Printing it shows null, but calling a method on it stops the program with a NullPointerException:

لە String[]ـدا nullـە: شوێنی چۆڵ، هێشتا هیچ Stringـێکی تێدا نییە. چاپکردنی null نیشان دەدات، بەڵام بانگکردنی لەسەری بە NullPointerException دەوەستێنێت:

Names.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Names {
    public static void main(String[] args) {
        String[] names = new String[3];
        names[0] = "Aram";
        names[1] = "Shilan";
        for (int i = 0; i < names.length; i++) {
            System.out.println(i + ": " + names[i]);
        }
        System.out.println(names[2].length());
    }
}

Since Java 15 (JEP 358) the message names the empty place. <local1> means local variable number 1 (here names), because plain javac does not store variable names in the class file. Compiled with javac -g, the same run says because "names[2]" is null. Fill every element before you use it, or check if (names[i] != null).

لە ⁦Java 15⁩ـەوە ⁦(JEP 358)⁩ پەیامەکە ناوی شوێنە چۆڵەکە دەبات. <local1> واتە ژمارە 1 (لێرەدا names)، چونکە javacـی ئاسایی ناوی لە فایلی classـدا هەڵناگرێت. ئەگەر بە javac -g کۆمپایل بکرێت، هەمان جێبەجێکردن دەڵێت because "names[2]" is null. هەموو پێش بەکارهێنانی پڕ بکەرەوە، یان if (names[i] != null) بپشکنە.

Outside the array: ArrayIndexOutOfBoundsExceptionدەرەوەی ڕیزەکەکە: ArrayIndexOutOfBoundsException

Every index is checked while the program runs. An index below 0 or at length or above stops the program with an that names the index and the length (Reading a stack trace):

هەموو لە کاتی کارکردنی دەپشکنرێت. لە خوار 0 یان لە length و سەرووتر بە دەوەستێنێت کە ناوی و درێژییەکە دەبات (خوێندنەوەی stack trace):

Bounds.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Bounds {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        System.out.println(marks[4]);
        System.out.println(marks[5]);
    }
}
Five boxes with the indexes 0 to 4, and two dashed boxes outside them, index -1 on the left and index 5 on the right, each crossed out. A stop sign with marks[-1]: Index -1 out of bounds for length 5, and marks[5]: Index 5 out of bounds for length 5. Note: ArrayIndexOutOfBoundsException: Java checks every index while the program runs.پێنج سندووق بە ئیندێکسەکانی 0 تا 4 و دوو سندووقی پچڕپچڕ لە دەرەوەیان، ئیندێکسی -1 لە چەپ و ئیندێکسی 5 لە ڕاست، هەریەکەیان خەتی لێ دراوە. نیشانەیەکی وەستان لەگەڵ marks[-1]: Index -1 out of bounds for length 5 و marks[5]: Index 5 out of bounds for length 5. تێبینی: ArrayIndexOutOfBoundsException: Java لە کاتی کارکردندا هەموو ئیندێکسێک دەپشکنێت.
Index −1-1 and index 5 are outside an array of length 5 −1-1 و 5 لە دەرەوەی درێژی 5نCêIT

Java has no negative indexes: marks[-1] is not the last element, as in Python, but the same exception. The most common cause is <= in a loop header; this loop prints all three marks, then asks for index 3:

Java نییە: marks[-1] وەک Python دوایین نییە، بەڵکو هەمان . باوترین هۆکار <=ـە لە سەرەی ؛ ئەم هەر سێ نمرەکە چاپ دەکات، پاشان داوای 3 دەکات:

OffByOne.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class OffByOne {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88};
        for (int i = 0; i <= marks.length; i++) {
            System.out.println(marks[i]);
        }
    }
}

Printing an array: Arrays.toStringچاپکردنی ڕیزەکێک: ⁦Arrays.toString⁩

System.out.println(marks) does not print the marks. It prints the type and a code for the object: [I means array of int, [Ljava.lang.String; array of String, and the part after @ is a number in hexadecimal. Arrays.toString from java.util prints the elements:

System.out.println(marks) نمرەکان چاپ ناکات. جۆرەکە و کۆدێک بۆ چاپ دەکات: [I واتە int، [Ljava.lang.String; String و بەشی دوای @ ژمارەیەکە بە . Arrays.toString لە java.utilـەوە چاپ دەکات:

PrintArray.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class PrintArray {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        String[] names = {"Aram", "Shilan"};
        System.out.println(marks);
        System.out.println(names);
        System.out.println(Arrays.toString(marks));
        System.out.println(Arrays.toString(names));
    }
}
Two panels. Left, System.out.println(marks); prints [I@7344699f, split into [ meaning an array, I meaning of int, and @… an identity code in hexadecimal, not the values; the part after @ can differ on your computer. Right, Arrays.toString(marks) prints [90, 75, 88, 62, 95], the elements in order; import java.util.Arrays; Arrays is in java.util.دوو بەش. چەپ، System.out.println(marks); [I@7344699f چاپ دەکات، کە دابەش کراوە: [ واتە ڕیزەک، I واتە هی int و @… کۆدی ناسینەوە بە شانزەیی، نەک نرخەکان؛ بەشی دوای @ لەسەر کۆمپیوتەرەکەت جیاواز دەبێت. ڕاست، Arrays.toString(marks) [90, 75, 88, 62, 95] چاپ دەکات، دانەکان بە ڕیز؛ import java.util.Arrays;، Arrays لە java.utilـدایە.
println shows a code for the array; Arrays.toString shows its elementsprintln کۆدێک بۆ نیشان دەدات؛ ⁦Arrays.toString⁩ CêIT

Two names, one arrayدوو ناو، یەک ڕیزەک

An array is an object, and an array variable holds a to it, not the elements themselves (arrays are ). So int[] b = a; copies the reference: a and b are two names for one array, and a change through b is seen through a:

و بۆی هەڵدەگرێت، نەک خودی ( ). بۆیە int[] b = a; کۆپی دەکات: a و b دوو ناون بۆ یەک و گۆڕانکاری لە ڕێگەی bـەوە لە aـشەوە دەبینرێت:

SharedArray.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class SharedArray {
    public static void main(String[] args) {
        int[] a = {10, 20, 30};
        int[] b = a;                      // b is a second name for the same array
        b[0] = 99;
        System.out.println("a: " + Arrays.toString(a));
        System.out.println("b: " + Arrays.toString(b));
        System.out.println("a == b: " + (a == b));
    }
}
An animation in five steps. 1: int[] a = {10, 20, 30}; the variable a points at an array of three ints. 2: int[] b = a; a second arrow from b points at the same array: two names, one array. 3: b[0] = 99; the first box becomes 99, so a[0] is 99 too. 4: int[] c = Arrays.copyOf(a, a.length); a new array 99, 20, 30 appears, with c pointing at it. 5: c[0] = 5; only the copy changes: c is 5, 20, 30 and a is still 99, 20, 30.
An animation in five steps. 1: int[] a = {10, 20, 30}; the variable a points at an array of three ints. 2: int[] b = a; a second arrow from b points at the same array: two names, one array. 3: b[0] = 99; the first box becomes 99, so a[0] is 99 too. 4: int[] c = Arrays.copyOf(a, a.length); a new array 99, 20, 30 appears, with c pointing at it. 5: c[0] = 5; only the copy changes: c is 5, 20, 30 and a is still 99, 20, 30.
b = a copies the reference; Arrays.copyOf copies the elements⁦b = a⁩ کۆپی دەکات؛ ⁦Arrays.copyOf⁩ CêIT

The same happens with Python lists (Two names, one list). It is not a bug: passing one big array around without copying it is fast. Just make a real copy when you need two separate arrays. Every object works this way (Two variables, one object).

هەمان شت لەگەڵ Python ڕوو دەدات (دوو ناو، یەک لیست). ئەمە نییە: گواستنەوەی گەورە بەبێ کۆپیکردن خێرایە. تەنیا کاتێک کۆپییەکی ڕاستەقینە دروست بکە کە پێویستت بە دوو جیا هەیە. هەموو بەم شێوەیە کار دەکات (دوو گۆڕاو، یەک ئۆبجێکت).

Two names, one arrayدوو ناو، یەک ڕیزەک

A real copy: Arrays.copyOfکۆپییەکی ڕاستەقینە: ⁦Arrays.copyOf⁩

Arrays.copyOf(a, length) makes a new array with the elements of a. With a bigger length the new places get default values; with a smaller one the copy is cut. (a.clone() or a loop also copy.)

Arrays.copyOf(a, length) نوێ بە a دروست دەکات. بە درێژییەکی گەورەتر شوێنە نوێیەکان وەردەگرن؛ بە درێژییەکی بچووکتر کۆپییەکە دەبڕدرێت. (a.clone() یان کۆپی دەکەن.)

CopyArray.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class CopyArray {
    public static void main(String[] args) {
        int[] a = {10, 20, 30};
        int[] c = Arrays.copyOf(a, a.length);   // a new array with the same values
        c[0] = 5;
        System.out.println("a: " + Arrays.toString(a));
        System.out.println("c: " + Arrays.toString(c));
        System.out.println("a == c: " + (a == c));
        int[] longer = Arrays.copyOf(a, 5);     // two more places, filled with 0
        int[] shorter = Arrays.copyOf(a, 2);    // only the first two
        System.out.println("longer: " + Arrays.toString(longer));
        System.out.println("shorter: " + Arrays.toString(shorter));
    }
}
Three rows. a is 10, 20, 30. Arrays.copyOf(a, 5) is 10, 20, 30, 0, 0: two new places, filled with 0. Arrays.copyOf(a, 2) is 10, 20: only the first two. Note: an array cannot grow: to add a place, copy it into a longer array.سێ ڕیز. a دەکاتە 10، 20، 30. Arrays.copyOf(a, 5) دەکاتە 10، 20، 30، 0، 0: دوو شوێنی نوێ، بە 0 پڕ کراونەتەوە. Arrays.copyOf(a, 2) دەکاتە 10، 20: تەنیا دووی یەکەم. تێبینی: ڕیزەکێک گەورە نابێت: بۆ زیادکردنی شوێنێک، کۆپیی بکە بۆ ڕیزەکێکی درێژتر.
copyOf makes a new array, longer or shortercopyOf نوێ دروست دەکات، درێژتر یان کورتترCêIT

This is also the only way to "grow" an array: copy it into a longer one and keep the new one in the same variable. When this happens often, use an ArrayList, which grows by itself:

ئەمە تاکە ڕێگەشە بۆ «گەورەکردنی» : کۆپیی بکە بۆ یەکێکی درێژتر و نوێیەکە لە هەمان هەڵبگرە. کاتێک ئەمە زۆر ڕوو دەدات، ArrayList بەکار بهێنە کە خۆی گەورە دەبێت:

AddMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class AddMark {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        marks = Arrays.copyOf(marks, marks.length + 1);   // a new, longer array
        marks[marks.length - 1] = 70;                      // the new mark goes in the last place
        System.out.println(Arrays.toString(marks) + " length " + marks.length);
    }
}

Two names, one arrayدوو ناو، یەک ڕیزەک

Comparing arrays: == or Arrays.equalsبەراوردکردنی ڕیزەکەکان: == یان ⁦Arrays.equals⁩

== asks whether two variables refer to the same array. Two different arrays with equal elements are not ==. Arrays.equals compares the length and every element:

== دەپرسێت ئایا دوو ئاماژە بە هەمان دەکەن. دوو جیاواز بە یەکسان == نین. Arrays.equals درێژی و هەموو بەراورد دەکات:

CompareArrays.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class CompareArrays {
    public static void main(String[] args) {
        int[] x = {1, 2, 3};
        int[] y = {1, 2, 3};
        System.out.println("x == y:             " + (x == y));
        System.out.println("x.equals(y):        " + x.equals(y));
        System.out.println("Arrays.equals(x, y): " + Arrays.equals(x, y));
    }
}
Two variables x and y point at two different arrays, both 1, 2, 3; dashed lines with ticks join equal elements. Boxes: x == y -> false, two different arrays; Arrays.equals(x, y) -> true, same length, same elements. Note: x.equals(y) is false too: for arrays it works like ==.دوو گۆڕاوی x و y ئاماژە بە دوو ڕیزەکی جیاواز دەکەن، هەردووکیان 1، 2، 3؛ هێڵی پچڕپچڕ بە نیشانەی ڕاستەوە دانەکانی یەکسان دەبەستنەوە. سندووقەکان: x == y -> false، دوو ڕیزەکی جیاواز؛ Arrays.equals(x, y) -> true، هەمان درێژی، هەمان دانەکان. تێبینی: x.equals(y)ـیش false دەدات: بۆ ڕیزەکەکان وەک == کار دەکات.
== asks "the same array?"; Arrays.equals asks "the same elements?"== دەپرسێت «هەمان ؟»؛ ⁦Arrays.equals⁩ دەپرسێت «هەمان ؟»CêIT

It is the same trap as comparing strings with == (Comparing strings): for objects, use a method that compares the contents.

هەمان تەڵەی بەراوردکردنی بە ==ـە (بەراوردکردنی زنجیرەنووسەکان): بۆ ، بەکار بهێنە کە ناوەڕۆک بەراورد بکات.

The Arrays class: sort, fill, toStringکلاسی ⁦Arrays: sort⁩، fill، toString

The class Arrays in java.util holds ready-made static methods for arrays (The Java API). Arrays.sort puts the elements in order, Arrays.fill gives every element the same value:

Arrays لە java.utilـدا ئامادەی بۆ هەیە (APIـی Java). Arrays.sort ڕیز دەکات و Arrays.fill هەمان دەداتە هەموو :

ArraysTools.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class ArraysTools {
    public static void main(String[] args) {
        int[] marks = {90, 75, 88, 62, 95};
        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));
        String[] names = {"Shilan", "Aram", "Karwan", "Dilan"};
        Arrays.sort(names);
        System.out.println(Arrays.toString(names));
        int[] seats = new int[6];
        Arrays.fill(seats, -1);           // -1 = an empty seat
        System.out.println(Arrays.toString(seats));
    }
}
Three tools. Arrays.sort(marks) turns 90, 75, 88, 62, 95 into 62, 75, 88, 90, 95. Arrays.sort(names) turns Shilan, Aram, Karwan, Dilan into Aram, Dilan, Karwan, Shilan. Arrays.fill(seats, -1) makes six places all -1: every place gets the same value. Note: numbers go in ascending order, words in alphabetical order, capital letters first.سێ ئامراز. Arrays.sort(marks) 90، 75، 88، 62، 95 دەکات بە 62، 75، 88، 90، 95. Arrays.sort(names) Shilan، Aram، Karwan، Dilan دەکات بە Aram، Dilan، Karwan، Shilan. Arrays.fill(seats, -1) شەش شوێن هەموو دەکات بە -1: هەموو شوێنێک هەمان نرخ وەردەگرێت. تێبینی: ژمارەکان بە ڕیزی بەرزبوونەوە و وشەکان بە ڕیزی ئەلفوبێ، پیتی گەورە یەکەم.
sort orders the elements; fill sets them allsort ڕیز دەکات؛ fill هەموویان دادەنێتCêIT

sort changes the array itself and returns nothing. Words are sorted by their character codes, so capitals come first: {"shilan", "Aram", "karwan", "Dilan"} becomes [Aram, Dilan, karwan, shilan]. How sorting works inside, and sorting in other orders, comes in Sorting and searching and Sorting algorithms.

sort خودی دەگۆڕێت و هیچ ناگەڕێنێتەوە. وشەکان بەپێی کۆدی ڕیز دەکرێن، بۆیە پیتی گەورە یەکەم دێت: {"shilan", "Aram", "karwan", "Dilan"} دەبێتە [Aram, Dilan, karwan, shilan]. لە ناوەوە چۆن کار دەکات و بە ڕیزی تر لە ڕیزکردن و گەڕان و ئەلگۆریزمەکانی ڕیزکردنـدا دێن.

A program: marks from the keyboardبەرنامەیەک: نمرە لە کیبۆردەوە

Now a complete program: read five marks into an array, then use it three times: for the average, the best mark and the number of students above the average. Without the array the third loop would be impossible, because the marks would be gone (Scanner):

ئێستا تەواو: پێنج نمرە بخوێنەوە بۆ ناو ، پاشان سێ جار بەکاری بهێنە: بۆ ناوەند، باشترین نمرە و ژمارەی ئەو قوتابیانەی لە سەرووی ناوەندن. بەبێ سێیەم مەحاڵ دەبوو، چونکە نمرەکان نەمابوون (Scanner):

ReadMarks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class ReadMarks {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] marks = new int[5];
        for (int i = 0; i < marks.length; i++) {
            System.out.print("Mark of student " + (i + 1) + ": ");
            marks[i] = input.nextInt();
        }
        int sum = 0;
        int best = marks[0];
        for (int mark : marks) {
            sum += mark;
            if (mark > best) {
                best = mark;
            }
        }
        double average = (double) sum / marks.length;
        System.out.println("Average: " + average);
        System.out.println("Best mark: " + best);
        int above = 0;
        for (int mark : marks) {
            if (mark > average) {
                above++;
            }
        }
        System.out.println(above + " students are above the average.");
    }
}

best starts as the first mark, not as 0: with all marks negative (say, temperatures in winter) a start of 0 would be wrong. The same pattern with an index finds where the best value is (see the exercises).

best بە نمرەی یەکەم دەست پێ دەکات، نەک بە 0: ئەگەر هەموو بن (بۆ نموونە پلەی گەرمی لە زستاندا) دەستپێکردن بە 0 هەڵە دەبێت. هەمان شێواز بە دەدۆزێتەوە باشترین لە کوێیە (ڕاهێنانەکان ببینە).

Arrays and methodsڕیزەکەکان و میتۆدەکان

A method can take an array as a (int[] numbers) and can return one (return type int[]) (Methods). Because the method gets the reference, it can change the caller's array; an int parameter is only a copy (pass by value):

دەتوانێت وەک وەربگرێت (int[] numbers) و دەتوانێت یەکێک بگەڕێنێتەوە ( int[]) (میتۆدەکان). چونکە وەردەگرێت، دەتوانێت بانگکەر بگۆڕێت؛ int تەنیا کۆپییەکە (ناردن بە نرخ):

ArrayMethods.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class ArrayMethods {
    static double average(int[] numbers) {
        int sum = 0;
        for (int n : numbers) {
            sum += n;
        }
        return (double) sum / numbers.length;
    }

    static void addBonus(int[] numbers, int bonus) {
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] += bonus;          // changes the caller's array
        }
    }

    static void addBonusToOne(int mark, int bonus) {
        mark += bonus;                    // changes only the copy in mark
    }

    static int[] squares(int n) {
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = (i + 1) * (i + 1);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] marks = {90, 75, 88};
        System.out.println("Average: " + average(marks));
        addBonus(marks, 2);
        System.out.println("After addBonus: " + Arrays.toString(marks));
        addBonusToOne(marks[0], 50);
        System.out.println("After addBonusToOne: " + Arrays.toString(marks));
        System.out.println("squares(5): " + Arrays.toString(squares(5)));
    }
}
main has the variable marks and addBonus(numbers, 2) has the parameter numbers; both arrows point at one array 92, 77, 90, changed by the method: +2 each. Below, addBonusToOne(marks[0], 50): the value 92 is copied into mark and becomes 142, while marks[0] stays 92. Note: an int parameter is a copy; an array parameter refers to the caller's array.main گۆڕاوی marksـی هەیە و addBonus(numbers, 2) پارامیتەری numbers؛ هەردوو تیرەکە ئاماژە بە یەک ڕیزەک دەکەن، 92، 77، 90، کە میتۆدەکە گۆڕیویەتی: هەریەکە +2. لە خوارەوە، addBonusToOne(marks[0], 50): نرخی 92 کۆپی دەکرێت بۆ mark و دەبێتە 142، لە کاتێکدا marks[0] هەر 92 دەمێنێتەوە. تێبینی: پارامیتەرێکی int کۆپییەکە؛ پارامیتەرێکی ڕیزەک ئاماژە بە ڕیزەکەکەی بانگکەر دەکات.
The method and main share one array; an int is copied و main یەک بەکار دەهێنن؛ int کۆپی دەکرێتCêIT

Arrays and methodsڕیزەکەکان و میتۆدەکان

Removing an element: a new, shorter arrayلابردنی دانەیەک: ڕیزەکێکی نوێی کورتتر

An array cannot shrink either. To "remove" the element at an index, a method makes a new array one place shorter and copies the others into it: the elements before the index keep their places, and each element after it moves one place to the left. The method returns the new array:

بچووکیش نابێتەوە. بۆ «لابردنی» ئەو لە ، نوێ دروست دەکات کە یەک شوێن کورتترە و ئەوانی تری تێدا کۆپی دەکات: پێش لە شوێنی خۆیان دەمێننەوە و هەر دوای ئەو یەک شوێن بەرەو چەپ دەچێت. نوێ دەگەڕێنێتەوە:

RemoveElement.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class RemoveElement {
    static int[] removeAt(int[] array, int index) {
        if (index < 0 || index >= array.length) {
            throw new IndexOutOfBoundsException("Index " + index + " is not in the array");
        }
        int[] result = new int[array.length - 1];      // one place shorter
        for (int i = 0; i < index; i++) {              // before the index: the same place
            result[i] = array[i];
        }
        for (int i = index + 1; i < array.length; i++) {   // after it: one place to the left
            result[i - 1] = array[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] numbers = {3, 8, 5, 2, 10};
        int[] shorter = removeAt(numbers, 2);
        System.out.println("Before: " + Arrays.toString(numbers));
        System.out.println("After removing index 2: " + Arrays.toString(shorter));
        removeAt(numbers, 7);
    }
}
Top row, array: 3, 8, 5, 2, 10 at the indexes 0 to 4; the 5 at index 2 is crossed out and left out. Bottom row, result: 3, 8, 2, 10 at the indexes 0 to 3. Green arrows go straight down from indexes 0 and 1: before the index, the same place, result[i] = array[i]. Grey arrows go down and one place to the left from indexes 3 and 4: after the index, one place to the left, result[i - 1] = array[i]. Note: new int[array.length - 1] has length 4; array itself does not change.ڕیزی سەرەوە، array: 3، 8، 5، 2، 10 لە ئیندێکسەکانی 0 تا 4؛ 5ـەکەی ئیندێکسی 2 خەتی بەسەردا هاتووە و کۆپی ناکرێت. ڕیزی خوارەوە، result: 3، 8، 2، 10 لە ئیندێکسەکانی 0 تا 3. تیری سەوز لە ئیندێکسەکانی 0 و 1ـەوە ڕاست بۆ خوارەوە دەچن: پێش ئیندێکسەکە، هەمان شوێن، result[i] = array[i]. تیری خۆڵەمێشی لە ئیندێکسەکانی 3 و 4ـەوە بۆ خوارەوە و یەک شوێن بەرەو چەپ دەچن: دوای ئیندێکسەکە، یەک شوێن بەرەو چەپ، result[i - 1] = array[i]. تێبینی: new int[array.length - 1] درێژییەکەی 4ـە؛ array خۆی ناگۆڕێت.
Before the index: the same place; after it: one place to the leftپێش : هەمان شوێن؛ دوای ئەو: یەک شوێن بەرەو چەپCêIT

The if at the top refuses an index outside the array: throw stops the method with an exception, as Java itself does for numbers[7] (throw comes later). The original array does not change. An ArrayList does all of this for you with remove(index).

ifـەکەی سەرەوە دەرەوەی ڕەت دەکاتەوە: throw بە ڕادەگرێت، هەروەک خودی Java بۆ numbers[7] دەیکات (throw دواتر دێت). سەرەکی ناگۆڕێت. ArrayList هەموو ئەمە بە remove(index) بۆت دەکات.

Arrays and methodsڕیزەکەکان و میتۆدەکان

String[] args: the array in main⁦String[] args⁩: ڕیزەکەکە لە mainـدا

Now you can read the header public static void main(String[] args): main receives an array of strings. It holds the words typed after the class name in the terminal:

ئێستا دەتوانیت سەرەی public static void main(String[] args) بخوێنیتەوە: main وەردەگرێت. ئەو وشانەی تێدایە کە لە لە دوای ناوی نووسراون:

Greet.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Greet {
    public static void main(String[] args) {
        System.out.println("args.length = " + args.length);
        for (String name : args) {
            System.out.println("Hello, " + name + "!");
        }
    }
}
The command java Greet Aram Shilan in a terminal. Arrows carry the words Aram and Shilan into an array called args with the indexes 0 and 1. Note: args.length is 2; with no words after Greet, args is an empty array of length 0.فەرمانی java Greet Aram Shilan لە تێرمیناڵێکدا. تیرەکان وشەکانی Aram و Shilan دەبەنە ناو ڕیزەکێک بە ناوی args بە ئیندێکسەکانی 0 و 1. تێبینی: args.length دەکاتە 2؛ ئەگەر هیچ وشەیەک لە دوای Greet نەبێت، args ڕیزەکێکی بەتاڵە بە درێژیی 0.
The words after the class name become the elements of argsوشەکانی دوای ناوی دەبنە argsCêIT

Other methods of the API return arrays too: "Aram,Shilan".split(",") gives a String[] (split).

تری دەگەڕێننەوە: "Aram,Shilan".split(",") String[]ـێک دەدات (split).

Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون

A timetable, a seating plan or a table of marks has rows and columns. A stores such a table. The type has two pairs of brackets, the values are given row by row, and an element is reached with two indexes, row first, then column:

خشتەی وانەکان، نەخشەی دانیشتن یان خشتەی نمرەکان و هەیە. خشتەیەکی لەو جۆرە هەڵدەگرێت. جۆرەکەی دوو جووت کەوانەی چوارگۆشەی هەیە، بە دەدرێن و بە دوو دەگەیتە : یەکەم ، پاشان :

Timetable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Timetable {
    public static void main(String[] args) {
        String[][] timetable = {
            {"Maths", "Java", "English"},       // row 0: Saturday
            {"Physics", "Maths", "Java"},       // row 1: Sunday
            {"English", "Kurdish", "Java"}      // row 2: Monday
        };
        System.out.println(timetable[1][2]);              // Sunday, third lesson
        System.out.println(timetable[2][0]);              // Monday, first lesson
        timetable[0][2] = "Sport";                        // Saturday's third lesson changes
        System.out.println(timetable[0][2]);
        System.out.println("Rows: " + timetable.length);
        System.out.println("Columns in row 0: " + timetable[0].length);
    }
}
A 3 by 3 grid: rows 0 Sat, 1 Sun and 2 Mon, columns 0, 1 and 2. Row 0: Maths, Java, English; row 1: Physics, Maths, Java; row 2: English, Kurdish, Java. The cell in row 1, column 2 (Java) is highlighted: timetable[1][2] -> "Java". Notes: timetable.length is 3 (rows); timetable[0].length is 3 (columns); like a matrix entry a_ij, i is the row and j the column.تۆڕێکی 3 لە 3: ڕیزەکانی 0 شەممە، 1 یەکشەممە و 2 دووشەممە، ستوونەکانی 0، 1 و 2. ڕیز 0: Maths، Java، English؛ ڕیز 1: Physics، Maths، Java؛ ڕیز 2: English، Kurdish، Java. خانەی ڕیز 1، ستوون 2 (Java) نیشان کراوە: timetable[1][2] -> "Java". تێبینییەکان: timetable.length دەکاتە 3 (ڕیزەکان)؛ timetable[0].length دەکاتە 3 (ستوونەکان)؛ وەک دانەی a_ij لە ماتریکسێکدا، i ڕیزە و j ستوونە.
timetable[row][column]: row first, then column⁦timetable[row][column]⁩: یەکەم ، پاشان CêIT

This is the order of maths, where the entry aija_{ij} of a is in row i and column j (Matrix entries). Python keeps tables as lists of lists (Two-dimensional lists) and MATLAB has matrices built in (Matrices).

ئەمە ڕیزبەندیی بیرکارییە، کە تێیدا دانەی aija_{ij}ـی لە i و jـدایە (دانەکانی ماتریکس). Python خشتەکان وەک لە هەڵدەگرێت (لیستە دووڕەهەندەکان) و MATLAB لە خۆیدا هەیە (ماتریکسەکان).

Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون

Nested loops over a tableخولە ناوەکییەکان بەسەر خشتەیەکدا

To visit every element, put one loop inside another (Nested loops): the outer loop picks a row, the inner loop walks along it. timetable[row].length is the length of that row:

بۆ سەردانی هەموو ، بخەرە ناو یەکێکی ترەوە (خولە ناوەکییەکان): دەرەوە هەڵدەبژێرێت، ناوەوە بە درێژاییدا دەڕوات. timetable[row].length درێژیی ئەو :

PrintTimetable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PrintTimetable {
    public static void main(String[] args) {
        String[] days = {"Sat", "Sun", "Mon"};
        String[][] timetable = {
            {"Maths", "Java", "English"},
            {"Physics", "Maths", "Java"},
            {"English", "Kurdish", "Java"}
        };
        for (int row = 0; row < timetable.length; row++) {
            System.out.print(days[row] + ": ");
            for (int col = 0; col < timetable[row].length; col++) {
                System.out.printf("%-9s", timetable[row][col]);
            }
            System.out.println();
        }
    }
}
An animation of nested loops over the 3 by 3 timetable. A highlighted cell moves along row 0 (Maths, Java, English), then row 1, then row 2, while the boxes row and col show the indexes and the output grows one line per row. Last frame: 3 rows x 3 columns = 9 visits; each row ends with println().
An animation of nested loops over the 3 by 3 timetable. A highlighted cell moves along row 0 (Maths, Java, English), then row 1, then row 2, while the boxes row and col show the indexes and the output grows one line per row. Last frame: 3 rows x 3 columns = 9 visits; each row ends with println().
The outer loop chooses the row, the inner loop the column دەرەوە و ناوەوە هەڵدەبژێرێتCêIT

%-9s pads each word to 9 places so the columns line up (Width and flags). For sums per row, reset the total at the start of each row:

%-9s هەر وشەیەک بۆ 9 شوێن پڕ دەکاتەوە تا ڕێک بن (پانی و ئاڵاکان). بۆ کۆی هەر ، کۆکە لە سەرەتای هەر سفر بکەرەوە:

MarkTable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class MarkTable {
    public static void main(String[] args) {
        int[][] marks = {
            {90, 75, 88},   // Aram:   Maths, Java, English
            {62, 95, 70},   // Shilan
            {80, 85, 91}    // Karwan
        };
        String[] students = {"Aram", "Shilan", "Karwan"};
        for (int row = 0; row < marks.length; row++) {
            int total = 0;
            for (int col = 0; col < marks[row].length; col++) {
                total += marks[row][col];
            }
            System.out.println(students[row] + ": total " + total);
        }
        for (int[] row : marks) {               // for-each: each row is an int[]
            System.out.println(Arrays.toString(row));
        }
    }
}

Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون

A 2-D array is an array of arraysڕیزەکی دووڕەهەند ڕیزەکێکە لە ڕیزەکەکان

Java has no real tables. new int[3][4] makes an array of 3 elements, and each element is itself an int[4] row, all 0. So seats[0] is a whole row, seats.length counts rows and Arrays.toString(seats) prints three array codes; Arrays.deepToString prints the numbers:

Java خشتەی ڕاستەقینەی نییە. new int[3][4] 3 دروست دەکات و هەر خۆی int[4]ـە، هەمووی 0. بۆیە seats[0] تەواوە، seats.length دەژمێرێت و Arrays.toString(seats) سێ کۆدی چاپ دەکات؛ Arrays.deepToString ژمارەکان چاپ دەکات:

Seats.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class Seats {
    public static void main(String[] args) {
        int[][] seats = new int[3][4];          // 3 rows, 4 seats in each row, all 0
        seats[0][1] = 1;                        // 1 = taken
        seats[2][3] = 1;
        System.out.println(Arrays.deepToString(seats));
        System.out.println(Arrays.toString(seats));
        System.out.println(Arrays.toString(seats[0]));
    }
}
Left: the variable seats points at an outer array of 3 boxes, numbered 0 to 2; each box points at its own row of 4 ints: 0 1 0 0, 0 0 0 0 and 0 0 0 1. seats[2] is a whole row, an int[]. Right, marked extra: int[][] t = new int[4][]; an outer array of 4 boxes pointing at rows of lengths 1, 2, 3 and 4. Note: new int[3][4] makes 3 rows, each an int[4], all 0; every row has its own length field.چەپ: گۆڕاوی seats ئاماژە بە ڕیزەکێکی دەرەوەی 3 سندووق دەکات، ژمارەدار 0 تا 2؛ هەر سندووقێک ئاماژە بە ڕیزی خۆی دەکات بە 4 int: 0 1 0 0، 0 0 0 0 و 0 0 0 1. seats[2] ڕیزێکی تەواوە، int[]. ڕاست، بە نیشانەی زیادە: int[][] t = new int[4][]; ڕیزەکێکی دەرەوەی 4 سندووق کە ئاماژە بە ڕیزەکان دەکەن بە درێژیی 1، 2، 3 و 4. تێبینی: new int[3][4] 3 ڕیز دروست دەکات، هەریەکە int[4]، هەمووی 0؛ هەر ڕیزێک lengthـی خۆی هەیە.
The outer array holds references to the rows دەرەوە هەڵدەگرێتCêIT

Common mistakesهەڵە باوەکان

You wroteنووسیتjavac or the run saysjavac یان جێبەجێکردن دەڵێتFixچارەسەر
marks[5](length 5) ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5(درێژی ⁦5⁩) ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5The last index is length - 1.دوایین length - 1ـە.
i <= marks.lengththe same exception after the last elementهەمان دوای دوایین Use i < marks.length.i < marks.length بەکار بهێنە.
marks.length()cannot find symbol symbol: method length()Arrays: length; strings: length().: length؛ : length().
System.out.println(marks);[I@7344699f[I@7344699fArrays.toString(marks).Arrays.toString(marks).
a == bfalse for two arrays with equal elementsfalse بۆ دوو بە یەکسانArrays.equals(a, b).Arrays.equals(a, b).
int[] b = a;changes through b appear in aگۆڕانکاری لە ڕێگەی bـەوە لە aـدا دەردەکەوێتCopy: Arrays.copyOf(a, a.length).کۆپی: Arrays.copyOf(a, a.length).
names[2].length()(nothing stored) NullPointerException(هیچ هەڵنەگیراوە) NullPointerExceptionFill the element first, or check != null.سەرەتا پڕ بکەرەوە، یان != null بپشکنە.
new int[3]{1, 2, 3}array creation with both dimension expression and initialization is illegalnew int[] {1, 2, 3} or {1, 2, 3}.new int[] {1, 2, 3} یان {1, 2, 3}.
b = {1, 2};illegal start of expressionBraces alone only in the declaration; else b = new int[] {1, 2};.کەوانە بە تەنیا تەنیا لە ناساندندا؛ ئەگینا b = new int[] {1, 2};.
for (int m : marks) m = 0;no message, but the array does not changeهیچ پەیامێک نییە، بەڵام ناگۆڕێتChange elements through the index. لە ڕێگەی بگۆڕە.

The real javac messages for the two wrong ways of creating an array:

پەیامە ڕاستەقینەکانی javac بۆ دوو ڕێگە هەڵەکەی دروستکردنی :

Outputدەرئەنجام
$ javac InitErrors.java
InitErrors.java:3: error: array creation with both dimension expression and initialization is illegal
        int[] a = new int[3]{1, 2, 3};
                            ^
InitErrors.java:5: error: illegal start of expression
        b = {1, 2};
            ^
InitErrors.java:5: error: not a statement
        b = {1, 2};
             ^
InitErrors.java:5: error: ';' expected
        b = {1, 2};
              ^
4 errors

Practiceڕاهێنان

ExerciseڕاهێنانReverse an arrayپێچەوانەکردنەوەی ڕیزەکێک

Reverse int[] numbers = {3, 8, 1, 9, 4}; in place (no second array), then print it.

int[] numbers = {3, 8, 1, 9, 4}; لە شوێنی خۆیدا پێچەوانە بکەرەوە (بەبێ دووەم)، پاشان چاپی بکە.

Hintئاماژە

Use a temp variable, and numbers.length - 1 - i for the partner from the end.

temp بەکار بهێنە و numbers.length - 1 - i بۆ هاوبەشەکە لە کۆتاییەوە.

Show answerوەڵامەکە پیشان بدە
Reverse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class Reverse {
    public static void main(String[] args) {
        int[] numbers = {3, 8, 1, 9, 4};
        for (int i = 0; i < numbers.length / 2; i++) {
            int j = numbers.length - 1 - i;      // the partner from the other end
            int temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
        System.out.println(Arrays.toString(numbers));
    }
}

Swap the first with the last, the second with the second-to-last, and stop at the middle: length / 2 swaps (Swapping).

یەکەم لەگەڵ دوایین، دووەم لەگەڵ پێش دوایین جێگۆڕکێ بکە و لە ناوەڕاستدا بوەستە: length / 2 جێگۆڕکێ (جێگۆڕکێ).

ExerciseڕاهێنانHow many passed?چەند کەس دەرچوون؟

Count the marks of 50 or more in {90, 45, 88, 30, 62, 49, 75}.

نمرەکانی ⁦50⁩ و سەرووتر لە {90, 45, 88, 30, 62, 49, 75}ـدا بژمێرە.

Show answerوەڵامەکە پیشان بدە
Passed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Passed {
    public static void main(String[] args) {
        int[] marks = {90, 45, 88, 30, 62, 49, 75};
        int passed = 0;
        for (int mark : marks) {
            if (mark >= 50) {
                passed++;
            }
        }
        System.out.println(passed + " of " + marks.length + " passed");
    }
}
ExerciseڕاهێنانFind a nameدۆزینەوەی ناوێک

Find the index of "Karwan" in {"Aram", "Shilan", "Karwan", "Dilan"}; print -1 if the name is not there.

"Karwan" لە {"Aram", "Shilan", "Karwan", "Dilan"}ـدا بدۆزەرەوە؛ ئەگەر ناوەکە نەبوو -1 چاپ بکە.

Show answerوەڵامەکە پیشان بدە
FindName.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class FindName {
    public static void main(String[] args) {
        String[] names = {"Aram", "Shilan", "Karwan", "Dilan"};
        String wanted = "Karwan";
        int position = -1;                       // -1 = not found yet
        for (int i = 0; i < names.length; i++) {
            if (names[i].equals(wanted)) {
                position = i;
                break;
            }
        }
        System.out.println(wanted + " is at index " + position);
    }
}

Compare strings with equals, and stop at the first match with break (Search and stop). This is a .

بە equals بەراورد بکە و بە break لە یەکەم یەکگرتنەوەدا بوەستە (گەڕان و وەستان). ئەمە .

ExerciseڕاهێنانThe best dayباشترین ڕۆژ

int[] steps = {4200, 8100, 6500, 9900, 7300}; holds the steps of five days. Print on which day (1 to 5) the most steps were walked.

int[] steps = {4200, 8100, 6500, 9900, 7300}; هەنگاوەکانی پێنج ڕۆژ هەڵدەگرێت. چاپ بکە لە کام ڕۆژدا (⁦1⁩ تا ⁦5⁩) زۆرترین هەنگاو نراوە.

Show answerوەڵامەکە پیشان بدە
MaxIndex.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class MaxIndex {
    public static void main(String[] args) {
        int[] steps = {4200, 8100, 6500, 9900, 7300};
        int best = 0;
        for (int i = 1; i < steps.length; i++) {
            if (steps[i] > steps[best]) {
                best = i;
            }
        }
        System.out.println("Most steps on day " + (best + 1) + ": " + steps[best]);
    }
}

Keep the index of the best value, not the value: the day number is best + 1.

باشترین هەڵبگرە، نەک خودی : ژمارەی ڕۆژەکە best + 1ـە.

ExerciseڕاهێنانA week in Hawlerهەفتەیەک لە هەولێر

Two arrays side by side: days with the seven day names and temps with the seven temperatures 18.5, 21.0, 19.5, 23.0, 25.5, 24.0 and 20.5. Print the average and the name of the hottest day.

دوو لە تەنیشت یەک: days بە ناوی حەوت ڕۆژەکە و temps بە حەوت پلەی گەرمیی ⁦18.5⁩، ⁦21.0⁩، ⁦19.5⁩، ⁦23.0⁩، ⁦25.5⁩، ⁦24.0⁩ و ⁦20.5⁩. ناوەند و ناوی گەرمترین ڕۆژ چاپ بکە.

Show answerوەڵامەکە پیشان بدە
WeekTemps.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class WeekTemps {
    public static void main(String[] args) {
        String[] days = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
        double[] temps = {18.5, 21.0, 19.5, 23.0, 25.5, 24.0, 20.5};   // Hawler, one week in October
        double sum = 0;
        int hottest = 0;                  // the index of the hottest day so far
        for (int i = 0; i < temps.length; i++) {
            sum += temps[i];
            if (temps[i] > temps[hottest]) {
                hottest = i;
            }
        }
        System.out.printf("Average: %.1f degrees%n", sum / temps.length);
        System.out.println("Hottest: " + days[hottest] + ", " + temps[hottest] + " degrees");
    }
}

The same index connects the two arrays: days[hottest] belongs to temps[hottest].

هەمان هەردوو پێکەوە دەبەستێتەوە: days[hottest] هی temps[hottest]ـە.

ExerciseڕاهێنانColumn averagesناوەندی ستوونەکان

int[][] marks has a row per student and a column per subject (Maths, Java, English). Print the average of each subject.

int[][] marks بۆ هەر قوتابییەک و بۆ هەر بابەتێک هەیە (Maths، Java، English). ناوەندی هەر بابەتێک چاپ بکە.

Show answerوەڵامەکە پیشان بدە
ColumnAverages.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ColumnAverages {
    public static void main(String[] args) {
        int[][] marks = {
            {90, 75, 88},
            {62, 95, 70},
            {80, 85, 91}
        };
        String[] subjects = {"Maths", "Java", "English"};
        for (int col = 0; col < marks[0].length; col++) {
            int sum = 0;
            for (int row = 0; row < marks.length; row++) {
                sum += marks[row][col];
            }
            System.out.printf("%s average: %.1f%n", subjects[col], (double) sum / marks.length);
        }
    }
}

Here the outer loop walks the columns and the inner loop the rows, because each sum runs down one column.

لێرەدا دەرەوە بەسەر و ناوەوە بەسەر دەڕوات، چونکە هەر کۆیەک بە درێژایی یەک دەڕوات.

More practice: methods that work on arraysڕاهێنانی زیاتر: ئەو میتۆدانەی کار لەسەر ڕیزەک دەکەن

Write each task as one method, like removeAt in Removing an element. Call it from main and print the result with Arrays.toString. The picture shows what each method should give back:

هەر ئەرکێک وەک یەک بنووسە، وەک removeAt لە لابردنی دانەیەک. لە mainـەوە بانگی بکە و ئەنجامەکە بە Arrays.toString چاپ بکە. وێنەکە نیشان دەدات هەر دەبێت چی بگەڕێنێتەوە:

Five rows, each an input and what the method gives back. isPalindrome, the same from both ends: r, a, d, a, r, with dashed arcs joining the two r's and the two a's, gives true. merge, one array after the other: 1, 3, 5 plus 2, 4 gives 1, 3, 5, 2, 4. rotateRight, every element k places right: 1, 2, 3, 4, 5 with k = 2 gives 4, 5, 1, 2, 3; the 4 and 5 that fell off the end are blue at the start. addArrays, add place by place: 1, 2, 3 plus 10, 20, 30 gives 11, 22, 33. withoutDuplicates, each value once, in order: 3, 1, 3, 2, 1, with the second 3 and the second 1 greyed out, gives 3, 1, 2.پێنج ڕیز، هەریەکەیان ئەوەی دەچێتە ژوورەوە و ئەوەی میتۆدەکە دەیگەڕێنێتەوە. isPalindrome، لە هەردوو سەرەوە وەک یەک: r، a، d، a، r، بە کەوانەی پچڕپچڕ کە دوو rـەکە و دوو aـەکە پێکەوە دەبەستن، دەدات true. merge، ڕیزەکێک لە دوای ئەوی تر: 1، 3، 5 لەگەڵ 2، 4 دەدات 1، 3، 5، 2، 4. rotateRight، هەر دانەیەک k شوێن بەرەو ڕاست: 1، 2، 3، 4، 5 بە k = 2 دەدات 4، 5، 1، 2، 3؛ ئەو 4 و 5ـەی لە کۆتاییەوە کەوتنە دەرەوە بە شین لە سەرەتادان. addArrays، کۆکردنەوەی شوێن بە شوێن: 1، 2، 3 لەگەڵ 10، 20، 30 دەدات 11، 22، 33. withoutDuplicates، هەر نرخێک یەک جار، بە ڕیزبەندی: 3، 1، 3، 2، 1، کە 3ـی دووەم و 1ـی دووەم کاڵ کراونەتەوە، دەدات 3، 1، 2.
Five methods: what goes in on the left, the result on the rightپێنج : ئەوەی دەچێتە ژوورەوە لە چەپ، ئەنجامەکە لە ڕاستCêIT
ExerciseڕاهێنانSame from both endsلە هەردوو سەرەوە وەک یەک

Write static boolean isPalindrome(char[] letters): true when the letters read the same from both ends. Test it with {'r', 'a', 'd', 'a', 'r'} and {'j', 'a', 'v', 'a'}.

static boolean isPalindrome(char[] letters) بنووسە: true کاتێک لە هەردوو سەرەوە وەک یەک دەخوێنرێنەوە. بە {'r', 'a', 'd', 'a', 'r'} و {'j', 'a', 'v', 'a'} تاقیی بکەرەوە.

Hintئاماژە

Compare letters[i] with its partner letters[letters.length - 1 - i] and stop at the middle, as in Reverse an array.

letters[i] لەگەڵ هاوبەشەکەی letters[letters.length - 1 - i] بەراورد بکە و لە ناوەڕاستدا بوەستە، وەک لە پێچەوانەکردنەوەی .

Show answerوەڵامەکە پیشان بدە
Palindrome.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Palindrome {
    static boolean isPalindrome(char[] letters) {
        for (int i = 0; i < letters.length / 2; i++) {
            if (letters[i] != letters[letters.length - 1 - i]) {
                return false;                  // the first pair that differs decides
            }
        }
        return true;
    }

    public static void main(String[] args) {
        char[] radar = {'r', 'a', 'd', 'a', 'r'};
        char[] javaWord = {'j', 'a', 'v', 'a'};
        System.out.println("radar: " + isPalindrome(radar));
        System.out.println("java: " + isPalindrome(javaWord));
    }
}

One pair that differs is enough to return false; only when every pair matches is it true. For a word in a String, see the strings practice.

یەک جووتی جیاواز بەسە بۆ گەڕاندنەوەی false؛ تەنیا کاتێک هەموو جووتەکان وەک یەک بن trueـە. بۆ وشەیەک لە Stringـێکدا، ڕاهێنانەکانی زنجیرەنووسەکان ببینە.

ExerciseڕاهێنانMerge two arraysیەکخستنی دوو ڕیزەک

Write static int[] merge(int[] first, int[] second): one new array with all the elements of first, then all of second, in their order. {1, 3, 5} and {2, 4} give [1, 3, 5, 2, 4].

static int[] merge(int[] first, int[] second) بنووسە: یەک نوێ بە هەموو first و پاشان هەموو ئەوانەی second، بە ڕیزبەندیی خۆیان. {1, 3, 5} و {2, 4} دەدەن [1, 3, 5, 2, 4].

Hintئاماژە

The new length is first.length + second.length.

درێژیی نوێ first.length + second.lengthـە.

Show answerوەڵامەکە پیشان بدە
Merge.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class Merge {
    static int[] merge(int[] first, int[] second) {
        int[] result = new int[first.length + second.length];
        for (int i = 0; i < first.length; i++) {
            result[i] = first[i];
        }
        for (int i = 0; i < second.length; i++) {
            result[first.length + i] = second[i];     // continue after the first array
        }
        return result;
    }

    public static void main(String[] args) {
        int[] odd = {1, 3, 5};
        int[] even = {2, 4};
        System.out.println(Arrays.toString(merge(odd, even)));
    }
}

The elements of second go on where first stops, at index first.length + i.

second لەو شوێنەوە بەردەوام دەبن کە first تێیدا دەوەستێت، لە first.length + i.

ExerciseڕاهێنانRotate to the rightسووڕاندن بەرەو ڕاست

Write static int[] rotateRight(int[] a, int k) (k is 0 or more): every element moves k places to the right, and the ones that fall off the end come back at the start. {1, 2, 3, 4, 5} with k = 2 gives [4, 5, 1, 2, 3].

static int[] rotateRight(int[] a, int k) بنووسە (k 0 یان زیاترە): هەر k شوێن بەرەو ڕاست دەچێت و ئەوانەی لە کۆتاییەوە دەکەونە دەرەوە لە سەرەتاوە دەگەڕێنەوە. {1, 2, 3, 4, 5} بە k = 2 دەدات [4, 5, 1, 2, 3].

Hintئاماژە

Element a[i] goes to index (i + k) % a.length (the remainder operator).

a[i] دەچێتە (i + k) % a.length (پاشماوە).

Show answerوەڵامەکە پیشان بدە
Rotate.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class Rotate {
    static int[] rotateRight(int[] a, int k) {
        int[] result = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            result[(i + k) % a.length] = a[i];       // past the end? % brings it back to the start
        }
        return result;
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        System.out.println("k = 2: " + Arrays.toString(rotateRight(numbers, 2)));
        System.out.println("k = 7: " + Arrays.toString(rotateRight(numbers, 7)));
        System.out.println("k = 5: " + Arrays.toString(rotateRight(numbers, 5)));
    }
}

% also handles a k larger than the length: 7 places on 5 elements is the same as 2, and 5 places bring every element back home.

% ئەو kـەش چارەسەر دەکات کە لە درێژییەکە گەورەترە: 7 شوێن لەسەر 5 وەک 2 شوێن وایە و 5 شوێن هەموو دەگەڕێنێتەوە شوێنی خۆیان.

ExerciseڕاهێنانAdd two arraysکۆکردنەوەی دوو ڕیزەک

Write static int[] addArrays(int[] a, int[] b) for two arrays of the same length: element i of the result is a[i] + b[i]. {1, 2, 3} and {10, 20, 30} give [11, 22, 33].

static int[] addArrays(int[] a, int[] b) بۆ دوو بە هەمان درێژی بنووسە: iـی ئەنجامەکە a[i] + b[i]ـە. {1, 2, 3} و {10, 20, 30} دەدەن [11, 22, 33].

Show answerوەڵامەکە پیشان بدە
AddArrays.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class AddArrays {
    static int[] addArrays(int[] a, int[] b) {
        int[] sums = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            sums[i] = a[i] + b[i];                   // the same index in both arrays
        }
        return sums;
    }

    public static void main(String[] args) {
        int[] first = {1, 2, 3};
        int[] second = {10, 20, 30};
        System.out.println(Arrays.toString(addArrays(first, second)));
    }
}

One index walks both arrays at once. If the lengths may differ, check them first and throw an exception, as removeAt does for a wrong index.

یەک هاوکات بەسەر هەردوو دەڕوات. ئەگەر درێژییەکان لەوانەیە جیاواز بن، سەرەتا بیانپشکنە و فڕێ بدە، وەک ئەوەی removeAt بۆ هەڵە دەیکات.

ExerciseڕاهێنانEach value onceهەر نرخێک یەک جار

Write static int[] withoutDuplicates(int[] a): a new array with each value once, in the order it first appears. {3, 1, 3, 2, 1} gives [3, 1, 2].

static int[] withoutDuplicates(int[] a) بنووسە: نوێ کە هەر تەنیا یەک جاری تێدایە، بەو ڕیزبەندییەی یەکەم جار دەردەکەوێت. {3, 1, 3, 2, 1} دەدات [3, 1, 2].

Hintئاماژە

Keep the values in a second array and count how many you kept. Before keeping a value, look for it among the kept ones; at the end, cut the array with Arrays.copyOf(kept, count).

لە دووەمدا هەڵبگرە و بژمێرە چەندت هەڵگرتووە. پێش هەڵگرتنی هەر ، لە ناو هەڵگیراوەکاندا بەدوایدا بگەڕێ؛ لە کۆتاییدا بە Arrays.copyOf(kept, count) کورت بکەرەوە.

Show answerوەڵامەکە پیشان بدە
NoDuplicates.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Arrays;

public class NoDuplicates {
    static int[] withoutDuplicates(int[] a) {
        int[] kept = new int[a.length];   // room for the worst case: no duplicates at all
        int count = 0;                    // how many places of kept are used
        for (int value : a) {
            boolean seen = false;
            for (int j = 0; j < count; j++) {
                if (kept[j] == value) {
                    seen = true;
                    break;
                }
            }
            if (!seen) {
                kept[count] = value;
                count++;
            }
        }
        return Arrays.copyOf(kept, count);   // cut off the unused places
    }

    public static void main(String[] args) {
        int[] numbers = {3, 1, 3, 2, 1};
        System.out.println(Arrays.toString(withoutDuplicates(numbers)));
    }
}

Later, a LinkedHashSet does the same in one line (Removing duplicates).

دواتر LinkedHashSet هەمان کار لە یەک دێڕدا دەکات (لابردنی دووپاتەکان).

Summaryکورتە

  • An array holds a fixed number of values of one type: int[] a = {…} or new int[n] (filled with default values: 0, false, null).
  • Indexes run from 0 to a.length - 1; anything else throws ArrayIndexOutOfBoundsException. length has no brackets.
  • Loop with for (int i = 0; i < a.length; i++) to use indexes; with for-each to read the elements (it gives copies).
  • An array variable holds a reference: b = a shares the array; Arrays.copyOf copies; Arrays.equals compares.
  • To remove an element, copy the others into a new array one place shorter (or use an ArrayList).
  • java.util.Arrays: toString, sort, fill, equals, copyOf. Methods can take and return arrays; main gets String[] args.
  • A 2-D array t[row][col] is an array of row arrays, visited with nested loops.
  • ژمارەیەکی جێگیر لە یەک جۆر هەڵدەگرێت: int[] a = {…} یان new int[n] (پڕ لە : 0، false، null).
  • لە 0ـەوە تا a.length - 1 دەڕۆن؛ هەر شتێکی تر ArrayIndexOutOfBoundsException فڕێ دەدات. length کەوانەی نییە.
  • بۆ بە for (int i = 0; i < a.length; i++) بسووڕێوە؛ بۆ خوێندنەوەی بە (کۆپی دەدات).
  • هەڵدەگرێت: b = a هاوبەش دەکات؛ Arrays.copyOf کۆپی دەکات؛ Arrays.equals بەراورد دەکات.
  • بۆ لابردنی ، ئەوانی تر کۆپی بکە بۆ نوێ کە یەک شوێن کورتترە (یان ArrayList بەکار بهێنە).
  • java.util.Arrays: toString، sort، fill، equals، copyOf. دەتوانن وەربگرن و بیگەڕێننەوە؛ main String[] args وەردەگرێت.
  • t[row][col] لە (هەریەکەیان ) و بە سەردان دەکرێت.
Review questionsپرسیارەکانی پێداچوونەوە
Why does System.out.println(a) print something like [I@7344699f?بۆچی System.out.println(a) شتێکی وەک [I@7344699f چاپ دەکات؟

Because a is a reference to an array object; use Arrays.toString(a) to see the elements.

چونکە a بۆ ؛ بۆ بینینی Arrays.toString(a) بەکار بهێنە.

How do you add a sixth element to an array of five?چۆن دانەیەکی شەشەم زیاد دەکەیت بۆ ڕیزەکێکی پێنجی؟

You cannot: copy it into a longer array with Arrays.copyOf(a, 6), or use an ArrayList.

ناتوانیت: بە Arrays.copyOf(a, 6) کۆپیی بکە بۆ درێژتر، یان ArrayList بەکار بهێنە.

What is the default value of a String[] element?نرخی بنەڕەتیی دانەیەکی String[] چییە؟

null: an empty slot. Calling a method on it throws NullPointerException.

null: شوێنی چۆڵ. بانگکردنی لەسەری NullPointerException فڕێ دەدات.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

ArrayList and Wrapper ClassesArrayList و کلاسە پێچەرەوەکان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.