1

I know Object class is the root class of all classes in Java, I wanted to know the relation between int[] and Object class.

Arrays.stream() can accept arg of int[], long[], double[] and Object[].

As I came across a code which gives int[] to a generic type (Stream<int[]>), This code works, we provide only class to Stream.

Also the output to this code was hex code rather than integers

        int arr[] = { 1, 2, 3, 4, 5 }; 

        // --------- Using Arrays.stream() --------- 

        // to convert int array into Stream 
        IntStream intStream = Arrays.stream(arr); 

        // Displaying elements in Stream 
        intStream.forEach(str -> System.out.print(str + " ")); // {1,2,3,4,5]

        // --------- Using Stream.of() --------- 

        // to convert int array into Stream 
        Stream<int[]> stream = Stream.of(arr); 

        // Displaying elements in Stream 
        stream.forEach(str -> System.out.print(str + " ")); // I@asdf
5
  • What's your question? What's the error you want to fix? what's the expected output? Commented Mar 8, 2021 at 6:07
  • 2
    answer to title can be found in JLS 10. Arrays. First sentence: "In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array." Commented Mar 8, 2021 at 6:52
  • @user15244370 Thank You so much, was searching for this Commented Mar 8, 2021 at 11:20
  • 1
    just for fun System.out.println(arr.getClass()) or Object obj = arr; int[] casted = (int[]) obj; Commented Mar 8, 2021 at 11:30
  • syso(arr.getClass()) // "[I" Makes sense toString() is Classname@hexcode Commented Mar 8, 2021 at 11:38

1 Answer 1

3

In intStream.forEach(str -> System.out.print(str + " ")); each str would be of type int. But in stream.forEach(str -> System.out.print(str + " ")); each str is of type int[]. Hence the difference in output.

To print a primitive array you need to use Arrays.toString like :

stream.forEach(str -> System.out.print(Arrays.toString(str) + "\n"));
Sign up to request clarification or add additional context in comments.

1 Comment

This answered cleared things as well stackoverflow.com/questions/21949570/… This cleared the concept

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.