概述
java的基本数据类型:short, int, long, float, double, char,string
对应的包装类型:Short, Integer, Long, Float, Double, Character, String
基本数据类型和String之间的转换:toString()
1. int to string:
String s = Integer.toString(int n);
2. short to string
String s = Short.toString(short n);
3. long to string
String s = Long.toString(Long n);
4. float to string
String s = Float.toString(Float f)
5. double to string
String s = Double.toString(Double n);
String to 基本数据类型:parsexxx(), valueOf()
1. string to int
int n = Integer.parseInt(String s);
int n = Interget.valueOf(String s);
2. String to short
short n = Short.parseShort(String s);
short n = Short.valueOf(String s);
3. String to long
long n = Long.parseLong(String s);
long n = Long.valueOf(String s);
4. String to float
float n = Float.parseFloar(String s);
float f = Float.valueOf(String s);
5. String to double
double d = Double.parseDouble(String s);
double d = Double.valueOf(String s);
char to int:
1. 利用char的Unicode编码规则
char c = '8';
int n = c -48;
2. 用Integer.parseInt()
Character ch = '8';
int n = Interget.parseInt(c.toString());
int to char:
int n = 8;
char c = (char)(n+48);
package cn.Sandy.Review;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
/**
* String to short/int/long/float/double
*/
String s = "8";
int i = Integer.parseInt(s); //string to int
long l = Long.parseLong(s); //string to long
short sh = Short.parseShort(s); //string to short
float f = Float.parseFloat(s); //string to float
double d = Double.parseDouble(s); //string to double
System.out.println(i);
System.out.println(l);
System.out.println(sh);
System.out.println(f);
System.out.println(d);
/**
* short/int/long/float/double types to string
*/
short sho = 12345;
String sint = Integer.toString(8); // int to string
String sshort = Short.toString(sho); //short to string
String slong = Long.toString(1234562222); //long to string
String sf = Float.toString(3.0f); // float to string
String sd = Double.toString(20.22d); //double to string
System.out.println(sint);
System.out.println(sshort);
System.out.println(slong);
System.out.println(sf);
System.out.println(sd);
/*
* char to int and int to char
*/
int num = 8;
char ch1 = (char)(num + 48); //利用char的unicode编码
System.out.println(ch1);
Character ch2 = '8';//char是基本的数据类型, Character是包装类型
int mun1 = Integer.parseInt(ch2.toString());
System.out.println(ch2);
}
}
最后
以上就是仁爱小白菜为你收集整理的java 原生数据类型的转换_java数据类型之间的转换的全部内容,希望文章能够帮你解决java 原生数据类型的转换_java数据类型之间的转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复