Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
Now Reading
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
One of the center ideas of writing computer programs is passing values to strategies and capabilities. Passing values in Java might be finished in one of two ways: by value or by reference. It's fundamental to grasp the distinctions between these two methods to compose successful and blunder-free code. In this post, we will examine pass by value and call by reference in Java, using examples, screenshots, and graphics to aid comprehension.
Pass by value and call by reference are different strategies for passing arguments to methods. A reference to the original variable is supplied during a call by reference, but during a pass by value, a copy of the value is sent to the function. By default, Java utilizes a pass by value, which implies that the method receives a copy of the data.
We should begin by looking at an illustration of pass by value in Java. Consider about the accompanying code scrap:
java
public class PassByValueExample {
public static void main(String[] args) {
int number = 10;
System.out.println("Before calling the method: " number);
increment(number);
System.out.println("After calling the method: " number);
}
public static void increment(int num) {
num ;
System.out.println("Inside the method: " num);
}
}
In the above example, the increment method adds one to the value of the integer input num. The output is as follows when the increment method is used with the number variable as an argument:
SQL
Before calling method: 10
Inside the method: 11
After calling method: 10
We can observe from the result that the method call has not affected the number's value. This exemplifies Java's usage of pass by value, which involves passing the method a copy of the value.
Pass by value alludes to the most common way of reordering the contention's worth to the technique. The technique's underlying variable is unaffected by any progressions made to the contention. Let's examine another example to illustrate pass by value in Java:
java
public class PassByValueExample {
public static void main(String[] args) {
int number = 10;
System.out.println("Before calling the method: " number);
changeValue(number);
System.out.println("After calling the method: " number);
}
public static void changeValue(int num) {
num = 20;
System.out.println("Inside the method: " num);
}
}
In this outline, the function changeValue acknowledges the number boundary num and gives it another worth. The result of running the code is as per the following:
SQL
Before calling method: 10
Inside the method: 20
After calling method: 10
Once again, we can see that the original variable number remains unchanged after the method call. This behavior confirms that Java uses pass by value.
As opposed to a few other programming languages, for example, C, Java doesn't unequivocally give pass by references. At the point when a technique utilizes pass by reference, it gets a reference to the first factor, empowering changes performed inside the strategy to affect the first factor. Java, however, treats references another way.
Java manages references through pass by value despite the fact that it doesn't unequivocally permit pass by reference. This infers that an item reference is duplicated and provided as a parameter at whatever point an object reference is passed to a technique. Thus, changes made to the reference inside a technique affect the first reference.
Think about the following instance:
java
public class PassByValueExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Before calling the method: " sb);
appendText(sb);
System.out.println("After calling the method: " sb);
}
public static void appendText(StringBuilder text) {
text.append(" World!");
System.out.println("Inside the method: " text);
}
}
The function appendText in this example appends " World!" to a StringBuilder object that it receives as an argument. Running this code produces the following results:
SQL
Before calling the method: Hello
Inside the method: Hello World!
After calling the method: Hello World!
The result demonstrates how the appendText method's modifications to the text reference have an impact on the original object. It's crucial to remember that the reference was supplied by value, though.
Pass by value is simple to use when working with primitive data types in Java, such as int, float, or boolean. The primitive variable's value is copied and sent to the method. The method's initial variable is unaffected by any changes made to the argument.
Let's consider an example with primitive data types:
java
public class PassByValueExample {
public static void main(String[] args) {
int num = 5;
System.out.println("Before calling the method: " num);
multiplyByTwo(num);
System.out.println("After calling the method: " num);
}
public static void multiplyByTwo(int number) {
number *= 2;
System.out.println("Inside the method: " number);
}
}
The output of running this code is as follows:
SQL
Before calling method: 5
Inside the method: 10
After calling method: 5
As expected, the original variable num remains unchanged after the method call.
To further illustrate pass by value with primitive types, let's examine another example:
java
public class PassByValueExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Before calling the method: a = " a ", b = " b);
swap(a, b);
System.out.println("After calling the method: a = " a ", b = " b);
}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
System.out.println("Inside the method: x = " x ", y = " y);
}
}
The output of running this code is as follows:
less
Before calling the method: a = 10, b = 20
Inside the method: x = 20, y = 10
After calling the method: a = 10, b = 20
Again, we can observe that the original variables a and b remain unchanged after the method call. This demonstrates that Java uses pass by value even with primitive types.
When it comes to objects in Java, pass by value works slightly differently. A duplicate of the item reference is provided to the technique instead of the total item itself. This suggests that changes to the item's properties finished inside the technique will affect the first article.
java
public class PassByValueExample {
public static void main(String[] args) {
Person person = new Person("John");
System.out.println("Before calling the method: " person.getName());
changeName(person);
System.out.println("After calling the method: " person.getName());
}
public static void changeName(Person p) {
p.setName("Jane");
System.out.println("Inside the method: " p.getName());
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In this illustration, a Person class with a name attribute is present. A Person object is sent to the changeName function, which changes the name to "Jane." Running this code produces the following results:
SQL
Before calling the method: John
Inside the method: Jane
After calling the method: Jane
As we can see, the changes made to the name property within the change name method affect the original Person object.
While relegating another object reference inside the technique affects the first reference, changes to the item's properties are reflected in the first object.
Think about the following instance:
java
public class PassByValueExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Before calling the method: " sb);
assignNewObject(sb);
System.out.println("After calling the method: " sb);
}
public static void assignNewObject(StringBuilder text) {
text = new StringBuilder("Hi");
System.out.println("Inside the method: " text);
}
}
The output of running this code is as follows:
SQL
Before calling the method: Hello
Inside the method: Hi
After calling the method: Hello
From the output, we can see that although the text reference within the assignNewObject method points to a new StringBuilder object, the original reference sb remains unchanged.
Understanding pass by value and call by reference in Java is crucial for writing effective and reliable code. Copy values are sent to methods by default in Java's pass by value technique. Although Java does not natively enable pass by references, it uses pass by values to manage object references. While assigning a new object reference has no effect on the original reference, changes made to an object's properties within a method do.
By grasping the concepts of pass by value and call by reference, developers can design their code more accurately and avoid potential pitfalls.
1: Can Java pass variables by reference?
A: No, Java does not support pass by reference directly. It uses pass by value, even when dealing with objects. However, changes made to object properties within a method will affect the original object.
2: Why does Java use pass by value?
A: Java uses pass by value to ensure predictable behavior and avoid unintended side effects. By passing copies of values to methods, it maintains encapsulation and helps prevent modifications to variables outside the intended scope.
3: Can I modify an object passed to a method in Java?
A: Yes, you can modify an object's properties within a method in Java. However, assigning a new object reference within the method does not affect the original reference.
4: What are the benefits of pass by value in Java?
A: Pass by value promotes encapsulation, prevents unintended modifications to variables, and improves code clarity and predictability. It ensures that modifications made within a method do not affect the original variables outside the method's scope.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...