Concept
How does Java handle passing primitive and object types to methods?
ComputerScienceOne / Passing By Reference
"Java does not allow you the ability to specify if a variable is passed by reference or by value. Instead, all primitive types are passed by value while all object types are passed by reference. Moreover, most of the built-in types such as Integer and String are immutable, even though they are passed by reference, any method that receives them cannot change them. Only if the passed object is mutable can the method make changes to it (by invoking its methods). As an example, consider the following piece of code. The StringBuilder class is a mutable string object. You can change the string contents stored in a StringBuilder by calling one of its many methods such as append() , which will add whatever string you give it to the end. In the main method, we create two objects, a String and a StringBuilder and pass it to a method that makes changes to both by appending \" world!\" to them. Understand what happens here though. The first line in change() actually creates a new string and then changes what the parameter variable s references. The reference to the original string, \"Hello\" is lost and replaced with the new string. In contrast, the StringBuilder instance is actually changed via its append() method but is still the same object.\n\n1 public class Mutability {\n\n2\n\n3 public static void change(String s, StringBuilder sb) {\n\n4 s = s + \" world!\";\n\n5 sb.append(\" world!\");\n\n6\n\n7 System.out.println(\"change: s = \" + s);\n\n8 System.out.println(\"change: sb = \" + sb);\n\n9 }\n\n10\n\n11 public static void main(String args[]) {\n\n12 String a = \"Hello\";\n\n13 StringBuilder b = new StringBuilder(\"Hello\");\n\n14\n\n15 System.out.println(\"main: s = \" + a);"
Related Ideas
- How are arrays passed to methods in Java?ComputerScienceOne · Multidimensional Arrays
- How can arrays be passed to and returned from methods in Java?ComputerScienceOne · Dynamic Memory
- How are String variables declared and reassigned in Java?ComputerScienceOne · Basics
- How does Java make working with strings easier?ComputerScienceOne · Basics
- How can pointers be used to pass variables by reference?ComputerScienceOne · Passing By Reference
- How does PHP pass arguments by reference?ComputerScienceOne · Passing By Reference
- How does Java handle arithmetic with wrapper classes?ComputerScienceOne · Operators
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods