I have a confusion, althouhh i've accepted but i don't find any reason for it. Consider the following code: 1) byte b1 = 1; 2) b1 += 1; // no compiler arror 3) // b1 = b1 + 1; //generates compiler error. Although statement 2 ad 3 are the 2 different forms of writing one and the same thing and also an arithmetic expression evaluates to at least an integer, i'm unable to give any reason for above code not giving an error for line 2. Anybody has an answer?
Asma Zafar,<BR>Sun Certified Programmer for Java2 Platform
Asma Remember that all arithmatic in java is done at at least ints, meaning that byte, char, and short are all promoted to ints before the operators are evaluated. In the compound assigment statements (+=, *=, %=, etc) they do not expand to be the exact same thing as you have. For example byte b=3; b *= 2; this actually is treated by the compiler as: b = (byte)(b*2); It's just one more way to make things easy for the programmer in not having to worry about explicitly casting it. There is a draw back to it however. Run this and you'll see... byte b = 100; b *= 2; System.out.println(b); When you use the long form of the expression you have to use an explicit cast to convert the result back to a byte. b = (byte)b + 100; hope that helps
Dave by the way, is this a question from a book or mock test that you've taken? If so, you should list the book and question so other people can find it if they do a search for it. If not then you might want ot move this to one of the general forums so everyone can see this. I would go with beginner (or intermediate and we might win a book!!!) [This message has been edited by Dave Vick (edited July 10, 2001).]
Joined: May 11, 2001
Thanks Dave. I took this question in a mock exam. I don't remember which it was, but i'll find out. Where should i put for general info? Asma.
Joined: May 10, 2001
You could put it under one of the general forums or under the certification study forum. From what I can gather, this forum is mainly for mistakes and corrections to the various mock exams and study guides out there. I only mentioned the intermediate forum because that is where the current book giveaway is.