Java variables are categorized by data types, defining their value and type. These fall into two main groups: primitive and object (non-primitive) data types.
Primitive data types are predefined, with fixed sizes and types: byte
, short
, int
, long
, float
, double
, char
, and boolean
. They are stored directly on the stack. Object data types, conversely, are reference types including arrays, Strings, classes, and interfaces. A reference variable resides on the stack, while the object itself is stored in the heap.
This guide outlines the creation of both primitive and object data types in Java.
main
method's String[] args
parameter.The following code snippets demonstrate primitive and object data type usage.
Example 1: Demonstrating Primitive Types
public class PrimitiveTypes { public static void main(String[] args) { byte b = 16; System.out.println("Byte: " + b); int i = 2001; System.out.println("Integer: " + i); double d = 1997.10; System.out.println("Double: " + d); boolean bool = true; System.out.println("Boolean: " + bool); char c = 'A'; System.out.println("Character: " + c); } }
Example 2: Demonstrating Object Types and Reference Behavior
import java.util.Arrays; public class ObjectTypes { public static void main(String[] args) { int[] x = {10, 20, 30}; int[] y = x; // y references the same array as x System.out.println("Original x: " + Arrays.toString(x)); y[0] = 100; // Modifying y affects x because they reference the same array System.out.println("Modified x: " + Arrays.toString(x)); } }
Example 3: Using BigDecimal (Object Type for precise decimal arithmetic)
public class PrimitiveTypes { public static void main(String[] args) { byte b = 16; System.out.println("Byte: " + b); int i = 2001; System.out.println("Integer: " + i); double d = 1997.10; System.out.println("Double: " + d); boolean bool = true; System.out.println("Boolean: " + bool); char c = 'A'; System.out.println("Character: " + c); } }
null
value, indicating that they do not refer to any object. Primitive types cannot be null
.This overview provides a foundational understanding of primitive and object data types in Java. For more advanced topics, explore Java's class libraries and delve into concepts like object-oriented programming, memory management, and exception handling. Consider researching specific data structures and algorithms for efficient data manipulation.
The above is the detailed content of Primitive data type vs. Object data type in Java with Examples. For more information, please follow other related articles on the PHP Chinese website!