parseInt() parseFloat() 和 toString()

1、parseInt() 方法 是將String 類型轉換成 int 類型 

     parseFloat()方法 是將String 類型裝換成 float 類型 

2、Integer.valueOf() 方法 是將  String 類型裝換成 Integer 類型  是Integer 類型 而不是 int 類型  

      Integer 類型是一個引用的複雜類型  

     int 類型是一個簡單的數字類型 

3、 toString 能將引用型轉換成String 類型

如: 下面的例子就是 將Integer 類型轉換成String 類型

  Integer integer = new Integer(123);

String  temp = integer .toString();

就變成了 Strinhg 類型的123 了;



如下例子  可供參考

package method.usually;


public class typeMethod {


public static void main(String[] args) {

//比較兩個方法
compareValueOfAndParse();
   
   // valueOf()方法的使用
   useValueIOf();

//toString()方法的調用
methodToString();
}


/**
* toString()方法的使用
*/
public static void methodToString(){
 Integer integer = new Integer(123);
 String  temp = integer .toString();
 System.out.println(temp);
 System.out.println(temp.getClass().getName());
}

/**
* valueOf()方法 德大結果驗證
*/
public static void useValueIOf(){
   String  str = "123";
   Integer integer = Integer.valueOf(str);
   System.out.println("類型爲:"+integer.getClass().getName()+"的   "+integer); 
   int strInt = integer.intValue();  //intValue() 可以將Integer 類型轉換成 int
   System.out.println(strInt);  //這個是 int 類型的123
}

/**
* parseInt/parseFloat() 方法和valueOf() 方法的區別 
* 前者是可以轉換成簡單的類型 如:int float 
* 後者是能裝換成Integer 或者是 Float 這樣的封裝類型 即複雜類型
*/
public static void compareValueOfAndParse(){
Float f = new Float("9.5");
String str = "123";
System.out.println(Integer.valueOf(str).getClass().getName());
System.out.println(Integer.parseInt(str));
System.out.println(Float.valueOf(str).getClass().getName());
System.out.println(Float.parseFloat(str));
System.out.println("Value1 = "+ Float.parseFloat(str));
System.out.println("Value = " +  f.valueOf(str));
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章