Why does my Java output string end with the % character at the end?

Viewed 461

The version of Java I'm using with Linux is:

  • openjdk version "16.0.2" 2021-07-20
  • OpenJDK Runtime Environment (build 16.0.2+7)
  • OpenJDK 64-Bit Server VM (build 16.0.2+7, mixed mode)

This is the code I used to compile from the Head-First Java book:

public class DooBee {
public static void main(String[] args) {    
  int x = 1;
  while (x < 3) {
    System.out.print("Doo");
    System.out.print("Bee");
    x = x + 1;
  }
    if( x == 3) {
        System.out.print("Do");
    }
}

}

I compiled it as such:

javac DooBee.java

java DooBee

This is the output:

DooBeeDooBeeDo% 

Why is that special character(%) present at the end of the string and how do I write my code to get rid of it?

2 Answers

I don't think the % comes from your java program, but from your shell. The last output from your program is a print() rather than a println(). This will result in the output ending without a line break. The shell you are running will come back in the middle of an existing line. If it uses a % for a prompt, then that's why.
Change the last print to println and you are hopefully good. Try running it in an IDE or a different shell to make sure. Or perhaps change the prompt, just as a debugging measure?

Related