- 方法 (method) 的參數 (parameter) 指定為物件
- 類別所定義的常數,如類別的上界或下界
- 由字串轉換成數字型態,或數字轉換成字串
基本資料型態中數字相關有 byte 、 short 、 int 、 long 、 float 、 double ,每一種都相對應繼承自 Number 的類別,如下表
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
在 Java 5.0 之後,使用基本資料型態的情況,編譯器大多會主動進行自動包裝 (autoboxing) ,因此很多情況下不需要考慮到將基本資料型態轉換成物件的包裝。
Number 的子類別 (subclass) 有實作如下的方法
| 方法 | 描述 |
|---|---|
| byte byteValue() short shortValue() int intValue() long longValue() float floatValue() double doubleValue() | 將 Number 轉換回基本資料型態 |
| int compareTo(Byte anotherByte) int compareTo(Double anotherDouble) int compareTo(Float anotherFloat) int compareTo(Integer anotherInteger) int compareTo(Long anotherLong) int compareTo(Short anotherShort) | 比較參數與 Number 物件 |
| boolean equals(Object obj) | 測試是否與參數具有相同型態及數值 |
另外有以下方法,用來轉換成字串
| 方法 | 描述 |
|---|---|
| static Integer decode(String s) | 將字串解碼為數字 |
| static int parseInt(String s) | 將字串解析為十進位整數 |
| static int parseInt(String s, int radix) | 將字串解析為指定進位的整數 |
| String toString() | 轉換成字串 |
| static String toString(int i) | 轉換成字串 |
| static Integer valueOf(int i) | 回傳參數的整數物件 |
| static Integer valueOf(String s) | 回傳參數的整數物件 |
| static Integer valueOf(String s, int radix) | 回傳參數的字串物件 |
以下程式舉數例示範
class NumberDemo {
public static void main(String[] args) {
String s1 = "33";
String s2 = "33.23";
int x1 = Integer.parseInt(s1);
System.out.println(x1);
double x2 = Double.parseDouble(s2);
System.out.println(x2);
String y1 = "" + x1;
System.out.println(y1);
String y2 = Double.toString(x2);
System.out.println(y2);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:NumberDemo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

| 中英文術語對照 | |
|---|---|
| 基本資料型態 | primitive data type |
| 物件 | object |
| 方法 | method |
| 參數 | parameter |
| 自動包裝 | autoboxing |
| 子類別 | subclass |
沒有留言:
張貼留言