+ 2

How to know if the first letter of a String is alphabetically greater than the first letter of another String?

Hello everyone, Hope you are having a great day so far! I'm fairly new to java and I received an exercise to compare the first characters of two Strings and print Yes if the first character of the first string is alphabetically greater than the second string and No otherwise Eg. (hello, java). this would give me No because h is not alphabetically greater than j. I know that there is some method out there that can assist me with this but I can't seem to find one. All answers are much appreciated!

16th Feb 2019, 9:45 PM
Leo Hunter
Leo Hunter - avatar
4 Antworten
+ 3
If your first string is in variable named first and second string is in variable named second. You can write this If(first.charAt(0) > second.charAt(0)){ //Do whatever here }
16th Feb 2019, 10:19 PM
Umar Sunusi Maitalata
Umar Sunusi Maitalata - avatar
+ 1
Thank you Umar!
16th Feb 2019, 10:21 PM
Leo Hunter
Leo Hunter - avatar
+ 1
Leo Hunter But you have to be careful: first.charAt (0) > second.charAt (0) means not that you compare the letters itself, you compare the ascii values of these letters. A > b --> true (65 < 98) a < B --> false (97 > 66) If you have capital letters in your String, you can use this method: YourString.toLowerCase ();
16th Feb 2019, 11:08 PM
Denise Roßberg
Denise Roßberg - avatar
0
did old java not have an easier way? char character = 'a'; int ascii = (int) character; get the specific Character from the String first and then cast it. char character = name.charAt(0); // This gives the character 'a' int ascii = (int) character; // ascii is now 97. do the next then compare well that how we used to do it lol
16th Feb 2019, 11:40 PM
peter
peter - avatar