于是前几天开始学习java,遇到一个问题。对于下一个表达式:
String foo=123;
不允许。但是,在 中System.out.printIn(),我们可以使用类似的东西:
int x=5;
System.out.println(x);
由于不允许将整数隐式分配给字符串,为什么上面的表达式有效?谁能给个详细的解释?我也想知道我们什么时候可以使用这种隐含的东西,什么时候不能。
于是前几天开始学习java,遇到一个问题。对于下一个表达式:
String foo=123;
不允许。但是,在 中System.out.printIn(),我们可以使用类似的东西:
int x=5;
System.out.println(x);
由于不允许将整数隐式分配给字符串,为什么上面的表达式有效?谁能给个详细的解释?我也想知道我们什么时候可以使用这种隐含的东西,什么时候不能。
您可以使用整数调用 println 的原因是该方法已重载。基本上有不止一种称为 println 的方法,其中一种接受整数。
看看这里:PrintStream
PrintStream 有很多重载方法System.out:
println(boolean x)
println(char x)
println(int x)
println(long x)
println(float x)
println(double x)
println(char x[])
println(String x)
println(Object x)
out类的静态成员System是一个PrintStream带有签名的方法println(int)。
查看PrintStream( System.outis a PrintStream) 的 API。它有方法println(), println(boolean), println(char), println(char[]), println(double), println(float), println(int), println(long),println(Object)和println(String)。这称为方法重载(向下滚动以找到有关方法重载的部分)。
如果您想String从整数文字创建 a,您可以在它周围加上引号 ( String s = "123";) 或使用Integer.toString( String s = Integer.toString(123);) 或String.valueOf( String s = String.valueOf(123);)。
Im assuming you mean't println not printin , java has a println function for each datatype, so you can call println on booleans, ints, strings, ect and it will select the right function. of course you cannot assign an integer to a string variable because they are different types.