Question

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

Was it helpful?

Solution

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)

someObject = someOtherObject

Here while assigning the reference someOtherObject is assigned to someObject and the value assigned is the reference.

Now we making this reference to another variable and assign a new value.

since a and c is a primitive and not an Object, so there in no matter of reference.

When you do this

 int c=a;  // value of a copied to c

Only Objects have references. Primitives are not Objects.

Might be helpful :Is Java "pass-by-reference" or "pass-by-value"?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top