object vs. primitive

A primitive is a data type that is composed of no other data types and can not be broken down any further. It is like the atoms in the programming scenario. I say atom because atom is a basic unit of matter and there is nothing that can be derived from it.

I mean, an int in C can not be broken down into smaller data type. An object, on the other hand can be thought of a molecule, consisting of more than one primitive type. For example, string comes as part of the C++ standard library; however, it is an object and it is composed of smaller data types internally and contains methods.

It is important to note that not all object-oriented languages are class based (eg. Javascript) You can not define a class in Javascript, so an object is quite different here. Even though everything in Javascript is an object (Ruby also), the Number object is really a wrapper for an internal primitive.


From Java perspective:

  1. A primitive is not composed of other data types. Where as an object can be and generally is.
  2. Primitives are passed by value, i.e. a copy of the primitive itself is passed. Whereas for objects, the copy of the reference is passed, not the object itself.
  3. Primitives are independent data types, i.e. there does not exist a hierarchy/super class for them. Whereas every Object is descendent of class "Object".
  4. Every object has some default methods of itself, which it inherits from the class Object (e.g. toString(), clone(), wait(), notify(), notifyAll(), etc.). The primitives does not have any method associated with themselves.
  5. Primitives are immutable, they can be used as so without any special care. Whereas for objects, special care needs to be taken, they are not immutable by default.
  6. With objects, there are two types of copies, Shallow and Deep. There is a significant difference between them. So the choice depends on how do we intend to use them. With primitives, there is no such difference, everything is by default deep copy only.

Let us Visualize the actual differences.

Primitives

1) A primitive data type uses a small amount of memory to represent a single item of data. All data of the same primitive type are the same size.

For Example: Primitive type int represents integers using 32 bits. All variables of type int use 32 bits.

2) There are only eight primitive data types in Java: byte, short, int, long, float, double, char, and boolean. A Java program cannot define any other primitive data types.

Objects

An object is a large chunk of memory that can potentially contain a great deal of data along with methods (little programs) to process that data. There are thousands of object classes that come standard with Java, and a programmer can easily create additional classes. (Although there are thousands of standard classes, for this course you only need become familiar with a dozen or so classes.)