Friday, February 4, 2011

Chapter 22: Assignment Operators

Assignment operators are those that are used to assign values to variables. Simply saying the equal to operator "=" is the assignment operator.

We covered most of the functionality of the assignment operator, “=”, in our chapter on Literals and Variable assignments. To summarize:
• When assigning a value to a primitive, size matters. Be sure you know when implicit casting will occur, when explicit casting is necessary, and when truncation might occur.
• Remember that a reference variable isn’t an object; it’s a way to get to an object. (We know all you C++ programmers are just dying for us to say “it’s a pointer”, but we’re not going to.)
• When assigning a value to a reference variable, type matters. Remember the rules for supertypes, subtypes, and arrays.

Exam Tip:
Topics like bit shifting operators, bitwise operators, two’s complement and divide by zero are not part of the SCJP 5 exam. I am not saying these are not important topics in Java. Actually they are very important but from the SCJP exam perspective they are not part of the syllabus, so don’t waste time reading them.

Compound Assignment Operators

There are actually 11 or so compound assignment operators, but only the four most commonly used (+=, -=, *=, and /=), are on the exam. The compound assignment operators let lazy programmers shave a few keystrokes off their workload. Here are several example assignments, first without using a compound operator,
y = y - 6;
x = x + 2 * 5;

Now, with compound operators:
y -= 6;
x += 2 * 5;

The last two assignments give the same result as the first two.

Exam Tip:
Earlier versions of the exam put big emphasis on operator precedence (like: What’s the result of: x = y++ + ++x/z;). Other than a very basic knowledge of precedence (such as: * and / are higher precedence than + and -), you won’t need to study operator precedence, except that when using a compound operator, the expression on the right side of the = will always be evaluated first. For example, you might expect
x *= 2 + 5;

to be evaluated like this:
x = (x * 2) + 5; // incorrect precedence

since multiplication has higher precedence than addition. But instead, the expression on the right is always placed inside parentheses. it is evaluated like this:
x = x * (2 + 5);

Previous Chapter: Self Test - Chapters 15 to 21

Next Chapter: Chapter 23 - Relational Operators

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers