Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Байты превращаются... превращаются байты ...


Автор: Royan 23.5.2007, 10:10
Как бы сказала героиня одного мульта, - "Вот типа код. Код типа такой вот..."
Код

package main;

public class Test {
    public static void main(String[] args) {
        byte b = 3;
        byte c = 7;
        // c = b + c;
        // c = +b;
        c += b;//Компилируется почему?
    }
}


Кто может объяснить почему в закоментированных строчках появляется ошибка: Type mismatch: cannot convert from int to byte

Автор: Platon 23.5.2007, 10:27
арифметические операции раздуваются до int, не вижу ничего страшного.

Автор: Shaggie 23.5.2007, 10:34
Приводи их в byte силой!
Код

public class Test {
    public static void main(String[] args) {
        byte b = 3;
        byte c = 7;
        c = (byte) b + c;
        c = (byte) +b;
    }
}

Потому что арифметическая операция + возвращает (в данном случае) тип int, который не помещается в byte.

Автор: Stampede 23.5.2007, 10:44
Мда, хороший вопрос. Как выясняется, в спецификации Java предусмотрена такая штука как Binary numeric promotion:

Цитата

5.6.2 Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:


  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.



Источник: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983

А о том, что Binary Numeric Promotion применяется в том числе к результату арифметического сложения, говорится здесь:

Цитата

15.18.2 Additive Operators (+ and -) for Numeric Types
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The binary - operator performs subtraction, producing the difference of two numeric operands.

Binary numeric promotion is performed on the operands (§5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.


Источник: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.2

Вот так вота, век живи - век учись smile Я вот тоже не знал, так что спасибо за интересный пример.

Автор: batigoal 23.5.2007, 12:39
Royan, если у тебя в первом слагаемом будет 110, а во втором - 120, то ты выйдешь за пределы byte. Поэтому и не разрешается это.

Автор: nornad 23.5.2007, 13:45
Цитата(batigoal @  23.5.2007,  15:39 Найти цитируемый пост)
Royan, если у тебя в первом слагаемом будет 110, а во втором - 120, то ты выйдешь за пределы byte. Поэтому и не разрешается это. 

Странное объяснение, право слово. А что мешает сделать такую же ситуацию для int? Его же из-за теоретической возможности такой ситуации не запрещают складывать.

Автор: batigoal 23.5.2007, 13:49
А потому что предел все равно есть smile

Автор: Royan 23.5.2007, 14:40
Почему не компилируются строки 7 и 8 благдаря Stampede, стало понятно, а почему компилируется c += b;? Поискал вот тут 
http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html ответа не нашел :(

Автор: powerOn 23.5.2007, 15:48
да все потому что данная конструкция эквивалентна такой:
Код

с = (byte) ((int) с + (int) b);


это называется неявное сужение. Опереации неявного сужения происходят для *= , +=,  -=, /=, %=.

Автор: Royan 23.5.2007, 16:07
а как неявное сужение по английски?

Автор: Maksym 23.5.2007, 16:15
implicit narrowing

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)