(char) int
). The compiler will treat a cast object as though its static type is the cast type, but this will only work if the cast type is the same as or a parent of the dynamic type. However, relative to the assigned static type, the cast type could be a child of the static type or a parent of the static type.aByte = 10
is fine even though 10 is an int literal. This is because arithmetic operations (+, *, ...) automatically promote operands (e.g., 'A' + 2
is equivalent to (int)'A' + 2
)aByte = aByte + 1
since operands become an int type which cannot be set equal to a byte type. But += works!int[] arr = new int[5]
, arr
only stores a 64-bit memory address which points to the real object, a 5-length integer array. Again, think back to the arrow in environment diagrams, and how those work.arr = null;
, the original 5-length array still exists, but just has nothing to refer to it.=
) has different behaviors for primitive types and references types.y = x
means "copy the bits from y into a new location, then call them x". Here, the entire object is copied- this means that changing y will NOT change x even though they are set "equal".obj1 = obj2
means "copy the address stored in obj1 to obj2". Here, obj1
and obj2
are referring to the exact same object, and mutating one will change the other.obj1.value = 1
. If you change the actual address of obj2
, as in obj2 = obj3
, this does not change obj1
because obj2
is now referring to a completely different object!String toString()
: By default, this prints out the class name followed by the memory address (e.g., [email protected]
). This can be overridden to make more user-friendly names for objects.boolean equals(Object obj)
: By default, this checks if the two objects are actually the same object (same memory address). This can be overridden to check if specific contents of objects are the same, rather than checking if they are literally the same object. (Like "foo"
should equal new String("foo")
)int hashCode()
: Returns a numeric hash code for the object that should differentiate it from other objects. This should be overridden if equals()
is overridden since x.hashCode()
should equal y.hashCode()
if x.equals(y)
is true!Class<?> getClass()
: Returns the class of this object.