What's the difference between primitive and reference types?

JavaTypesReferencePrimitive

Java Problem Overview


This is a past exam question and I was wondering what a primitive type and reference type are first off? With an array I know the a reference type is where the array is composed of objects or variables, but a primitive type is where you would create the array with just int or strings. (right?)

How do you think you would answer the question on the test and be given good credit? Without really referring directly to an primitive ARRAY type... Is there a way to do it without that? Or do you think it would be fine to just explain it with the array.

Java Solutions


Solution 1 - Java

From book OCA JAVA SE 7

> Just as men and women are fundamentally different (according to John > Gray, author of Men Are from Mars, Women Are from Venus), primitive > variables and object reference variables differ from each other in > multiple ways. The basic difference is that primitive variables store > the actual values, whereas reference variables store the addresses of > the objects they refer to. Let’s assume that a class Person is > already defined. If you create an int variable a, and an object > reference variable person, they will store their values in memory as > shown in figure 2.13.

int a = 77;
Person person = new Person();

enter image description here

Solution 2 - Java

These are the primitive types in Java:

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

All the other types are reference types: they reference objects.

This is the first part of the Java tutorial about the basics of the language.

Solution 3 - Java

Primitive Data Types :

  • Predefined by the language and named by a keyword
  • Total no = 8
    boolean
    char
    byte
    short
    integer
    long
    float
    double

Reference/Object Data Types :

  • Created using defined constructors of the classes
  • Used to access objects
  • Default value of any reference variable is null
  • Reference variable can be used to refer to any object of the declared type or any compatible type.

Solution 4 - Java

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

Solution 5 - Java

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

Solution 6 - Java

As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).

Primitive Type

Describes a value (and not a type).

11

Reference Type

Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!

Integer

Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.

Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.

Wildcard Type

Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.

? extends List<String>
? super ArrayList<String>

Void Type

Nothingness. No value/instance possible.

void method();

Null Type

The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).

null

Union Type

A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.

catch(IllegalStateException | IOException e) {}

Interference Type

A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.

void method(List<? extends List<?> & Comparable> comparableList) {}

Unknown Type

The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).

list.forEach(element -> System.out.println(element.toString)); //element is of unknown type

Var Type

Unknown type introduced by a variable declaration spotting the 'var' keyword.

var variable = list.get(0);

Solution 7 - Java

The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.

Primatives:

boolean

character

byte

short

integer

long

float

double

Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types

Solution 8 - Java

Primitive data type

The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.

It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.

And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)

8 primitive data types in Java

+================+=========+===================================================================================+
| Primitive type | Size    | Description                                                                       |
+================+=========+===================================================================================+
| byte           | 1 byte  | Stores whole numbers from -128 to 127                                             |
+----------------+---------+-----------------------------------------------------------------------------------+
| short          | 2 bytes | Stores whole numbers from -32,768 to 32,767                                       |
+----------------+---------+-----------------------------------------------------------------------------------+
| int            | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647                         |
+----------------+---------+-----------------------------------------------------------------------------------+
| long           | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float          | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits           |
+----------------+---------+-----------------------------------------------------------------------------------+
| double         | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits               |
+----------------+---------+-----------------------------------------------------------------------------------+
| char           | 2 bytes | Stores a single character/letter or ASCII values                                  |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean        | 1 bit   | Stores true or false values                                                       |
+----------------+---------+-----------------------------------------------------------------------------------+

Reference data type

Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.

when declaring the reference type need to allocate memory. In Java, we used new keyword to allocate memory, or alternatively, call a factory method.

Example:

List< String > strings = new ArrayList<>() ;  // Calling `new`  to instantiate an object and thereby allocate memory.

Point point = Point(1,2) ;           // Calling a factory method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWestJacksonView Question on Stackoverflow
Solution 1 - JavaBERGUIGA Mohamed AmineView Answer on Stackoverflow
Solution 2 - JavaJB NizetView Answer on Stackoverflow
Solution 3 - JavaGaurav TyagiView Answer on Stackoverflow
Solution 4 - JavaSachindra N. PandeyView Answer on Stackoverflow
Solution 5 - JavaMustafa HussainView Answer on Stackoverflow
Solution 6 - JavaMartin KerstenView Answer on Stackoverflow
Solution 7 - JavajamesTheProgrammerView Answer on Stackoverflow
Solution 8 - JavaJayani SumudiniView Answer on Stackoverflow