Programming Language

Difference Between A Class Type And A Primitive Type In Java

In Java, every variable has a type, which basically tells Java about the treatment of that variable, and how much memory should be assigned for that variable. Generally, Java has key types of characters, different types of floating point numbers, different types of integers, and also types for the values false and true –bool, char, float and int. All these basic kinds are named as primitive types.

What is a class type in Java?

As you probably already know, Java classes are created for solving object oriented problems. Thus, any object of a class has the “class” type. Since an object of a class is more complicated as compared to a simple boolean, integer or other primitive type, therefore, a variable naming an object is identified to be a class type.

Reference types vs. Object types vs. Class types

You may be puzzled by all these different terminologies. Thus, just to clarify, reference types, class types and object types all are the same thing having the same meaning (an object of a class).

Differences Between Primitive And Class Types In Java

In Java, a variable of a class type – such as a String – stocks objects of its class in a different manner of how variables of primitive types – such as char or int – store their values. Each variable, whether it’s of a class type or a primitive type, is implemented as a location in the memory of the computer.

For a primitive type variable, the variable’s value is stored in the memory location allocated to the variable. Thus, in case, an integer variable is stated as “int x = 2″, then when we see the memory location of “x”, there will be a “2” stored there as per the expectation.

But, a variable of a class type stocks the memory address about the location of the object as well as the values inside the object. Thus, in case, we have a class named “FewClass”, when we develop an object like this: “FewClass anObject”, then in memory when we see at “anObject”, we will find out that it does not stock any of the variables that is related to that object in memory.

Rather “anObject” variable only stocks an address of another place in memory where all the description of “anObject” exists. This clearly means that the variable comprises of just the memory address of where the object is stored, which is also known as a reference to the object.

Leave a Reply