Java 练习题摘录
2024-08-26 03:08:35
2018-01-21 23:23:08
1、finally与return同时出现的情况
- finally中有return语句则会使try...catch中的return语句失效
public static void main(String[] args) {
System.out.print(getNumber(0));
System.out.print(getNumber(1));
System.out.print(getNumber(2));
System.out.print(getNumber(4));
} public static int getNumber(int num) {
try {
int res = 2 / num;
return res;
} catch (Exception e) {
return 0;
} finally {
if (num == 0) {
return -1;
}
if (num == 1) {
return 1;
}
}
} 输出为:-1110
- finally中对try...catch中的return语句的修改是不会产生效果的
public static void main(String[] args) {
System.out.print(getNumber(2));
} public static int getNumber(int num) {
try {
return num;
} finally {
num *= 2;
}
} 输出为:2
2、初始化静态变量--执行静态代码块--执行main方法
static int i = 6;
static {
i += 9;
} public static void main(String[] args) {
System.out.print(i);
} static {
i /= 3;
} 输出为:5
3、char,byte,short的类型转换问题
byte:
- byte 数据类型是8位、有符号的,以二进制补码表示的整数;
- 最小值是 -128(-2^7);
- 最大值是 127(2^7-1);
- 默认值是 0;
- byte 类型用在大型数组中节约空间,主要代替整数,因为 byte 变量占用的空间只有 int 类型的四分之一;
- 例子:byte a = 100,byte b = -50。
short:
- short 数据类型是 16 位、有符号的以二进制补码表示的整数
- 最小值是 -32768(-2^15);
- 最大值是 32767(2^15 - 1);
- Short 数据类型也可以像 byte 那样节省空间。一个short变量是int型变量所占空间的二分之一;
- 默认值是 0;
- 例子:short s = 1000,short r = -20000。
char:
- char类型是一个单一的 16 位 Unicode 字符;
- 最小值是 \u0000(即为0);
- 最大值是 \uffff(即为65,535);
- char 数据类型可以储存任何字符;
- 例子:char letter = 'A'。
byte,short和char会自动转换成int进行运算,这就会导致出错。
byte a1 = 2, a2 = 4, a3;
short s = 16;
a2 = s; // 出错,因为s会默认转成int,所以需要强转
a3 = a1 * a2; // a1 * a2会默认转成int,所以需要强转 但是+=是不会产生类型转换问题的:
short s;
s = s + 1; // 出错,会转成int,需要强转成short short s;
s += 1; // 正确
最新文章
- 16.2.2 Space Needed for keys
- Mac系统下使用VirtualBox虚拟机安装win7--第四步 安装虚拟机硬件扩展包支持
- 开发Android必知的工具
- Java中的TreeMap、Comparable、Comparator
- JS之事件(一)
- 在hibernate中使用c3p0数据源
- android 三目运算符 运用错误
- 解读分库分表中间件Sharding-JDBC
- 守望先锋overwatch美服外服设置方法
- System Operations on AWS - Lab 6W - Using Auto Scaling (Windows)
- lokijs
- ThinkPHP5.0相关
- 跨域两种解决方案CORS以及JSONP
- iOS启动速度优化
- 爬虫BS4—淘女郎
- 方差+标准差+四分位数+z-score公式
- centos7上设置中文字符集
- 转:C#清除回收站
- python代码打包发布
- poj3449 Geometric Shapes【计算几何】