Does System.out.println move the cursor to the next line after printing in some cases?

import java.util.Scanner;

public class CanYouReadThis {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        String input = scn.next();
        int i = 0;
        while ( input.length() > i && input.charAt(i) < 'a'  )
        {
            System.out.println(input.charAt(i));
            i++;
            while(input.length() > i && input.charAt(i)> 'Z' )
            {
                System.out.print(input.charAt(i));
                i++;
            }
            
        }
    }
}

Input : IAmACompetitiveProgrammer
Excepted Ouput :
I
Am
A
Competitive
Programmer

My Output :
I
A
mA
C
ompetitiveP
rogrammer

import java.util.Scanner;

public class CanYouReadThis {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        String input = scn.next();
        int i = 0;
        while ( input.length() > i && input.charAt(i) < 'a'  )
        {
            System.out.print(input.charAt(i)); // removed ln
            i++;
            while(input.length() > i && input.charAt(i)> 'Z' )
            {
                System.out.print(input.charAt(i));
                i++;
            }
            System.out.println(); // Added this line
        }
    }
}

I made these changes to my code and it works fine . But isn't the logic of both programs the same. What am i missing here ? Please help me out .


Solution 1:

Println renders and outputs its argument followed by whatever is configured as the JVM's end-of-line character sequence1.

The normal behavior and expected behavior2 of a console program when it gets that sequence is to move to the start of the next line.

In the light of this, two versions of your program are clearly different. The first version outputs a line separator after the first character, and not the last one. The second version outputs a line separator after the last character of each word but not the first one.

The output you are getting reflects that difference.


"Shouldn't it just print on the new line and leave the cursor there?"

Well, that depends on the console program's implementation. But on platforms where "\n" is the line separator, the default behavior of a console program should be to go to the start of the next line. Whether that is correct in terms of the historical meaning of the ASCII NL characters as implemented by 1960's era teleprinters, etc is moot.

The fact that Linux and Windows console programs interpret these things is also a historical anomaly. But you can get yourself into problems if you hard-wire "\n" or "\r\n" into your output. That is why println is provided, and why Formatter.format (etc) support %n as meaning line separator.


1 - On Windows it is "\r\n", and on Linux it is "\n".
2 - However, the actual behavior depends on the implementation of the console. That is outside of Java's control.