Wrong ans in second case of String Sort

I can’t figure out what I am doing wrng
my code is
import java.util.*;

public class b {
void sort(String a[])
{
int n=a.length;
for(int j=0;j<n;j++){
for(int i=0;i<n-1-j;i++)
{
if((int)(a[i].charAt(0))>(int)(a[i+1].charAt(0))){
String s=a[i];
a[i]=a[i+1];
a[i+1]=s;}
}

        }
    for(int i=0;i<n-1;i++) {
        if ((int) (a[i].charAt(0)) == (int) (a[i + 1].charAt(0))) {
            int l = a[i].length();
            int l1 = a[i + 1].length();
            if (l < l1) {
                if (a[i].equals(a[i + 1].substring(0, l))) {
                    String s = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = s;
                }
            }
        }
    }
}

public static void main(String args[]) {
    Scanner obj=new Scanner(System.in);
    int n=obj.nextInt();
    b m=new b();
    String a[]=new String[n];
    for(int i=0;i<n;i++)
    {
        a[i]=obj.next();
    }
    m.sort(a);
    for(int i=0;i<n;i++)
    {
        System.out.println(a[i]);
    }
}

}

Hi @Anupreet9

when sorting the strings you not only have to check charAt(0) of all the strings instead you also have to check for lengths.Try again by using compareTo function.

Thank you…Using compareTo function corrected my code.