問題描述
我正在嘗試為課程完成一些代碼:
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;
這讓我很驚訝,因為該方法的返回類型是 int
類型.然而,它告訴我返回一個 char
!我正在使用 eclipse,并且習慣了無窮無盡的警告和東西,這是一個重大的驚喜.
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
嗎?為什么會這樣?
So, is a char
really an int
? Why is this happening?
推薦答案
Java 語言規范 狀態
當帶有 Expression
的 return 語句出現在方法中時聲明,Expression
必須 可分配(第 5.2 節) 到聲明的方法的返回類型,或發生編譯時錯誤.
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.
控制一個值是否可分配給另一個值的規則定義為
where the rules governing whether one value is assignable to another is defined as
賦值上下文允許使用以下之一:
Assignment contexts allow the use of one of the following:
- 擴大原語轉換(§5.1.2)
和
原始類型的 19 種特定轉換稱為擴展原始轉換:
19 specific conversions on primitive types are called the widening primitive conversions:
char
到int
、long
、float
或 `double
char
toint
,long
,float
, or `double
最后
擴展原語轉換不會丟失有關在下列情況下,數值的總大小,其中數值被完全保留:[...]
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
到整數類型 T
的擴展轉換將零擴展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.
簡而言之,作為 return
語句表達式的 char
值可通過擴展原語轉換分配給 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.
這篇關于Java char 也是 int 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!