The Notebook of CS61B

Introduction to Java

  • [x] 1
  • [ ] 2
  • [ ] 3
  • [ ] 4
  • [ ] 5
  • [ ] 6
  • [ ] 7

Lists

Mystery of Walrus

1
2
3
4
5
6
Walrus a = new Walrus(1000, 8.3);
Walrus b;
b = a;
b.weight = 5;
System.out.println(a);
System.out.println(b);

The Golden Rule of Equals (GRoE)

When you write y = x, you are telling the Java interpreter to copy the bits from x into y. This Golden Rule of Equals (GRoE) is the root of all truth when it comes to understanding our Walrus Mystery.

Object Instantiation

8 primitive types: byte, short, int, long, float, double, boolean, char.

Everything else, including arrays, is not a primitive type but rather a reference type.

When we instantiate an Object using new, java:

  1. allocates a box for each instance variable of the class, and fills them with a default value.
  2. The constructor then usually (but not always) fills every box with some other value.

Reference Variable Declaration

When we declare a variable of any reference type (Walrus, Dog, Planet, array, etc.), Java allocates a box of 64 bits, no matter what type of object.

The 64 bit box contains not the data about the walrus, but instead the address of the Walrus in memory.

Box and Pointer Notation

Parameter Passing: Pass by Value (VIP)

When you pass parameters to a function, you are also simply copying the bits. In other words, the GRoE also applies to parameter passing. Copying the bits is usually called “pass by value“. In Java, we always pass by value.

so in this expressionWalrus b;, b is undefined, not null.

Instantiation of Arrays

Int[] a -> declaration

Creates a 64 bit box (the size of its address) intended only for storing a reference to an int array.

No Object is instantiated.

new int[]{1, 2, 4, 94} ->instantiation

new object, which is an int array, is created by this expression and anonymous.

Int[] a =new int[]{1, 2, 4, 94} contains:
Declaration/ Instantiation/ Assignment: put the address of the new object into that 64 bit box.

so if a = [something new] that address would be lost and never get that back.

The Law of the Broken Futon