25. What is the result when you compile and run the following code? byte Byte = 10; byte Double = 12; byte Integer = Byte * Double; A) 120; B) Compile time error while declaring variables C) Compile time error while multiplication D) None of the above Answer 25: C) Compile time error while multiplication Explanation: This does not compile because according to the arithmetic promotion rules, the * ( multiplication ) represents binary operator. There are four rules apply for binary operators. If one operand is float,double,long then other operand is converted to float,double,long else the both operands are converted to int data type. So in our example we are trying put integer into byte which is illegal. ------------- i have got two questions 1.can we declare variable with initial uppercase letter?like byte Byte=10? 2.i dont know yet why c is correct ans?could anyone give me further explanation for it?
answer to the first question.. 1. yes you can define variable names with the first character upper case but it is considered bad coding style. 2. to answer your second question byte, short, char are all converted to int to do any operation (eg multplication, division, bit manipulations). The result of multiplying a int with a int is going to be atleast a int and thats being assigned to a byte. A int is 32 bits long whereas a byte is just 8 bits long. Thus the compiler is going to give a compilation error. Hope this helps Anand
Hi Wei Liu Q1 Yes, you can declare variable identifiers starting with initial upper case letters. Both double and byte are keywords but as Java is case sensitive Byte and Double are not. Q2. The question is really testing how well we understand how primitives are promoted when they are used in numeric operations. The convention is that both operands are promoted to int, unless one of them is broader than an int in which case the narrower operand is promoted to that. So, in this case both operands are bytes so they are both promoted to ints and then multiplied giving an int value of 120. This is then assigned to a variable identifier Integer which is declared to be a byte and the compiler complains at this. In order to get the code to compile then either Integer should be declared to be an int or the result of the multiplication of Byte and Double needs to be cast to a byte. That's how I understand it anyway. hth Simon