Search code examples
javaarraysstringconcatenation

Why to add a Empty String while adding an string with int?


In the below when I wasn't adding the ""(Empty String), the output was in int, which is pretty abnormal because adding a String with an int always gives a string. But as soon as I added the Empty String thing, the code seemed to work fine. In both the cases,I was adding a string from the string array that I created earlier in the code.

import java.io.*;

public class TooLong{
    public static void main(String[] args)  throws IOException{
        InputStreamReader n = new InputStreamReader(System.in);
        BufferedReader input = new BufferedReader(n);
        byte i ;
        i=Byte.parseByte(input.readLine());
        String origWords[] = new String[i];
        for (int j=0;j<i;j++)   origWords[j]= input.readLine();
        for (int j=0;j<i;j++){

            int charLength = origWords[j].length(); 
            if (charLength < 11)    System.out.println(origWords[j]);
            else System.out.println(origWords[j].charAt(0) +""+ (charLength-2) + origWords[j].charAt(charLength-1) );
        }
    }
}

Solution

  • I assume, you are trying to achieve “internationalization ⇒ i18n”

    That is because String.charAt(int) returns char. Which will be treated as numerical when using +. By using + with the empty String you force the compiler to convert everything to String

    You can use String.substring(0,1) instead of the first charAt to force type String conversion