I always think that line.separator do the same things as \n, and yes it is. but I noticed that both values are actually not the same(perhaps not even close?) when I test this code:
String str1 = System.getProperty("line.separator");
String str2 = "\n";
System.out.println(str1.equals(str2)); // output:false (as expected)
Then I checked the length of both:
System.out.println(str1.length()); //output: 2
System.out.println(str2.length()); //output: 1
wondering why str1.length() is 2, I tried this:
System.out.println("**"+str1.charAt(0)+"**");
output:
**
System.out.println("##"+str1.charAt(1)+"##");
output:
##
##
So I noticed that the actual newline character in line.separator is the second character. Then what is the value in first index, as when it supposed to print **** (atleast), its print ** instead?
Depends on your OS.
For windows, the actual value of line.separator is \r\n
From your code System.out.println(str1.length()); //output: 2, I believe you are on Windows's OS (Other OS will give output: 1)
It explain why got this output:
System.out.println("**"+str1.charAt(0)+"**");
output:
**
\r is a carriage return, after you print ** the pointer is returned back to the initial point, and print the second **, which rewrite the first **. Finally, you got only ** as output
And for the second one:
System.out.println("##"+str1.charAt(1)+"##");
output:
##
##
you got such output because str1.charAt(1) is actually \n
It's depends on the platform/OS, in Linux it's \n, in Windows, it's \r\n
Windows: '\r\n'
Mac (OS 9-): '\r'
Mac (OS 10+): '\n'
Unix/Linux: '\n'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With