0

I am new to Java.

Coming from Python, I find it way more tedious to deal with arrays in Java than Python.
Specifically, to access arrays' positions. This is the Python code I want to translate to Java:

# Access first 3 elements

arr = [1, 2, 3, 4, 5]
arr[:3]

output: [1, 2, 3]

But in Java, there is no "colon", and the shortest way I have found to get the first three elements is throuh a loop.

Is there a package or a non-loop way to do this?

Sergi
  • 11
  • 1
  • 7
  • Yes, exactly! But, when I try to print it out to the console... it returns "[I@e9e54c2" instead. How's that? – Sergi Aug 31 '21 at 13:55
  • 1
    Something like `System.out.println(java.util.Arrays.toString(subarray));` should do the trick. – Federico klez Culloca Aug 31 '21 at 13:56
  • Just note that arrays are objects to and thus if you call `System.out.println(array)` it will call `toString()` on the array which returns the result. `Arrays.toString(array)` basically iterates over the array, calls `toString()` on each element and returns a list of those strings which are separated by a comma. – Thomas Aug 31 '21 at 13:58
  • You can do it in a functional style like that String[] a = {"str1","str2"}; Arrays.stream(a).limit(3).forEach(System.out::println); – Denis Rodin Aug 31 '21 at 15:04

0 Answers0