Linkedin Java 認證題庫


Posted by c9103205 on 2021-07-02

class Main {
    public static void main(String[] args){
       String message = "Hello";
       for (int i = 0; i<message.length(); i++){
          System.out.print(message.charAt(i+1));
       }
    }
}
  1. "Hello"
  2. A runtime exception is thrown.
  3. The code does not compile.
  4. "ello"

answer : 2
解析:
這題是個小陷阱,也是新手工程師常犯的錯誤
message.length() == 5
但字串轉成 char 的 index 是從 0開始計算
也就是 "01234"
所以當(i+1)==5的時候,會出現
StringIndexOutOfBoundsException
不可不慎阿~~


#linkedin #java







Related Posts

序列化操作(Gson ObjectMapper)

序列化操作(Gson ObjectMapper)

【單元測試的藝術】Chap 2: 第一個單元測試

【單元測試的藝術】Chap 2: 第一個單元測試

MTR04_0910

MTR04_0910


Comments