0

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

1
  • Even with a reference type this could result in two different prints. When you assign a new value to a, the value of c wouldn't be changed even with reference types. On the other hand, if you mutated the object a refers to, the object c refers to would be changed as well because they'd be the same object. Commented Dec 7, 2013 at 11:54

1 Answer 1

3

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"?

Sign up to request clarification or add additional context in comments.

7 Comments

the reference is passed by value I meant like this.
@seenome, primitive types (such as int) are value types, you can't have references to them in Java. You can only have references to objects. Suresh Atta is correct.
"Java is always pass by value.", I think that statement is misleading. Java is pass by value, including value of reference, and objects are passed by reference value. Leaving that 2nd bit out leaves reader wondering, how objects can be passed by value...
@hyde Makes sense to me. Edited little bit.
@hyde I agree wholeheartedly. Java passes primitives by value and objects by reference. I don't know why people insist on confusing the issue with that "always" statement; perhaps they think, mistakenly, that the simple misleading statement will make things easier to understand.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.