Today I Learned

Some of the things I've learned every day since Oct 10, 2016

100: Primitive Types vs. Reference Types (Java)

In the Java programming language, values either have a primitive type or a reference type. The primitive types are:

  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double

All other types not in this list are reference types.

A value with a primitive type stores the information determining the value itself, such as the binary code for a given integer or character. By contrast, a value with a reference type stores the address of the location in memory where this information can be found. For instance, after declaring and instantiating a variable

\texttt{String s = "string";}

the variable \texttt{s} doesn’t store the code for the String itself, but rather a ‘pointer’ to where this code can be found.

This has important consequences for how primitive values are assigned to variables or passed as parameters, as opposed to reference values. A primitive value passed or assigned will have the bits describing the value itself copied to the target, whereas a reference value will merely have the address of these bits copied.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: