Primitive and Reference types
Data types in Java
There are mainly 2 groups of data types in Java as Primitive and Reference data types.
Java has 8 primitives types built-in. All are lowercase. E.g: int
int age = 23
All 8 primitive types,
- boolean
- byte
- short
- char
- int
- long
- float
- double
Reference types are huge and constantly growing. There are built-in types once and also the programmer can create its own.
Simply all data types other than primitive are reference...
E.g: String, Scanner, Thread, File
String language = new String(“texthere”);
In most cases, new keyword is used to instantiate (create) a reference type (object).
User-defined ones will be like,
Person person = new Person();
Stack Vs Heap
The main difference comes related to this. There are 2 memory spaces as stack and heap. Primitive types store actual values and reference types stores memory address where actual data is located.
More details about stack vs heap [1]
Referencing
Here is a small example to differentiate the use of existing memory address and creating a memory address.
String x = new String(“text”);
String y = new String(“text”);
String z = y;
System.out.println(x == y); // false, because its 2 memory addresses
System.out.println(y == z); // true, referring same memory address
Null
Unlike primitive types, reference type can refer to a null.
String x = null
References
[1]https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap