简体   繁体   English

如果Java方法的返回类型是int,那么该方法是否可以返回byte类型的值?

[英]If a Java method's return type is int, can the method return a value of type byte?

I'm preparing myself for the Java SE 7 Programmer I exam ( 1Z0-803 ) by reading a book called OCA Java SE 7 Programmer I Certification Guide . 我正在通过阅读一本名为OCA Java SE 7 Programmer I认证指南的书来为Java SE 7程序员I考试( 1Z0-803 )做准备。 This book has a numerous amount of flaws in it despite the author having 12 years of experience with Java programming and despite a technical proofreader, presumably on a salary. 尽管作者在Java编程方面有12年的经验,并且尽管有技术校对员,但可能是薪水,但本书中存在大量的缺陷。

There is one thing though that makes me insecure. 有一件事让我不安全。 The author says on page 168 that this statement is true: 作者在第168页上说这句话是真的:

If the return type of a method is int , the method can return a value of type byte . 如果方法的返回类型是int ,则该方法可以返回byte类型的值。

Well I argue differently and need your help. 好吧,我争论不同,需要你的帮助。 Take this piece of code for an example: 以这段代码为例:

public static void main(String[] args)
{
    // This line won't compile ("possible loss of precision"):
    byte line1 = returnByte();

    // compiles:
    int line2 = returnByte();

    // compiles too, we "accept" the risk of precision loss:
    byte line3 = (byte) returnByte();
}

public static int returnByte()
{
    byte b = 1;
    return b;
}

Obviously, the compiler do not complain about a different return type int in the returnByte() method signature and what we actually do return at the end of the method implementation: a byte. 显然,编译器不会在returnByte()方法签名中抱怨不同的返回类型int,以及我们在方法实现结束时实际返回的内容:一个字节。 The byte uses fewer bits (8) than the int (32) and will be cast to an int without the risk of a precision loss. 该字节比int(32)使用更少的位(8),并且将被转换为int而不存在精度损失的风险。 But the returned value is and will always be an integer! 但返回的值是,并且将始终是一个整数! Or am I wrong? 还是我错了? What would you have answered on the exam? 你在考试中会得到什么回答?

I'm not totally sure what the actual return type is, since this statement in the book is said to be true. 我不完全确定实际的返回类型是什么,因为书中的这句话被认为是真的。 Is the cast happening at the end of our method implementation or is the cast happening back in the main method just before assignment? 演员是否在我们的方法实现结束时发生,或者是在赋值之前在main方法中发生的演员?

In the real world, this question would not matter as long as one understand the implicit casting and the risk of losing precision. 在现实世界中,只要理解隐式铸造和失去精度的风险,这个问题就不重要了。 But since this is just one of those questions that might popup on the exam, I'd love to know the technically correct answer to the question. 但由于这只是考试中可能出现的问题之一,我很想知道问题的技术上正确的答案。

Clarification! 澄清!

The majority of the answers seem to think that I want to know whether one can cast a byte to an int and what happens then. 大多数答案似乎都认为我想知道是否可以将一个byte转换为int ,然后会发生什么。 Well, that is not the question. 嗯,这不是问题。 I'm asking what the returned type is. 我问的是返回的类型是什么。 In other words, is the author's quoted statement right or wrong ? 换句话说,作者的引用陈述是对还是错 Does the cast to an int happen before or after the returnByte() method actually returns? 转换为int是否发生 returnByte()方法实际返回之前或之后 If this was the real exam and you would have got the question, what would you have answered? 如果这是真正的考试,你会有问题,你会回答什么?

Please see line1 in my code snippet. 请参阅我的代码段中的第1行。 If what the author say is right, that line would have compiled as the returned value would have been a byte. 如果作者说的是对的,该行将被编译,因为返回的值将是一个字节。 But it does not compile, the rules of type promotion says that we risk loosing precision if we try to squeeze an int into a byte. 但是它没有编译,类型提升的规则说如果我们试图将int压缩到一个字节中,我们就会冒失去精度的风险。 For me, that is a proof that the returned value is an integer. 对我来说,这证明了返回的值是一个整数。

Yes, you can do that. 是的,你可以这么做。

  • The value of the byte expression will be promoted to int before it is returned. 在返回之前, byte表达式的值将被提升为int

  • The actual return type is as declared in the method signature - int . 实际的返回类型是在方法签名 - int声明的。

IMO, what the author of that book wrote is more or less correct. 国际海事组织,这本书的作者写的或多或少是正确的。 He just left out explaining the bit about the byte-to-int promotion that happens in the return statement when you "return a byte". 当你“返回一个字节”时,他只是在解释有关return语句中发生的字节到字的提升的问题。

Is the cast happening at the end of our method implementation or is the cast happening back in the main method just before assignment? 演员是否在我们的方法实现结束时发生,或者是在赋值之前在main方法中发生的演员?

The cast (promotion) happens in the returnByte method. returnByte (促销)发生在returnByte方法中。

In the real world, this question would not matter as long as one understand the implicit casting and the risk of losing precision. 在现实世界中,只要理解隐式铸造和失去精度的风险,这个问题就不重要了。

There is no loss of precision in promoting a byte to an int . byte提升为int不会有精度损失。 If the types were different, there could be loss of precision, but (hypothetically) the loss of precision would be the same wherever the promotion is performed. 如果类型不同,可能会失去精确度,但(假设)精确度的损失在执行促销的任何地方都是相同的。


The section of the JLS that deals with this is JLS 14.17, which says that the return expression must assignable to the method's declared return type. 处理此问题的JLS部分是JLS 14.17,它表示return表达式必须可分配给方法声明的返回类型。 It doesn't explicitly state that the promotion is done in the method, but it is implied. 它没有明确声明促销是在方法中完成的,但它是隐含的。 Furthermore, it is the only practical way to implement this. 此外,它是实现这一目标的唯一实用方法。

If (hypothetically) the conversion was done in the calling method (eg main ), then: 如果(假设)转换是在调用方法(例如main )中完成的,那么:

  • The compiler would need to know what the return statement is doing. 编译器需要知道return语句正在做什么。 This is not possible, given that Java classes can be compiled separately. 考虑到Java类可以单独编译,这是不可能的。
  • The compiler would need to know which actual method is going to be called. 编译器需要知道将调用哪个实际方法。 This is not possible if the method is overridden. 如果重写该方法,则无法执行此操作。
  • If the method contained two (or more) return statements with expressions that have different types, then the compiler needs to know which return will be executed. 如果该方法包含两个(或多个)具有不同类型的表达式的return语句,则编译器需要知道将执行哪个return This is impossible. 这是不可能的。

If this was the real exam and you would have got the question, what would you have answered? 如果这是真正的考试,你会有问题,你会回答什么?

I would have answered ... "it depends" ... and proceeded to the alternative viewpoints. 我会回答......“这取决于......”并继续进行另类观点。

Technically speaking the method is returning an int , but the return statement can take any expression whose type can be converted to an int . 从技术上讲,该方法返回一个int ,但return语句可以采用任何类型可以转换为int表达式。

But if someone said to me that the method is returning a byte , I would understand what they meant. 但如果有人对我说这个方法返回一个byte ,我就会理解它们的含义。


Also, as far as i know methods/function use stacks for storage.etc and inside those stacks they store the return addresses not what (type) they are returning to. 另外,据我所知,方法/函数使用stack.etc的堆栈,在这些堆栈中,它们存储的返回地址不是它们返回的(类型)。 So, again the ambiguity arises (at least for me). 所以,再次出现歧义(至少对我而言)。 Please correct me if I am wrong. 如果我错了,请纠正我。

Yes, technically a method doesn't return a type. 是的,从技术上讲,方法不会返回类型。 (Not even if it returns a Type object. That is an object that denotes a type, not the type itself.) But everyone and his dog would happily say "the returnByte methods returns type int". (即使它返回一个Type对象也没有。这是一个表示类型的对象,而不是类型本身。)但是每个人和他的狗都会高兴地说“returnByte方法返回类型int”。

So, if you are going to be pedantic, then yes it is ambiguous. 所以,如果你要迂腐,那么是的,它是模棱两可的。 But the solution is to not be pedantic. 但解决方案是不要迂腐。

我很确定它与执行myInt << 24相同,得到最后的8位,因此如果整数超过255(2 ^ 8),则即将失去精度。

Yes the statement is valid. 是的,该声明是有效的。 A byte will always fit into an int comfortably. 一个byte总是很容易适合int

byte => int //no precision loss
int  => byte //precision loss

But if you are doing: 但如果你这样做:

byte => int => byte //you won't lose any data

Which is what you are doing. 这是你在做什么。 Does that help? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM