Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the actual value of "line.separator"?

Tags:

java

string

char

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?

like image 473
DnR Avatar asked Dec 09 '22 09:12

DnR


2 Answers

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

like image 186
Baby Avatar answered Jan 01 '23 06:01

Baby


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'
like image 44
Abimaran Kugathasan Avatar answered Jan 01 '23 06:01

Abimaran Kugathasan