- 雙語版Java程序設計
- 何月順主編
- 696字
- 2018-12-27 20:14:12
3.3 Casting
Because Java is a strongly typed language, it is sometimes necessary to perform a cast of a variable. Casting is the explicit(顯式) or implicit(隱式) modification(修改) of a variable’s type. Remember before when I mentioned that once you declare a variable as a specific type, it has that type indefinitely? Well, casting allows us to view the data within a given variable as a different type than it was given. Casting is a rather large topic (especially when dealing with reference types). Instead of trying to tackle(解決) all of it, I’ll just hit on a few aspects relating to Java’s primitive data types.
類型轉換允許將一個變量的類型改變為不同的類型。
In order to perform a cast, you place the type that you want to view the data as in parenthesis prior to the variable you want to cast, like this:
1: short x = 10; 2: int y = (int)x;
This code snippet(片段) causes the data in x, which is of type short, to be turned into an int and that value is placed into y. Please note, the variable x is not changed! The value within x is copied into a new variable (y), but as an int rather than a short.
There are two types of conversions that can be done to data, widening conversions and narrowing conversions. Widening conversions can be done implicitly (by the compiler, that is) and narrowing conversions must be done explicitly, by you, the programmer. The difference is simple. A widening conversion is when you take a variable and assign it to a variable of larger size. A narrowing conversion is when you take a variable and assign it to a variable of smaller size. Let’s look at some examples:
對數據來講有兩種轉換方式:擴展轉換和收縮轉換。擴展轉換是隱式的(通過編譯器),而收縮轉換必須顯式聲明。
3.3.1 Widening
1: byte x = 100; // Size = 1 byte 2: // In memory: x = 01100100 = 100 3: short y; // Size = 2 bytes 4: // In memory: y = 0000000000000000 = 0 5: y = x; // Legal 6: // In memory: y = 0000000001100100 = 100
3.3.2 Narrowing
1: short x = 1000; // Size = 2 bytes 2: // In memory: x = 0000001111101000 = 1000 3: byte y; // Size = 1 byte 4: // In memory: y =00000000 = 0 5: y = x; // Illegal 6: // Not enough space to copy all data 7: y = (byte)x; // Legal 8: // In memory: y =11101000 = 232
You can see from the first example that it is easy to copy the contents of a byte into a short because a short has enough space to accommodate whatever data was originally stored in the byte. In the second example, however, there isn’t enough space in a byte to accommodate what may be in the short. In order to get around that, you are required to explicitly cast, as seen in the seventh line. Notice, however, even though you are allowed to perform this cast, some data may be lost, as was the case in this example. This potential data loss is the reason for the required explicit cast.
字節型轉換為短整型只是簡單地將內容復制,因為短整型提供了足夠大的空間來存儲原存儲在字節型中的任何數。如果沒有提供足夠的空間來存儲短整型,為了實現這種轉換就必須顯式地進行轉換。