What's the difference between primitive and reference types?
Asked Answered
J

9

81

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 that 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.

Jato answered 9/1, 2012 at 15:30 Comment(8)
..primitive type is where you would create the array with just int or strings strings [or to be more accurate: Strings] are not primitive types in javaBrocatel
Whenever people ask this types of questions, I recommend them to learn C first.Alarcon
@Alarcon C has pointers not referencesSoiree
@Eng.Fouad: passing an argument by reference is well defined in C. Understanding of these concepts [pointers, values, pass by reference] in C almost ensures understanding the difference between reference and primitive types, although there are no references in C. The idea of 'messing' with the memory and low level - gives you a better understanding on what is a reference and what is a value.Brocatel
@Eng.Fouad, yes but the underlying concept is so similar. I have never seen one who understands C pointer but don't understand Java/C++ reference.Alarcon
Some decades ago -- the generally accepted definition of a primitive type was simply -- a variable type that fit in the microprocessor's registers. (Usually A, AX, EAX, etc. -- the Accumulator.) Strings, for example -- are arrays and do not fit into a register. An Integer was always the size (width in bits) of the Accumulator. References may not be pointers, however -- pointers ARE references.Irisirisa
A Java reference variable is far more like a C or C++ pointer variable than like a C++ reference variable.Hydraulics
further you can read, smugjava.blogspot.in/2017/11/reference-data-type-in-java.htmlFlotage
S
47

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.

Scratchy answered 9/1, 2012 at 15:33 Comment(6)
Though true, I doubt he will get full credit for this answer. I think the lecturer expects to hear more about what "thery reference objects" means, and some example showing what happens to a variable, in a calling environment, if you change it within a called methodBrocatel
Yes, but I won't repeat all what's being said in the tutorial, and I prefer giving him pointers to pages where he can learn rather than a ready-to-use answer.Scratchy
Note also that all array types are objects, and can be casted to/from java.lang.Object.Chemosh
I don't think this answers the question. You haven't really said what the difference between a primitive type and a reference type is. You've just listed some of one. JB, I feel you have squandered the opportunity to write one of your usual highly exemplary answers.Hydraulics
I feel accepted answer should have been one given by BERGUIGA Mohamed Amine belowLatin
This is not the answer to question "What's the difference"Thrasher
A
180

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

Audition answered 17/8, 2015 at 11:57 Comment(5)
they should deffinetly increace the time in witch you can mark best answer to a 24h and then pop up a remider to remind you to mark one so that people don't rush it. I could have said as well that referent types can store primitive, but i knew there was more it. Thank you.Mines
nicely explained. I have one more question here though. is there any difference between non primitive and reference variables (or these are just synonymous)Irrefutable
@Irrefutable AFAIK, they are just synonyms.Broder
@QuackMan245 This must be selected as answer! Voted up, thanks a lot.Ambler
@ВсеЕдно It is still not clear why would one use reference type? For example instead of doing Person person = new Person(); , one can also use Person person; person.set(something); person.get() Quadruple
S
47

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.

Scratchy answered 9/1, 2012 at 15:33 Comment(6)
Though true, I doubt he will get full credit for this answer. I think the lecturer expects to hear more about what "thery reference objects" means, and some example showing what happens to a variable, in a calling environment, if you change it within a called methodBrocatel
Yes, but I won't repeat all what's being said in the tutorial, and I prefer giving him pointers to pages where he can learn rather than a ready-to-use answer.Scratchy
Note also that all array types are objects, and can be casted to/from java.lang.Object.Chemosh
I don't think this answers the question. You haven't really said what the difference between a primitive type and a reference type is. You've just listed some of one. JB, I feel you have squandered the opportunity to write one of your usual highly exemplary answers.Hydraulics
I feel accepted answer should have been one given by BERGUIGA Mohamed Amine belowLatin
This is not the answer to question "What's the difference"Thrasher
B
8

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.
Bag answered 31/8, 2016 at 10:35 Comment(0)
C
6

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

Curcio answered 17/1, 2016 at 11:52 Comment(0)
D
4

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

Dimphia answered 25/7, 2013 at 5:16 Comment(1)
No. A primitive value can be stored in the heap or the stack. It will be in the heap if it's a field of some object.Hydraulics
V
3

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);
Volgograd answered 2/10, 2018 at 20:36 Comment(0)
G
3

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.
Greenstone answered 13/1, 2020 at 4:1 Comment(1)
@OleV.V. I changed itGreenstone
B
2

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

Berke answered 9/1, 2012 at 15:42 Comment(0)
G
0

The difference is that whatever value you assign to a primitive variable PV, that actual value is what will be associated with the variable PV, not a reference to that value. In the other hand, whatever value you assign to a reference variable RV, a reference to that value is what will be associated with the variable RV not the value itself.

Glabrous answered 13/9, 2022 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.