DifferenceModerate2 marks
State the difference between length and length() in Java.
Topic: length and length()
Previous-year question practice database
Answer
Exam answer
The difference is shown in the table.
Explanation
This is a favourite two-mark question and the answer must make three contrasts: variable versus method, array versus String, and brackets versus no brackets. Remember the trap in array-of-String questions: name.length is the number of words in the array, while name[0].length() is the number of characters in the first word. Writing a.length() or s.length would both fail to compile.
Comparison
| length | length() |
|---|---|
| A variable (data member) of an array, written WITHOUT brackets. | A method of the String class, written WITH brackets. |
| Gives the number of elements in the array, e.g. a.length for int a[] = {1,2,3} is 3. | Gives the number of characters in the string, e.g. "Java".length() is 4. |
More from String Manipulation
To extract the word NOW from the word "ACKNOWLEDGEMENT", the Java statement "ACKNOWLEDGEMENT".substring(3, ____) is used. Choose the correct number to fill in the blank.2026String a[] = {"Atasi", "Aditi", "Anant", "Amit", "Ahana"};
System.out.println(a[1].charAt(1) + "*" + a[2].charAt(2));
The output of the above statement is:2026Which of the following String methods returns a negative value?2026Assertion (A): The substring() method modifies the original String.
Reason (R): The substring() method can extract part of a String starting from a specific index.2026Give the output of the following program segment:
String S = "GRACIOUS".substring(4);
System.out.println(S);
System.out.println("GLAMOROUS".endsWith(S));2026Name the following:
(a) The return data type of the method equals().
(b) The String method which has no parameter and returns a String.2026