Java, compareTo () usage

1, the string comparison

      1) When two strings if they are identical, returns 0

      2) When two strings, e.g. ccc and cccbbb, cccbbb compared with ccc: 3; returns the length difference of the two strings

      3) When two strings, e.g. ccc ddd than the result of: 1, to return the difference values of the two ascii characters , there is a difference of a value of ascii d and c.

2, Integer comparison:

      1) comparison of two numbers: the same, return 0 ;

      2) a first large number, a return, a first small number, return -1 ;

3, Code Share:

{class CompareToTest public 
    public static void main (String [] args) { 
        // string of the same length 
        String S1 = "ddd"; 
        String S2 = "ccc"; 
        System.out.println ( "ccc ddd than the result of: "+ s1.compareTo (S2)); 
        System.out.println (" ccc ddd than the result is: "+ s2.compareTo (S1)); 
        // ccc ddd than the result is:. 1 
        // ccc ddd ratio of results: -1 

        // string while the length 
        string S3 = "cccbbb"; 
        string S4 = "cccdddd"; 
        System.out.println ( "cccbbb compared CCC:" + s3.compareTo (S2)); 
        the System. out.println ( "ccc compared cccdddd:" + s2.compareTo (s4) );
        // cccbbb compared with ccc: 3 
        Compare // ccc and cccbbb: -3 
        compare // ccc and cccddd: -4 
        String S5 = "A";
        System.out.println ( "a comparison with cccbbb:" + s5.compareTo (S3)); 
        String S6 = "A"; 
        System.out.println ( "a comparison with a:" + s5.compareTo (s6) ) ; 

        Integer I = 1; 
        Integer I2 = 11; 
        System.out.println ( "comparison 1 and 11:" + i.compareTo (I2)); 
        System.out.println ( "comparison 1 and 11:" + i2.compareTo (I)); 

        Integer I3 = 90; 
        System.out.println ( "comparison 1 and 90:" + i3.compareTo (I)); 
        Integer I4 = 90; 
        System.out.println ( "90 compared to 90:" i4.compareTo + (I3)); 
        Integer i5 = 1; 
        System.out.println ( "comparison 1 and 1:" + i5.compareTo (i)) ;

        11 @ 1 and Comparison: -1 
        // 11 and Comparison 1: 1 
        @ 90 and Comparison 1: 1 
        // 90 compared with 90: 0 
        // 1 and Comparison 1: 0








    }
}

result:

ccc ddd than the result is:. 1
ccc ddd than the result is: -1
cccbbb compared ccc:. 3
ccc compared cccdddd: -4
A Comparison and cccbbb: -2
A compared with A: 0
. 1 and Comparison 11: -1
1 compared with 11: 1
90 Comparative 1: 1
90 90 comparison: 0
1 and comparison 1: 0

 

Published 45 original articles · won praise 8 · views 5843

Guess you like

Origin blog.csdn.net/wenyunick/article/details/104327646