問題描述
我正在嘗試為課程完成一些代碼:
I was trying to get some code done for class:
public int getValue(char value) {
if (value == 'y') return this.y;
else if (value == 'x') return this.x;
由于我最終可能無法返回任何東西,所以它告訴我最后要這樣做:
Since I might not be able to return anything in the end, it told me to do this at the end:
return value;
這讓我很驚訝,因?yàn)樵摲椒ǖ姆祷仡愋褪?int
類型.然而,它告訴我返回一個(gè) char
!我正在使用 eclipse,并且習(xí)慣了無窮無盡的警告和東西,這是一個(gè)重大的驚喜.
This surprised me because the return type for the method was of type int
. Yet, it was telling me to return a char
! I'm using eclipse, and accustomed to the endless number of warnings and stuff, this was a major surprise.
那么,char
真的是 int
嗎?為什么會(huì)這樣?
So, is a char
really an int
? Why is this happening?
推薦答案
Java 語言規(guī)范 狀態(tài)
當(dāng)帶有 Expression
的 return 語句出現(xiàn)在方法中時(shí)聲明,Expression
必須 可分配(第 5.2 節(jié)) 到聲明的方法的返回類型,或發(fā)生編譯時(shí)錯(cuò)誤.
When a return statement with an
Expression
appears in a method declaration, theExpression
must be assignable (§5.2) to the declared return type of the method, or a compile-time error occurs.
控制一個(gè)值是否可分配給另一個(gè)值的規(guī)則定義為
where the rules governing whether one value is assignable to another is defined as
賦值上下文允許使用以下之一:
Assignment contexts allow the use of one of the following:
- 擴(kuò)大原語轉(zhuǎn)換(§5.1.2)
和
原始類型的 19 種特定轉(zhuǎn)換稱為擴(kuò)展原始轉(zhuǎn)換:
19 specific conversions on primitive types are called the widening primitive conversions:
char
到int
、long
、float
或 `double
char
toint
,long
,float
, or `double
最后
擴(kuò)展原語轉(zhuǎn)換不會(huì)丟失有關(guān)在下列情況下,數(shù)值的總大小,其中數(shù)值被完全保留:[...]
A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly: [...]
char
到整數(shù)類型 T
的擴(kuò)展轉(zhuǎn)換將零擴(kuò)展char
值的表示以填充更寬的格式.
A widening conversion of a char
to an integral type T
zero-extends the
representation of the char
value to fill the wider format.
簡(jiǎn)而言之,作為 return
語句表達(dá)式的 char
值可通過擴(kuò)展原語轉(zhuǎn)換分配給 int
的返回類型.
In short, a char
value as the expression of a return
statement is assignable to a return type of int
through widening primitive conversion.
這篇關(guān)于Java char 也是 int 嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!