8種數據類型之間的轉換
版權聲明:所屬版權歸本人所有 https://blog.csdn.net/weixin_42295141/article/details/89879196
-
package com.itheima;
-
-
import java.text.ParseException;
-
import java.text.SimpleDateFormat;
-
import java.util.Calendar;
-
import java.util.Date;
-
-
public class 各種轉換 {
-
public static void main(String[] args) throws ParseException {
-
/*
-
* 1.基本數據類型轉換
-
*/
-
//隱式轉換 byte,short,char -- int -- long -- float -- double
-
//強制轉換
-
int a = 12;
-
byte b = (byte) a;
-
-
/*
-
* 2.String StringBuilder
-
*/
-
//String to StringBuilder
-
StringBuilder sb = new StringBuilder("abcde");
-
//StringBuilder to String
-
String s = sb.toString();
-
-
/*
-
* 3.String 和 數組
-
*/
-
//String to 數組
-
String ss = "abcdefg";
-
char[] charArray = ss.toCharArray();
-
byte[] bytes = ss.getBytes();
-
//數組 to String
-
String bys = new String(bytes);
-
String chs = new String(charArray);
-
-
* 4 String 和 基本數據類型
-
//基本數據類型 to String
-
int an = 10;
-
String aa = an+ "";
-
String aa1 = String.valueOf(an);
-
-
//String to 基本數據類型
-
int bb = Integer.parseInt("123");
-
//String to int
-
char charAt = "123".charAt(0);
-
//String to char
-
-
/*
-
*5 String 大小寫轉
-
*/
-
String bigSmall = "AbCdEf";
-
String big = bigSmall.toUpperCase();
-
String small = bigSmall.toLowerCase();
-
-
/*
-
*6 自動裝箱和拆箱
-
*/
-
Integer i = 123;//自動裝箱
-
int ii = i; //自動拆箱
-
-
/*
-
*7 Date 和 String
-
-
Date d = new Date();
-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
String format = sdf.format(d);
-
//Date to String
-
Date parse = sdf.parse(format);
-
//String to Date
-
-
* 8 Date 和 Calendar
-
-
Date date = new Date();
-
Calendar cal = Calendar.getInstance();
-
Date time = cal.getTime();
-
//Calendar to Date
-
cal.setTime(date);
-
//Date to Calendar