Jump to content


Check out our Community Blogs

wim DC

Member Since 24 May 2009
Offline Last Active Jul 12 2016 10:57 PM
*****

Posts I've Made

In Topic: [Java] Reverse Char Array?

12 July 2016 - 10:57 PM

Anything which is not a primitive (int, boolean, double, ...), eg. Which is a class instance, will behave that way.
Array objects are actually instances of the Array class in Java so they will behave exactly like any other class instance.
 
Whenever an instance of a class is passed as parameter, the instance itself can be modified, and it will modify the source's instance. However the variable can't be reassigned, so it's not strictly pass-by-reference.
 

class Address {
  private String street;
  private String postcode;

  // getter and setter
}

class Test {
  public static void main(String... args) {
    Address address = Address();
    fillAddress(address)
    System.out.println("1: " + address.getStreet() + " " + address.getPostcode());
    setAddress(address)
    System.out.println("2: " + address.getStreet() + " " + address.getPostcode());
  }
  
  public static void fillAddress(Address address) {
    address.setStreet("A");
    address.setPostcode("B");
  }

  public static void setAddress(Address address) {
    address = Address();
    address.setStreet("C");
    address.setPostcode("D");
  }
}

The output of this will be:

1: A B
2: A B

Because in the setAddress() method you set "C" and "D" to a new object. But since the variables themselves are not pass by reference, the new object is lost.

In fillAddress() the parameter variable actually contains the object by reference of the original address.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download