public class CompareToExample {
public static void main(String args[]) {
String str1 = "String method tutorial";
String str2 = "compareTo method example";
String str3 = "String method tutorial";
int var1 = str1.compareTo( str2 );
System.out.println("str1 & str2 comparison: "+var1);
int var2 = str1.compareTo( str3 );
System.out.println("str1 & str3 comparison: "+var2);
int var3 = str2.compareTo("compareTo method example");
System.out.println("str2 & string argument comparison: "+var3);
}
}
Output:
str1 & str2 comparison: -16
str1 & str3 comparison: 0
str2 & string argument comparison: 0
iii) indexOf( )
The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.
public class IndexOfExample3 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing substring and index
int index = s1.indexOf("method", 10); //Returns the index of this substring
System.out.println("index of substring "+index);
index = s1.indexOf("method", 20); // It returns -1 if substring does not found
System.out.println("index of substring "+index);