2

I was creating a program that had an array involved and at one point I wanted to print out part of the array. I wanted to know how to print out for example array indexes 2-5.

I tried doing something like this but it didn't work.

String[] testArray = {"a", "b", "c", "d", "e", "f'", "g"};
System.out.println(testArray[2,5]);

but it didn't work. (not that I fully expected it too).

I was just wondering how you would do something like this.

deHaar
  • 17,687
  • 10
  • 38
  • 51
Miqhtie
  • 63
  • 9
  • Further to YCF_L's great answer, if you just wanted to pass a slice of the array around, see this answer which shows you how: https://stackoverflow.com/a/11001772/2357085 – w08r Jan 19 '20 at 15:04

5 Answers5

5

You can use Arrays::copyOfRange, like this :

Arrays.copyOfRange(testArray, 2, 5)

To print the result, you can use :

System.out.println(Arrays.toString(Arrays.copyOfRange(testArray, 2, 5)));

Outputs

[c, d, e]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

You can do it in a loop:

for (int i = 2; i < 6; i++) {
    System.out.println(testArray[i]);
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
0

If you want to print array element from index 2 to index 5:

public void printArrayInIndexRange(String[] array, int startIndex, int endIndex) {
      for(int i = startIndex; i < endIndex && i < array.length; i++) {
          System.out.println(array[i]);
      }       
}

Then simply call the method:

printArrayInIndexRange(testArray, 2, 5);

Note: the condition i < array.length helps to avoid IndexOutOfBoundException.

A. Wolf
  • 1,309
  • 17
  • 39
0

You have 2 options:

1) Using Arrays.copyOfRange() method.

2) If you're using Java8, then you can use streams to do your job as follows:

int[] slice = IntStream.range(2, 5)
                        .map(i -> testArray[i])
                        .toArray(); 
A. Wolf
  • 1,309
  • 17
  • 39
Mohammed Deifallah
  • 1,290
  • 1
  • 10
  • 25
0

You can use System.arraycopy here is java documentation

// copies elements 2 and 5 from sourceArray to targetArray

    System.arraycopy(sourceArray, 2, targetArray, 0, 4);

OR

Wrap your array as a list, and request a sublist of it.

MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(startIndex, endIndex);
Muzzamil
  • 2,823
  • 2
  • 11
  • 23