原始数据类型:在Java,原始数据类型是Java预定义的数据类型。它们指定任何标准值的大小和类型。 Java有 8 种原始数据类型,分别是 byte、short、int、long、float、double、char 和 boolean。当存储原始数据类型时,将分配值的是堆栈。复制变量时,会创建该变量的另一个副本,对复制的变量所做的更改不会反映原始变量的更改。下面是一个Java程序,以证明所有Java中的基本数据类型。
对象数据类型:这些也称为非原始数据类型或参考数据类型。它们被称为是因为它们指代任何特定的对象。与原始数据类型不同,非原始数据类型是由用户在Java中创建的。示例包括数组、字符串、类、接口等。当存储引用变量时,变量将存储在堆栈中,原始对象将存储在堆中。在 Object 数据类型中,虽然将创建两个副本,但它们都将指向堆中的同一个变量,因此对任何变量所做的更改都将反映两个变量的更改。这里是一个Java程序在Java中展示阵列(一个对象的数据类型)。
Java原始数据类型和对象数据类型的区别:
现在让我们看一个程序,它演示了Java原始数据类型和对象数据类型之间的区别。
Java
import java.lang.*;
import java.util.*;
class GeeksForGeeks {
public static void main(String ar[])
{
System.out.println("PRIMITIVE DATA TYPES\n");
int x = 10;
int y = x;
System.out.print("Initially: ");
System.out.println("x = " + x + ", y = " + y);
// Here the change in the value of y
// will not affect the value of x
y = 30;
System.out.print("After changing y to 30: ");
System.out.println("x = " + x + ", y = " + y);
System.out.println(
"**Only value of y is affected here "
+ "because of Primitive Data Type\n");
System.out.println("REFERENCE DATA TYPES\n");
int[] c = { 10, 20, 30, 40 };
// Here complete reference of c is copied to d
// and both point to same memory in Heap
int[] d = c;
System.out.println("Initially");
System.out.println("Array c: "
+ Arrays.toString(c));
System.out.println("Array d: "
+ Arrays.toString(d));
// Modifying the value at
// index 1 to 50 in array d
System.out.println("\nModifying the value at "
+ "index 1 to 50 in array d\n");
d[1] = 50;
System.out.println("After modification");
System.out.println("Array c: "
+ Arrays.toString(c));
System.out.println("Array d: "
+ Arrays.toString(d));
System.out.println(
"**Here value of c[1] is also affected "
+ "because of Reference Data Type\n");
}
}
输出
PRIMITIVE DATA TYPES
Initially: x = 10, y = 10
After changing y to 30: x = 10, y = 30
**Only value of y is affected here because of Primitive Data Type
REFERENCE DATA TYPES
Initially
Array c: [10, 20, 30, 40]
Array d: [10, 20, 30, 40]
Modifying the value at index 1 to 50 in array d
After modification
Array c: [10, 50, 30, 40]
Array d: [10, 50, 30, 40]
**Here value of c[1] is also affected because of Reference Data Type
让我们以表格的方式看一下原始数据类型和对象数据类型之间的区别。
Properties | Primitive data types | Objects |
---|---|---|
Origin | Pre-defined data types | User-defined data types |
Stored structure | Stored in a stack | Reference variable is stored in stack and the original object is stored in heap |
When copied | Two different variables is created along with different assignment(only values are same) | Two reference variable is created but both are pointing to the same object on the heap |
When changes are made in the copied variable | Change does not reflect in the original ones. | Changes reflected in the original ones. |
Default value | Primitive datatypes do not have null as default value | The default value for the reference variable is null |
Example | byte, short, int, long, float, double, char, boolean | array, string class, interface etc. |