导入
基本类型和引用类型
学习 Java 如何存储基本类型值和对象引用,以及它们在内存中的行为。
...
Primitives store values directly; references store addresses pointing to objects
Table
| Type | Description | Size |
|---|---|---|
| byte | Very small integer | 8-bit |
| short | Small integer | 16-bit |
| int | Standard integer | 32-bit |
| long | Large integer | 64-bit |
| float | Decimal number (standard precision) | 32-bit |
| double | Decimal number (high precision) | 64-bit |
| boolean | true or false | ~1 bit (virtual) |
| char | Single Unicode character | 16-bit |
1public class PrimitivesExample { 2 public static void main(String[] args) { 3 int population = 8000; 4 double price = 19.99; 5 boolean isActive = true; 6 char grade = 'A'; 7 8 System.out.println("Population: " + population); 9 System.out.println("Price: " + price); 10 } 11}
1public class ReferenceExample { 2 public static void main(String[] args) { 3 // 'greeting' is the reference (holds the address) 4 // "Hello Java" is the object (stored separately in memory) 5 String greeting = "Hello Java"; 6 7 System.out.println(greeting); 8 } 9}
1public class PrimitiveCopy { 2 public static void main(String[] args) { 3 int a = 10; 4 int b = a; // Copies the value 10 into b 5 6 b = 55; // Changes b only 7 8 System.out.println("a: " + a); // a remains 10 9 System.out.println("b: " + b); // b is 55 10 } 11}
1public class ReferenceAlias { 2 public static void main(String[] args) { 3 // Create a modifiable string containing "Start" 4 StringBuilder ref1 = new StringBuilder("Start"); 5 6 // Copy the address from ref1 to ref2 7 StringBuilder ref2 = ref1; 8 9 // Change the text using ref2 10 ref2.append("+End"); 11 12 // ref1 sees the change because it points to the same object 13 System.out.println("ref1: " + ref1); 14 } 15}
1public class NullExample { 2 public static void main(String[] args) { 3 String message = null; // message holds no address 4 5 // System.out.println(message.length()); // RUNTIME ERROR 6 7 System.out.println("Message is: " + message); 8 } 9}