Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.out.println print a new line while System.out.print prints nothing?

Tags:

java

I am having trouble with split function. I do not know how it works.

Here is my source code:

// Using println to print out the result
String str  = "         Welcome       to    Java     Tutorial     ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
    System.out.println(c);
}

//Using print to  print out the result
String str  = "         Welcome       to    Java     Tutorial     ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
    System.out.print(c);
}

and the results are: Result

The first is the result when using println, the second is the result when using print,

I do not understand why space appears in println, while it does not appear in print. Can anyone explain it for me?

like image 836
Le Quynh Anh Avatar asked Dec 05 '22 14:12

Le Quynh Anh


1 Answers

Since you have many spaces in your string, if you look at the output of split function, the resulted array looks like

[Welcome, , , , , , , to, , , , Java, , , , , Tutorial]

So if you look close they are empty String's "".

When you do a println("") it is printing a line with no string.

However when you do print(""), it is no more visibility of that string and it looks nothing getting printed.

If you want to separate them regardless of spaces between them, split them by white space.

Lastly, trim() won't remove the spaces within the String. It can only trim spaces in the first and last.

like image 107
Suresh Atta Avatar answered May 11 '23 00:05

Suresh Atta