SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Strings And Vectors
Exercise:
Self-test Exercises
Question:6 | ISBN:9780321531346 | Edition: 7

Question

How many characters are in each of the following character and string

constants?

a. '\n'

b. 'n'

c. "Mary"

d. "M"

e. "Mary\n"

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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.

 

0 0

Discussions

Post the discussion to improve the above solution.