0

Java SE 8 Oracle Certified Associate 1Z0-808 - #11

1. Câu hỏi

2. Phân tích

Đây là 1 câu hỏi cần kiến thức cơ bản của String (immutable). Xem docs

Trong ví dụ này.

  • Line 9: Khởi tạo 1 biến String
String s = new String("Hello");
  • Line 11: Lưu s vào phần tử đầu của ArrayList
list.add(s);
  • Line 12: Tạo 1 phần tử mới, lưu tiếp vào ArrayList
list.add(new String("Hello"));
  • Line 13: Lưu s vào phần tử thứ 3 của ArrayList
list.add(s);

**Important: **

  • Thay thế giá giá trị l -> L see docs
s.replace("l", "L");
public String replace(CharSequence target,
                      CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
Parameters:
target - The sequence of char values to be replaced
replacement - The replacement sequence of char values
Returns:
The resulting string

String là một immutable class. Vậy immutable class là gì ? Immutable class là là một lớp bất biến, các thuộc tính của nó không bao giờ bị thay đổi và chỉ có thể thiết lập lúc khởi tạo.

Khi đó s.replace("l", "L"); sẽ tạo ra 1 String mới HeLLo nhưng giá trị của s vẫn là "Hello" [s --> "Hello"]. Do vậy [Hello, Hello, Hello] sẽ được in ra

Đáp án: image.png

3. Kết luận

Bạn có thể gõ code vào IDE để chạy lại và kiểm tra Source cho câu hỏi


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí