1.关键字switch可以作用在以下哪些数据类型上?
A. int B. char C. string D. byte E. long F. short
答案:在switch(expr1)中,expr1只能是一个整数表达式或者枚举常量(更大字体)。整数表达式可以是int基本类型或者是Integer包装类型;由于byte,short,char都可以隐含转换为int所以这些类型以及这些类型的包装类型都可以作为switch的表达式。而,long和String类型则不符合switch的语法规定且无法被隐式转换为int类型。所以它们不能作用于switch语句中。答案是 A B D F
bonus:(参考:http://mrwlh.blog.51cto.com/2238823/1109364)
public class test {
public static void main(String[] args){
byte a = 127;
//byte a = 128;此时报错
System.out.println(a);
}
}
byte的取值范围是-128~127.(int也类似,不是从0开始的)
java中类型转化问题(低精度向高精度转换)即byte/short/char转换为int
byte b = 2,e = 3;
byte f = b + e;//产生编译的错误,因为无法隐式将int转为byte.
应该改为byte b = 2, e = 3;byte f = (byte)(b + e);//注意括号的位置
对于short s1 = 1,s1 = s1 + 1;//编译器提示强制转换类型的错误。在加法的时候会转为int处理,而int 无法隐式转换为short
而short s = 1;s += 1;//是正确的,因为+= 是java语言规定的运算符,java编译器会对它进行特殊的处理,因此可以正确编译。
总结:
java会将short / byte / char4种类型数运算后的结果自动转换为int类型因为int的范围比它们都大。
再考虑byte的转换问题:
public class test {
public static void main(String[] args){
byte a = 127;
byte b = 2;
byte f = (byte) (a + b);
System.out.println(f);
}
}
输出结果是-127
网络定义:
import java.io.*;
public class test {
public static void main(String[] args)throws Exception{
int i = 65535;
byte[] b = intToByteArray(i);
for(byte bb : b){
System.out.println(bb + " ");
}
}
public static byte[] intToByteArray(int i){
byte[] result = new byte[4];//int32byte8
result[0] = (byte)((i >> 24) & 0xFF);//不改变i的值,向右移24位,相当于除去2的24次方
result[1] = (byte)((i >> 16) & 0xFF);//& 按位与计算
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)((i & 0xFF));
return result;
}
public static byte[] intToByteArray2(int i)throws Exception{
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(i);
byte[] b = buf.toByteArray();
out.close();
buf.close();
return b;
}
}