小結(jié):
我在jshell跑了一下,詳細(xì)信息太多了杰捂,需要再回來查舆床。
5.0 Conversions and Contexts
類型轉(zhuǎn)換,因為java是強類型語言挨队。
- 數(shù)值類型:
不同類型的字節(jié)長度谷暮,拓寬可以自動做,縮窄需要強制轉(zhuǎn)換盛垦。
//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
- 擴展的原始轉(zhuǎn)換不會丟失有關(guān)整體的信息在下列情況下數(shù)值的大小湿弦,其中數(shù)值為完全保留. (拓寬)
- 反之省撑,不能保證精度竟秫。
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
精度下降的強制類型轉(zhuǎn)換愕提,可能會損失信息纽谒。(類似有損壓縮)
我覺得最快的是直接在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轉(zhuǎn)換到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
一些運算符將單一數(shù)字提升應(yīng)用于單個操作數(shù)润梯,這必須是
生成數(shù)值類型的值。
學(xué)習(xí)中 2018.7.9
《The Java? Language Specification Java SE 10 Edition》
absolute page 111 - 149