小结:
我在jshell跑了一下,详细信息太多了,需要再回来查。
5.0 Conversions and Contexts
类型转换,因为java是强类型语言。
- 数值类型:
不同类型的字节长度,拓宽可以自动做,缩窄需要强制转换。
//Example 5.0-2. Conversions In Various Contexts
jshell> int i = (int)12.5f
i ==> 12
jshell> float f = i
f ==> 12.0
jshell> f * i
$69 ==> 144.0
jshell> double d = Math.sin(f)
d ==> -0.5365729180004349
5.1 Kinds of Conversion
5.1.2 Widening Primitive Conversion
- 扩展的原始转换不会丢失有关整体的信息在下列情况下数值的大小,其中数值为完全保留. (拓宽)
- 反之,不能保证精度。
jshell> int big = 1234567890
big ==> 1234567890
jshell> float bigF = big
bigF ==> 1.23456794E9
//following will use float for big and bigF automactically
jshell> big - bigF
$73 ==> 0.0
//(int) will lost precision
jshell> big - (int)bigF
$74 ==> -46
5.1.3 Narrowing Primitive Conversion
精度下降的强制类型转换,可能会损失信息。(类似有损压缩)
我觉得最快的是直接在jshll试试,不用记,而且最好不要这样做。
//Example 5.1.3-1. Narrowing Primitive Conversion
jshell> Float.NEGATIVE_INFINITY
$1 ==> -Infinity
jshell> Float.POSITIVE_INFINITY
$2 ==> Infinity
jshell> Float.POSITIVE_INFINITY + Float.NEGATIVE_INFINITY
$3 ==> NaN
//Example 5.1.3-2. Narrowing Primitive Conversions that lose information
(short)0x12345678==0x5678
(byte)255==-1
(int)1e20f==2147483647
(int)NaN==0
(float)-1e100==-Infinity
(float)1e-50==0.0
5.2 Assignment Contexts
注意类型是否兼容。
//Example 5.2-1. Assignment for Primitive Types
jshell> short s = 123
s ==> 123
jshell> char c = s
| 错误:
| 不兼容的类型: 从short转换到char可能会有损失
| char c = s;
| ^
jshell> s = c
| 错误:
| 找不到符号
| 符号: 变量 c
| 位置: 类
| s = c
//Example 5.2-2. Assignment for Reference Types
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
public String toString() { return "("+x+","+y+")"; }
}
interface Colorable { void setColor(int color); }
class ColoredPoint extends Point implements Colorable {
int color;
ColoredPoint(int x, int y, int color) {
super(x, y); setColor(color);
}
public void setColor(int color) { this.color = color; }
public String toString() {
return super.toString() + "@" + color;
}
}
//test
jshell> Point[] pa = new ColoredPoint(
jshell> Point[] pa = new ColoredPoint[4]
pa ==> ColoredPoint[4] { null, null, null, null }
jshell> pa[0] = new ColoredPoint(2,2,12)
$19 ==> (2,2)@12
jshell> pa[1] = new ColoredPoint(4,5,24)
$20 ==> (4,5)@24
jshell> ColoredPoint[] cpa = (ColoredPoint[])pa;
cpa ==> ColoredPoint[4] { (2,2)@12, (4,5)@24, null, null }
5.6.1 Unary Numeric Promotion
一些运算符将单一数字提升应用于单个操作数,这必须是
生成数值类型的值。
学习中 2018.7.9
《The Java® Language Specification Java SE 10 Edition》
absolute page 111 - 149