Java passes parameters by value or by reference? Analyzing a popular myth
Hi everyone! I'm a beginner Java developer, and I'm constantly confused by one fundamental question. Many people say that Java passes objects by reference and primitives by value. But I've read that actually Java always passes parameters by value. I tried writing a small piece of code to figure it out, but it only confused me more.\n\nHere's an example:\n\n```java\npublic class Main {\n public static void main(String[] args) {\n int x = 5;\n changePrimitive(x);\n System.out.println("After changePrimitive: " + x); // Output: 5\n\n StringBuilder sb = new StringBuilder("Hello");\n changeObject(sb);\n System.out.println("After changeObject: " + sb); // Output: Hello World\n }\n\n public static void changePrimitive(int value) {\n value = 10;\
No answers yet.
Log in to leave an answer