您的位置:首页 > 编程语言 > Java开发

Java的各种类型转换的例子

2012-02-21 14:04 471 查看
这个类根据课堂的练习所做的,目的在于通过认识数据类型

public class ExerciseQuestion {

/**
* @param args
*/
static int b1 = 0;
static long  b2 = 1000;
static float b3 = 3.4f;//*如果不加f会出错。
static double b4 = 34.45;
static char b5 = '4';
static boolean b6 = true;

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
System.out.println(b5);
System.out.println(b6);
}

}

这个类根据课堂的练习所做的,这个题目是为了验证一些类型转换

 

public class ExerciseQuestion {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
byte a1 = 126,a2 = (byte)256,a3 = 'A';
System.out.println("a1="+a1+"\ta2="+a2+"\ta3="+a3);

int b1 = 12345,b2 =(int)123456789000L,b3 = '0',b4 = 0xff;
System.out.println("b1="+b1+"\tb2="+b2+"\tb3="+b3+"\tb4="+b4);

char c1 = 'a',c2= 98,c3='\u0043',c4='\n';
System.out.println("c1="+c1+"\tc2="+c2+c4+"c3="+c3);
}

}

这个题目主要是来研究object跟各种类型之间的关系。

public class ExerciseQuestion {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
Object o1 = 100;
Object o2 = 100.0;
Object o3 = 100.0f;
Object o4 = 'O';
Object o5 = "OBJECT";

//		int a1 = o1;
//		double a2 = o2;
//		float a3 = o3;
//		char a4 = o4;
//		String a5 = o5;
//object不能直接转换成其他类型。
//		int a1 = (int)o1;
//		double a2 = (double)o2;
//		float a3 = (float)o3;
//		char a4 = (char)o4;
String a5 = (String)o5;
//object除了stirng之外其他都不能强制类型转换。
String a6 = o5.toString();

}

}


这个题目是研究double  float int 类型的转换

public class ExerciseQuestion {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
double d = 100.0;
float  f = 100.0f;
int    n = 100;

float f1 = (float) d;
float f2 = n;

double d1 = f;
double d2 = n;

int  n1  =(int) d;
int  n2  =(int) f;

}

}


这个题目是研究char跟其他类型的转换

public class ExerciseQuestion {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
char  c = 'c';

int  n = c;
float f = c;
float d = c;

System.out.println(n);
System.out.println(f);
System.out.println(d);
}
}


这个题目是研究string跟其他类型的转换。

public class ExerciseQuestion {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "1";

//		int n1 = s;
//		int n2 = (int)s;
int n3 = Integer.parseInt(s);
int n4 = Integer.valueOf(s);
System.out.println(n3);//如果s是字母会有java.lang.NumberFormatException错误。数字就不会,如“1”
System.out.println(n4);//同上

double d1 = Double.parseDouble(s);
double d2 = Double.valueOf(s);
System.out.println(d1);
System.out.println(d2);

float f1 = Float.parseFloat(s);
float f2 = Float.valueOf(s);
System.out.println(f1);
System.out.println(f2);

}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string float class object c