-4

Can someone explain this to me as I'm relatively new to Java and coming from objective-c background (difference being, pass by reference instead of pass (reference) by value).

Given that Java is pass by value I shouldn't expect to be able to re-assign variables within a different scope and have those changes persist, right? Thats why objectValue is null. String and int are primitives so thats why they work. But, why does Integer work?

Object objectValue = null;
int intValue;
String stringValue = null;
Integer integerValue = null;

if (true) {
    objectValue = new Aircraft();
    intValue = 1;
    stringValue = "is one";
    integerValue = new Integer(1);
}

// objectValue == null
// intValue == 1
// stringValue == "is one"
// integerValue == 1

4 Answers4

8

You are not using pass by reference or by value. The local variable should be altered in each case.

Pass by value only applies to variables passed as arguments to method calls.

Variables are not passed to nested scopes, there is only one variable for these scopes and changing it alters the original.

The only time variables are copied is for anonymous inner classes and lambdas, however these variables need to be effectively final.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

You are not passing anything to any where in your whole code. You are just reassigning that values to the initially declared variables. That's all.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The "pass reference by value" is referring to method (function) calls. You don't call any methods, so the concept is meaningless.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

You don't pass by value when reaching a scope block. That would be a nightmare. What would you do with if statements and for loops? Everything would break.

You only pass by value in functions, and then you pass references by value.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78