public class Numero {
public static void main(String[] args){
int i = 7;
byte b = i;
}
}
Javac:
Numero.java:4: possible loss of precision
byte b = i;
^
required: byte
found: int
1 error
—————————————————————————
public class Numero {
public static void main(String[] args){
final int i = 7;
byte b = i;
}
}
Javac:
ok
—————————————————————————
public class Numero {
public static void main(String[] args){
final int i;
i = 7;
byte b = i;
}
}
Javac:
Numero.java:5: possible loss of precision
byte b = i;
^
required: byte
found: int
1 error
O que muda do primeiro para o segundo código é que a variável i (no segundo caso) é declarada como ‘final’ e é atribuida um valor. Portanto, para o compilador ela é um constante em tempo de compilação.
Veja:
Arup when you define a field as final and assign it a value with the declaration, then it becomes a compile time constant. They get special treatment by the compiler. They can be used in case labels, assigned to a smaller datatype if in range etc. This is because they actually act like literals. When the compiler compiles the class, it replaces the name of the final field with the actual value of the final field.
Colado de <
Detalhezinho chato de entender…
GostarGostar