官术网_书友最值得收藏!

3.8 Casting Variables to a Different Type

There will be occasions when you will have a variable which you wish to store in a variable of another type.

3.8.1 Automatic Casting

When the Java compiler knows that the new data type has enough room to store the new value the casting is automatic and there is no need to specify it explicitly. For example, if you had a value stored in a byte typed variables and wanted to store it in a integer typed variable the compiler will let you because a byte value will always fit in an integer.

int a; // 定義一個變量a
byte b=10; // 定義一個字節b并分配10
a = b; // 將b賦值給a

This kind of casting is commonly known as widening since the value has been made wider because it is now stored in a type which is larger than it actually needs, it is useful to view the widened value as padded by zeros.

這種擴展是一種普通的轉換,它的值會擴展,因為它存儲在一個比它實際還大的類型中,通過填補0來完成這種擴展。

3.8.2 Explicit Casting

When an int value is to be stored in a byte it is possible that the byte will not be able to hold the full value. In this case as explicit casting must be made, the syntax for this is as follows:

variable_of_smaller_type = (smaller_type) value_of larger_type;

該賦值語句將右邊較大的類型變量轉換為左邊類型較小的變量。

At first this appears complicated but it isn’t really, what the code is really saying is that the variable on the left is made equal to the smaller_type version of the value on the right. For the example above, this is:

class CastTest{
    public static void main (String args[]){
      byte a; //聲明一個字節變量a
      int b=10000; //聲明一個整型變量并賦值10000
      a = (byte) b; //顯式地將b轉換成a
      System.out.println (a); //將a打印出來
    }
}

In other words the variable a is assigned the byte value of the int variable b. When the full value will not fit in the new type, as in this example, then the value is reduced modulo(模)the byte’s range. In the above example the result stored in a is 16, that is 10000 % 128 = 16, where 128 is the range of a byte(0 to 127). If you want to try this for yourself, the just copy and paste it, save as CastTest.java and compile with the javac command and run with java - as you did for the first program in the last lesson.

將整型變量b的值賦值給字節變量。在這個例子中,變量的值不能完整地裝入新的類型中,這個值被縮小為字節型的范圍內。

主站蜘蛛池模板: 大埔县| 江阴市| 常宁市| 伊春市| 灌南县| 克什克腾旗| 阜康市| 葫芦岛市| 南乐县| 闵行区| 会昌县| 南丰县| 德清县| 缙云县| 馆陶县| 宜阳县| 衢州市| 阳原县| 鹤庆县| 合肥市| 阳谷县| 木兰县| 新竹市| 夏邑县| 嘉兴市| 大方县| 方城县| 宁德市| 迭部县| 桦甸市| 太白县| 资兴市| 呈贡县| 江城| 三江| 金秀| 巫溪县| 松江区| 福安市| 清远市| 济南市|