In this code we have an int where we initialized with a value. Now we making this reference to another variable and assign a new value. But this should be reflected in other variable. But it does not. How this java reference is passed by value. Strings are immutable but how this happens in integer
public class Confusedwithintegerandstrings
{
public static void main(String[] args)
{
int a=10;
int c=a;
System.out.println(c);
a=20;
System.out.println(a);
System.out.println(c);
}
}
this is O/P
10
20
10
Actually your title and question mismatched.
Java is always pass by value. This is a correct statement for primitives. The confusion comes here for Object.
Consider this example (Objects)
Here while assigning the reference
someOtherObject
is assigned tosomeObject
and the value assigned is the reference.since
a
andc
is a primitive and not an Object, so there in no matter of reference.When you do this
Only Objects have references. Primitives are not Objects.
Might be helpful :Is Java "pass-by-reference" or "pass-by-value"?