一直听到两种说法,一种是说没有特定的类型,一种是说int,写了个程序,觉得两种说法都有问题
public class TestOverload
{
public static void main(String[] args)
{
Compare c = new Compare();
c.max(1, 1);//打印结果为"int max",说明默认是int
short s = 1;//无错,说明int可以隐式转成short
int i = 1;
s = i;//报错,说明int不可以隐式转成short
}
}class Compare
{
public void max(short a, short b)
{
System.out.println("short max");
}
public void max(int a, int b)
{
System.out.println("int max");
}
}
public class TestOverload
{
public static void main(String[] args)
{
Compare c = new Compare();
c.max(1, 1);//打印结果为"int max",说明默认是int
short s = 1;//无错,说明int可以隐式转成short
int i = 1;
s = i;//报错,说明int不可以隐式转成short
}
}class Compare
{
public void max(short a, short b)
{
System.out.println("short max");
}
public void max(int a, int b)
{
System.out.println("int max");
}
}
只能低级别向高级别转化,不会丢失精度。
如果是变量就要强式转化
int i=1;
s=i;这个就是变量之间转化
public static void main(String[] args) {
short s = 12; // narrow 12 to short
float f = s; // widen short to float
System.out.println("f=" + f);
char c = '\u0123';
long l = c; // widen char to long
System.out.println("l=0x" + Long.toString(l,16));
f = 1.23f;
double d = f; // widen float to double
System.out.println("d=" + d);
}
}It produces the following output:f=12.0
l=0x123
d=1.2300000190734863The following test, however, produces compile-time errors:class Test {
public static void main(String[] args) {
short s = 123;
char c = s; // error: would require cast
s = c; // error: would require cast
}
}because not all short values are char values, and neither are all char values short values.参考:java language specification,CHAPTER 5 Conversions and Promotions