Monday, September 21, 2009

Java Object Reference Variables

Reference Variable Assignments

Car myRide = new Car();

Makes a reference variable myRide of type Car.
Creates a new Car object on the heap
Assigns the newly created Car object to the reference variable myRide.


Assigning One Object Reference to Another


Object reference variables work exactly like the primitive data types. The contents of a reference variable are a bit pattern, which when assigned to another object reference, it is copied to that reference.

import java.awt.Dimension;

public class ReferenceTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Dimension a = new Dimension(5, 10);
System.out.println(" a.height =" + a.height);
Dimension b = a;
b.height = 30;
System.out.println(" a.height =" + a.height + " after change to b ");
System.out.println(" b.height =" + b.height + " after change to b ");
}
}

a.height = 10

a.height = 30 after change to b

Both the variables, refer to the same instance of the Dimension object.



One exception to the way object references are assigned is String. In Java, String objects are given special treatment. String objects are immutable, you can't change the value of a String object.

class StringTest {

public static void main(String[] args) {

String x = "Java"; // Assign a value to x

String y = x; // Now y and x refer to the same String object

System.out.println("y string = " + y);

x = x + " Bean "; // Now modify the object using the x reference

System.out.println("y string = " + y);

}

}



y string = Java

y string = Java

No comments:

Post a Comment

 

Onion Labs © 2008 ---- Sakshieducation, Onion Labs.