Search code examples
javaforeachjava-8java-stream

int Array Stream System.out.print method adds % sign at the end while printing Java8


Facing issue while using trying to print primitive type int array elements onto the console using Stream API forEach method using System.out.print method as an extra % sign is being added to the console output.

Please find below my main method -

 public static void main(String[] args) {       
        int[] A = {1, 2, 3, 4, 5, 6, 7, 8};

        Arrays.stream(A).forEach(s -> System.out.print(s));
    }

Output - 12345678%

Expected Output - 12345678

I was wondering why an extra % sign is being added at the end of printing the array. I am using MacOS. Tried both with VSCode and terminal javac and java commands, both giving same issue.

Note: System.out.println works fine without adding any % sign.

Related Post(Without a satisfactory answer) : Remove percent sign after System.out.print();

UPDATE: It turned out to be a zsh issue. I was able to follow the StackExchange post answer and add PROMPT_EOL_MARK='' in my ~/.zshrc file to remove the % sign.


Solution

  • This is how zsh behaves when there is no new line character at the end of your output. You are using print, which unlike println, does not print a trailing new line. See also this post on Unix & Linux Stack Exchange.

    You will see the same behaviour with echo -n (echo, but without a trailing new line):

    sweeper@sweepers-MacBook-Pro ~ % echo -n Foo
    Foo% 
    sweeper@sweepers-MacBook-Pro ~ %
    

    If you use bash, there is no %, but notice that the lack of a new line makes the next prompt stay on the same line as the output.

    bash-3.2$ echo -n Foo
    Foobash-3.2$ 
    

    You can just put another System.out.println() after your code and there will not be a % on zsh.