Single characters are represented using a char type. A char literal must be enclosed by single quotes (‘ ‘) whilst a String type (which is not a primitive class but is used to represent a collection of characters) us double quotes to delimit (“ “). A sequence of character data is called a string and is implemented in the Java environment by the String class (a member of the java.lang package). You will need to use character strings in most of your programs, if only to output error messages. Strings You have already been making extensive use of string constants for output. Every time you used the println() method, you used a string constant as the argument. A string constant is a sequence of characters between double quotes:
String myString = “This is a string!”;
Some characters can’t be entered explicitly from the keyboard to be included in a string constant. For example you can’t include a double quote because it is used to indicate where a string constant begins and ends. You can’t also use a new line character by pressing Enter key, as this will move the cursor to a new line. For this reason you must use an escape sequence to specify those characters. Shown below is a list of escape characters that you can use to define control characters:
\’ Single quote \t Tab
\” Double quote \n New line
\r Carriage return \\ Backslash
\u???? Replace Unicode with Hexadecimal
If for example, you want to print the following string on the screen,
“He’s brilliant in Java”
He can just about do anything.
then you can write it as follows:
“\”He\’s brilliant in Java\”\n\tHe can just about do anything.”
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment