Java program to check order of characters in string

To check order of characters in string in Java, the code is as follows −


 Live Demo

public class Demo{
   static boolean alphabetical_order(String my_str){
      int str_len = my_str.length();
      for (int i = 1; i < str_len; i++){
         if (my_str.charAt(i) < my_str.charAt(i - 1)){
            return false;
      return true;
   static public void main(String[] args{
      String my_str = "abcmnqxz";
      if (alphabetical_order(my_str)){
         System.out.println("The letters are in alphabetical order.");
      } else{
         System.out.println("The letters are not in alphabetical order.");


The letters are in alphabetical order.

A class named Demo contains a function named ‘alphabetical_order’. This function iterates over the string and checks if the value of character at the first place and the previous place are same. If yes, it returns true, indicating the alphabets are in order, otherwise returns false, indicating the alphabets are not in order. In the main function, the string is defined and the function is called on this string. Relevant message is displayed on the console.

Updated on: 08-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started