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.

user4035
  • 22,508
  • 11
  • 59
  • 94
WestJackson
  • 1,067
  • 3
  • 11
  • 14
  • 3
    `..primitive type is where you would create the array with just int or strings` strings [or to be more accurate: `String`s] are not primitive types in java – amit Jan 09 '12 at 15:32
  • 3
    Whenever people ask this types of questions, I recommend them to learn C first. – taskinoor Jan 09 '12 at 15:35
  • @taskinoor C has pointers not references – Eng.Fouad Jan 09 '12 at 15:38
  • 3
    @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. – amit Jan 09 '12 at 15:40
  • 1
    @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. – taskinoor Jan 09 '12 at 15:56
  • 2
    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. – jinzai Mar 03 '16 at 17:11
  • A Java reference variable is _far_ more like a C or C++ pointer variable than like a C++ reference variable. – Dawood ibn Kareem Jun 30 '17 at 03:54
  • further you can read, https://smugjava.blogspot.in/2017/11/reference-data-type-in-java.html – Jameer Mulani Nov 18 '17 at 10:22

9 Answers9

178

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

BERGUIGA Mohamed Amine
  • 6,094
  • 3
  • 40
  • 38
  • 3
    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. – Все Едно May 11 '17 at 18:25
  • nicely explained. I have one more question here though. is there any difference between non primitive and reference variables (or these are just synonymous) – atish Sep 06 '19 at 10:29
  • 1
    @atish AFAIK, they are just synonyms. – O.Badr Feb 25 '20 at 07:38
  • 2
    @QuackMan245 **This must be selected as answer**! Voted up, thanks a lot. –  May 07 '20 at 13:57
  • @ВсеЕдно 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() ` – user2979872 Feb 10 '22 at 16:37
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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 7
    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 method – amit Jan 09 '12 at 15:44
  • 5
    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. – JB Nizet Jan 09 '12 at 15:49
  • Note also that all array types are objects, and can be casted to/from `java.lang.Object`. – Nayuki May 29 '17 at 20:18
  • 7
    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. – Dawood ibn Kareem Jun 30 '17 at 03:46
  • 1
    I feel accepted answer should have been one given by BERGUIGA Mohamed Amine below – Yogesh D Oct 19 '18 at 04:13
  • 6
    This is not the answer to question "What's the difference" – Dmitriy Pavlukhin Oct 01 '19 at 12:45
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.
Tom
  • 16,842
  • 17
  • 45
  • 54
Gaurav Tyagi
  • 81
  • 1
  • 4
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

Dexter
  • 4,036
  • 3
  • 47
  • 55
Sachindra N. Pandey
  • 1,177
  • 17
  • 15
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

Ankur
  • 5,086
  • 19
  • 37
  • 62
Mustafa Hussain
  • 107
  • 1
  • 6
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);
Martin Kersten
  • 5,127
  • 8
  • 46
  • 77
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.
Jayani Sumudini
  • 1,409
  • 2
  • 22
  • 29
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

Useless
  • 64,155
  • 6
  • 88
  • 132
jamesTheProgrammer
  • 1,747
  • 4
  • 22
  • 34
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.

Milford P
  • 48
  • 6