W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
java數(shù)據(jù)類型的相互轉換 -=
1.string和int互相轉化
1.1 如何將字串 String 轉換成整數(shù) int, double, float, long?
A. 有兩個方法:
1) int i = Integer.parseInt([String]); 或 int i = Integer.parseInt([String],[int radix]);
2) int i = Integer.valueOf(my_str).intValue(); 注1:這兩種種方法有什么區(qū)別呢?
1) i=Integer.parseInt(s);//直接使用靜態(tài)方法,不會產(chǎn)生多余的對象,但會拋出異常 2) i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相當于 new Integer(Integer.parseInt(s)),也會拋異常,但會多產(chǎn)生一個對象
注2: String 轉成 double, float, long 的方法大同小異.
1)double d = Double.parseDouble("1.0");
2)float f = Float.parseFloat("1.0");;
3)long L = Long.parseLong("1.0");
1.2 如何將整數(shù) int 轉換成字串 String ?
A. 有叁種方法:
1.) String s = String.valueOf(i);
2.) String s = Integer.toString(int i); String s = Double.toString(double d); String s = Float.toString(float f); String s = Long.toString(long L);
3.) String s = "" + i; 注1:這兩種種方法有什么區(qū)別呢?
1) s=i+""; //會產(chǎn)生兩個String對象 2) s=String.valueOf(i); //直接使用String類的靜態(tài)方法,只產(chǎn)生一個對象
2.string 和 Integer, Double, Float, Long互相轉化
2.1 如何將字串 String 轉換成整數(shù) Integer, Double, Float, Long?
A. 有兩個方法:
1) Integer i = Integer.valueOf(String num); 2) Double d = Double.valueOf(String num); 3) Float f = Float.valueOf(String num); 4) Long l = Long.valueOf(String num);
2.2 如何將整數(shù) Integer, Double, Float, Long 轉換成字串 String ? 與1.2相同
這是一個例子,說的是JAVA中數(shù)據(jù)數(shù)型的轉換.供大家學習引
package cn.com.lwkj.erts.register;
import java.sql.Date;
public class TypeChange {
public TypeChange() {
}
//change the string type to the int type
public static int stringToInt(String intstr)
{
Integer integer;
integer = Integer.valueOf(intstr);
return integer.intValue();
}
//change int type to the string type
public static String intToString(int value)
{
Integer integer = new Integer(value);
return integer.toString();
}
//change the string type to the float type
public static float stringToFloat(String floatstr)
{
Float floatee;
floatee = Float.valueOf(floatstr);
return floatee.floatValue();
}
//change the float type to the string type
public static String floatToString(float value)
{
Float floatee = new Float(value);
return floatee.toString();
}
//change the string type to the sqlDate type
public static java.sql.Date stringToDate(String dateStr)
{
return java.sql.Date.valueOf(dateStr);
}
//change the sqlDate type to the string type
public static String dateToString(java.sql.Date datee)
{
return datee.toString();
}
public static void main(String[] args)
{
java.sql.Date day ;
day = TypeChange.stringToDate("2003-11-3");
String strday = TypeChange.dateToString(day);
System.out.println(strday);
}
}
JAVA中常用數(shù)據(jù)類型轉換函數(shù) 雖然都能在JAVA API中找到,整理一下做個備份。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: