Page 305 - ComputerScience_Class_11
P. 305
if str1<str2 : it returns a negative value
if str1==str2 : it returns 0
The syntax is:
int <variable> = String_datatype_Variable.compareTo(String str);
Let us see the below examples:
Program 16 Write a program to compare two strings and print the result using compareTo method.
1 class compare
2 {
3 public static void main(String[] args)
4 {
5 String wd1= "And";
6 String wd2= "and";
7 int value= wd1.compareTo(wd2);
8 System.out.println("Value: "+ value);
9 }
10 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
Value: -32
i.e., the difference between the ASCII codes of A and a = 65-97=-32, the comparison
is between A and a, as the first characters of both the strings are equal.
Program 17 Write a program to compare two strings and print the result using the compareTo method.
1 class compare
2 {
3 public static void main(String[] args)
4 {
5 String str1= "INDIAN";
6 String str2= "INDIA";
7 int value= str1.compareTo(str2);
8 System.out.println("Value: "+ value);
9 }
10 }
Strings 303

