Legal Return Types

Return Primitive Types

boolean: the only type of value that can be returned is a boolean literal such as true or false. Java will not accept a boolean object, null, an integer value such as 0 or 1, or any other type.

char: a char is a 16-bit value that ranges from 0 to 65535. This meas some (but not all) integral types are legal return types for char. A negative integral number, or an integral larger than 65535 is not legal.

A good way to determine whether an integral return type is legal is to think of the number of bits that a primitive can hold. If the bits value of the return type is less than the declared return type, it is legal.

Legal Return Types for Integer and Floating-Point Numbers
Declared TypeLegal Return Type
bytebyte
shortbyte, short
intbyte, short, int, char
longbyte, short, int, long, char
floatbyte, short, int, long, float, char
doublebyte, short, int, long, float, double, char

How can a 32-bit float is capable of storing a 64-bit integer?

When float numbers get very large they begin to use exponential numbers.  if there are 19 individual digits in single number, it will give you a number x1018. No accuracy is lost with this small of a number, however. But for larger numbers, the large float loses some accuracy.

class AccuracyTest {

public static void main(String [] args) {

  long salary = Long.MAX_VALUE - 443322112233L;

  System.out.println("long is " + salary);

  float taxes = salary;

  System.out.println("float is " + taxes);

  long net = (long) taxes;

  System.out.println("New long is " + net);

}

}

for this program, the result is:

long is 9223371593532663574
float is 9.2233715E18
New long is 9223371487098961920

So float can handle large numbers, but as a banker or mathematician you would have to doubt these results. A better solution would be to use java.math.BigInteger or java.math.BigDecimal. These classes are slower to use, but they have no upper limit on numbers, and they provide most of the methods contained in the java.lang.Math class.

It is illegal for a primitive to be assigned to null. In other words, if a method declares a primitive return type, then the method may not attempt to return null.

 Object Return Types

 A method with an object return type can return the same object type, or subclass of the object, or null value.

It is also legal to have a return type that is an interface. For example, a method can use Runnable as its return type even though a Thread object is being returned. This is because Thread implements the Runnable interface.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值