JAV基础语法之---数据类型转换

数制转换":

1、string 转 byte[]

String str = "Hello";
byte[] srtbyte = str.getBytes();

2、byte[] 转 string

byte[] srtbyte;
String res = new String(srtbyte);
System.out.println(res);

3、设定编码方式相互转换

String str = "hello";
byte[] srtbyte = null;
try {
    srtbyte = str.getBytes("UTF-8");
    String res = new String(srtbyte,"UTF-8");
    System.out.println(res);
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

数据类型的转换
  Java是一种强类型的语言,在赋值和参数传递时,都要求类型的匹配。类型转换有三种情况:自动转换、强制转换和使用类的方法转换。
自动转换:往往低精度类型到高精度类型能自动转换。
  如: 
  byte b1=10, b2=20;
  int b3=b1+b2;
强制转换:高精度类型到低精度类型必须强制转换。这时数据可能会丢失部分信息。
  如:char key=(char)(12+55) //变量key被赋值为unicode值为67的字符'c'
方法转换:如
  String str = "123";
  int a = Integer.parseInt(str);
  使用Integer类的方法parseInt将String转换为对应的整数。


如何将字串 String 转换成整数 int? 
A. 有两个方法: 
1). int i = Integer.parseInt([String]); 或 
i = Integer.parseInt([String],[int radix]);
 
2). int i = Integer.valueOf(my_str).intValue();
 
注: 字串转成 Double, Float, Long 的方法大同小异.
 

2 如何将整数 int 转换成字串 String ? 

A. 有叁种方法: 
1.) String s = String.valueOf(i); 
2.) String s = Integer.toString(i); 
3.) String s = "" + i;
 
注: Double, Float, Long 转成字串的方法大同小异.
JAVA中常用数据类型转换函数 
虽然都能在JAVA API中找到,整理一下做个备份。
 
string->byte
Byte static byte parseByte(String s) 
 
byte->string 
Byte static String toString(byte b)
 
char->string 
Character static String to String (char c)
 
string->Short 
Short static Short parseShort(String s)
 
Short->String 
Short static String toString(Short s)
 
String->Integer 
Integer static int parseInt(String s)
 
Integer->String 
Integer static String tostring(int i)
 
String->Long 
Long static long parseLong(String s)
 
Long->String 
Long static String toString(Long i)
 
String->Float 
Float static float parseFloat(String s)
 
Float->String 
Float static String toString(float f)
 
String->Double 
Double static double parseDouble(String s)
 
Double->String
Double static String toString(Double)
原文地址:https://www.cnblogs.com/wujixing/p/5472823.html