Is Java Pass by Value?

"Is Java pass by value or pass by reference?" is one of the most asked Java interview questions. This quiz answers it with real programs: you will see when a method's changes reach the caller and when they silently disappear.

Khó 10 câu hỏi ~8 phút Đạt từ 80% Java 17

Chọn chế độ

Bạn đang chơi với tư cách khách: đăng nhập để lưu XP và streak.

Câu hỏi mẫu

Câu 1/10

What does this print?

public class Main {
    static void swap(String a, String b) {
        String temp = a;
        a = b;
        b = temp;
    }

    public static void main(String[] args) {
        String x = "left";
        String y = "right";
        swap(x, y);
        System.out.println(x + " " + y);
    }
}
Xem đáp án

B. left right a and b are copies of the references in x and y. Swapping the copies inside the method does not touch the caller's variables, which is why a classic swap method is impossible in Java.

Quiz này có gì

  • Java always passes a copy of the value
  • For objects, the copied value is the reference
  • Mutating an object vs reassigning a parameter
  • Why a swap method does not work
  • Immutable types like String and Integer as parameters

Câu hỏi thường gặp

Có cần tài khoản không?

Không. Ai cũng chơi được. Đăng nhập để lưu XP, streak, badge và lịch sử.

Có làm lại được không?

Được. Điểm cao nhất của bạn được giữ lại, câu hỏi và đáp án được xáo trộn mỗi lần.