天天看點

java的常見類型轉換

如何将long類型轉換為string

//方法一:

當我們要把String轉化為Integer時,一定要對String進行非空判斷,否則很可能報空指針異常。

String str = "...";

Integer i = null;

if(str!=null){

i = Integer.valueOf(str);

}

擷取一個變量的類型

        <code>   </code><code>public</code> <code>static</code> <code>void</code> <code>main(String[] args) {</code>

<code>        </code><code>Test test = </code><code>new</code> <code>Test();</code>

<code>        </code><code>System.out.println(test.getClass().getSimpleName());</code>

<code>    </code><code>}</code>

<code>}</code>

1.Integer轉換成int的方法

Integer i;  int k = i.intValue(); 即Integer.intValue();

2.int轉換成Integer

int i;

Integer it = new Integer(i);

3.String轉換成int的方法

String str = "10";   Integer it = new Interger(str);  

int i = it.intValue();  

即:int i = Integer.intValue(string);

4.int轉換成String

(1)String s = String.valueOf(i);

(2)String s = Ingeger.toString(i);

(3)String s = "" + i;

5.String轉換成Integer

String str = "10"

Integer it = Integer.valueOf(str);

6.Integer轉換成String

Integer it;

String str = it.toString();

7.String轉換成BigDecimal

BigDecimal bd = new BigDecimal(str);

8.日期

Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1; int day = calendar.get(Calendar.DATE);

//擷取今天的日期字元串 String today = Java.text.DateFormat.getDateInstance().format(new java.util.Date()); //擷取今天的日期 new java.sql.Date(System.currentTimeMillis());