It's necessary to use a postfix delimiter to denote the type of constant being used in the source code, like L for long. However, for shorts and bytes there are no delimiters, so I need to explicitly cast the constant value like so:
short x = (short)0x8000;
I was wondering if Java takes extra steps in the compiled bytecode to actually convert this from an integer type to a short, or does it know that this will fit into a word and use the constant as is? Otherwise, is there a way I can postfix numbers like these to denote short or byte?
I was wondering if Java takes extra steps in the compiled bytecode to actually convert this from an integer type to a short, or does it know that this will fit into a word and use the constant as is?
I think it knows that it will fit into a word and uses it as is. For instance bytecode for:
public class IntToShortByteCode {
public static void main(String... args){
short x = (short)0x8888;
System.out.println(x);
}
}
is (javac 1.6.0_14):
Compiled from "IntToShortByteCode.java"
public class IntToShortByteCode extends java.lang.Object{
public IntToShortByteCode();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: sipush -30584
3: istore_1
4: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
7: iload_1
8: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
11: return
}
Otherwise, is there a way I can postfix numbers like these to denote short or byte?
No.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With