Reputation: 43
I want to store the newline character in a char variable in Java using the following line:
char newline = "/n";
My compiler returns the following:
error: incompatible data types: String cannot be converted to char
how can I fix or work around this issue?
Upvotes: 0
Views: 10484
Reputation: 88796
Use single quotes. i.e.
char newline = '\n';
Having said that, Java has a system property for storing the current OS's line break, System.getProperty("line.separator");
, which returns a String.
Upvotes: 7
Reputation: 302
I would like to add to @Powerlords answer and mention that the line separator can, as of Java SE 7, be retrieved using System.lineSeparator() meaning you could just write:
String lineSep = System.lineSeparator();
Keep in mind that the String
class does not inherently exist as a primitive in Java in contrast to char
as it merely is a class of the standard Java libraries.
This solution is the best for maintaining consistency across Operating Systems as not all OS hold a line separator in a single byte slot (char
variable).
Upvotes: 0
Reputation: 2802
As per Oracle Java doc.
Literals of types char and String may contain any Unicode (UTF-16) characters. Always use 'single quotes' for char literals and "double quotes" for String literals.
The escape sequences for char and string are as follows:
\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash)
.
Therefore, if newline is of datatype char then use char newline = '\n'
Else if newline is of datatype String then use String newline = "\n"
Upvotes: 0
Reputation:
I think you're using the incorrect escape character. Please replace it like
String s = "hello "+"\n";
please try and let me know if it helps.
Upvotes: 0
Reputation: 3433
You asked for a String
to be assigned to a char
. That will never work. String
literals are delineated with the double-quote character, "
. Character literals are delineated with the single-quote character, '
. In addition, you specified two characters in your string, not one. '/'
is one character, and 'n'
is another. If you are trying to specify an escape sequence
http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6
then you need to use the backslash character, not the forward slash: '\n'
.
Upvotes: 2