You are not connected. Please login or register

View previous topic View next topic Go down  Message [Page 1 of 1]

1 {Java} Comparing using the compareTo Method on Mon Feb 07, 2011 6:10 am

des

avatar
Achiever
Loading
This Java script isn't mine, but enjoy the script:

Java man who did this wrote:The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print “name2 follows name1” In the first case and “name1 follows name3” in the second case.
Code:
public class StringComparision3 {

   public static void main(String[] args) {
      String name1 = "bob";
      String name2 = new String("cob");
      String name3 = "Bob";
      // 1st case
      if (name1.compareTo(name2) == 0) {
         System.out.println("The strings are equal.");
      } else if (name1.compareTo(name2) < 0) {
         System.out.println("name2 follows name1");
      } else {
         System.out.println("name1 follows name2");
      }
      // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case
      if (name1.compareTo(name3) == 0) {
         System.out.println("The strings are equal.");
      } else if (name1.compareTo(name3) < 0) {
         System.out.println("name3 follows name1");
      } else {
         System.out.println("name1 follows name3");
      }
   }
}

View previous topic View next topic Back to top  Message [Page 1 of 1]

Related topics

Permissions in this forum:
You cannot reply to topics in this forum