How many characters are in each of the following character and string
constants?
a. '\n'
b. 'n'
c. "Mary"
d. "M"
e. "Mary\n"
a)
'\n'
: This is a character constant representing a newline character. It contains one character. In each case, the length()
method is used to determine the number of characters in the constant.
System.out.println("a. Length: " + String.valueOf('\n').length());
The output of the '\n' length is 1.
b)
'n'
: This is a character constant representing the letter 'n'. It contains one character.
System.out.println("b. Length: " + String.valueOf('n').length());
The output of the 'n' length is 1.
c)
. "Mary"
: This is a string constant containing the characters 'M', 'a', 'r', and 'y'. It contains four characters.
System.out.println("c. Length: " + "Mary".length());
The output of the "Mary" length is 4.
d)
"M"
: This is a string constant containing the character 'M'. It contains one character.
System.out.println("d. Length: " + "M".length());
The output of the "M" length is 1.
e)
"Mary\n"
: This is a string constant containing the characters 'M', 'a', 'r', 'y', and a newline character. It contains five characters.
System.out.println("e. Length: " + "Mary\n".length());
The output of the '"Mary\n" length is 5.