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
  • 14,698
  • 10
  • 35
  • 45
Miqhtie
  • 63
  • 6
  • 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]
YCF_L
  • 51,266
  • 13
  • 85
  • 129
1

You can do it in a loop:

for (int i = 2; i < 6; i++) {
    System.out.println(testArray[i]);
}
deHaar
  • 14,698
  • 10
  • 35
  • 45
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,261
  • 16
  • 36
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,261
  • 16
  • 36
Mohammed Deifallah
  • 1,275
  • 1
  • 10
  • 22
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,665
  • 2
  • 8
  • 22