ICSE Class 10 Computer Applications Question 8 of 46

String Handling — Question 8

Back to all questions
8
Question

Question 2(vii)

Mention the purpose and syntax of compareTo() method.

Answer

The compareTo() method compares two strings lexicographically, and returns a value based on the following logic:

  1. if string1 > string2 the result will be a positive integer, i.e., result > 0
  2. if string1 < string2 the result will be a negative integer, i.e., result < 0
  3. if string1 = string2 the result will be 0, i.e., result = 0

Syntax:
string1.compareTo(string2)