[java] What's the difference between primitive and reference types?

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.

This question is related to java types reference primitive

The answer is


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


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


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


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


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.

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);

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.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to reference

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference "

Examples related to primitive

Converting characters to integers in Java What's the difference between primitive and reference types? Java: Integer equals vs. == How to cast Object to boolean? Java equivalent of unsigned long long? Primitive type 'short' - casting in Java Generic type conversion FROM string