問題描述
以下代碼的輸出是 123
因為 substring
從 beginIndex 到 EndIndex - 1.但是,我很驚訝 char
在這里被理解為 3 (int) 因為 substring
需要兩個整數.這背后的概念是什么?
The output from the following code is 123
because substring
takes from beginIndex to EndIndex - 1. However, I am surprised how char
here is understood as 3 (int) because substring
take two ints. What is the concept behind this?
String x = "12345";
char a = 3;
x = x.substring(0, a);
System.out.println(x);
推薦答案
這可以追溯到 C,其中 char
本質上是一種窄整數類型,并在必要時隱式轉換為 int
.
This goes all the way back to C, where char
is in essence a narrow integer type and gets implicitly converted to int
whenever necessary.
在 Java 中,這在技術上稱為擴展原語轉換",并在 JLS 的第 5.1.2 節.
In Java, this is technically known as a "widening primitive conversion", and is covered in section 5.1.2 of the JLS.
這篇關于將 char 傳遞給帶有 int 參數的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!