1

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) );
        }
    }
}
Satyam Bansal
  • 363
  • 1
  • 4
  • 11
  • 1
    Because `charAt(int index)` > Returns the char value at the specified index. – sleepToken Jan 13 '20 at 14:16
  • Can you show us some examples? I don't think I understand what you want to say. – KunLun Jan 13 '20 at 14:16
  • 1
    `charAt()` return `char` (basically a number) the `+` is define as `number + number`, cause `char` only contains one char, once you introduce `String` (`""`) the `+` became concatenation of strings – shahaf Jan 13 '20 at 14:17

2 Answers2

4

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

Jan
  • 1,042
  • 8
  • 22
  • Got it, one more question on which I am not able to get a short answer is, Scannner or Buffered Reader? – Satyam Bansal Jan 13 '20 at 14:23
  • 2
    :D https://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader. My first google hit on “java Scanner or BufferedReader” – Jan Jan 13 '20 at 14:28
1

The charAt() method of String returns the char. char is one of the primitive data types. char is a textual primitive, however, it also can do arithmetic operations like numerical primitives. The codes below are examples for it:

 `public static void main(String args[]){
            String st = "i am a string";
            char c = st.charAt(0);
            System.out.println(c);
            System.out.println(c+ st.charAt(2));
            System.out.println(c+ "" + st.charAt(2));
        }

`

The result of the above code will be:

 i
202
ia

Hope this example makes it clear.