Sometimes we are so lazy that we can’t be bothered to type things out in
Java. That’s not surprising; programmers are inherently very lazy.
Let’s say you run a zoo containing only giraffes (that’s
fine in my book, by
the way. Haha, my book. That’s funny cause we’re in my book right now.
Get it? Isn’t that hilarious? Anyway, I hate when books have entire
paragraphs inside parentheses. You forget what the original sentence was
even saying); that could be represented with this line of code:
int
numGiraffes =
23
;
Now, let’s say you just received a new giraffe at your zoo. Hooray!!! Maybe
this line of code is executed:
numGiraffes = numGiraffes +
1
;
Wonderful! But wait, papa Java is knocking at the door. There’s a shorter
way to write this for essentially no reason! How? Like this!!
numGiraffes++;
Wow! That’s shorthand
for the same line of code, saying “Take the current
value of
numGiraffes
, increase it by 1, and set
numGiraffes
equal to that
value.”
How insanely useful is that?!?! Knocks your socks right off!
Is that only for addition?
Unsurprisingly to those of us with functioning neural passageways in our
craniums, there are other fancy talk operators like the above addition one.
A
giraffe passes away, decrease by 1…
numGiraffes--;
Triplets are born, increase by 3…
numGiraffes +=
3
;
Half of the giraffe population is culled, divide by 2…
numGiraffes /=
2
;
The giraffes are cloned, multiply by 2…
numGiraffes *=
2
;
This is how we’d say that last one out loud:
“assign to numGiraffes the current value of numGiraffes times 2.”
In all honesty, I typically
do not recommend using these, except maybe the
++ and -- ones.
I PERSONALLY (
opinion alert!! ) find writing out the actual mathematical
operation to be easier to understand. Remember that you should primarily
write your code to understood by a human; your
future self and other team
members will appreciate it.
King boolean
Remember when I went over the exclamation point (!) and how it basically
is saying “not”?
So “!=” is checking if a value is “not equal to” another value?
There’s an easier way to write this in Java if you’re simply trying to flip
something from true to false (boolean values), or vice versa.
For example, instead of something like this:
boolean isBad = isGood != true ;
You could simply say
boolean isBad = !isGood ;
The exclamation point goes directly in front of the boolean. Wow again!!
The other operators…
Not even gonna go over them. If you want to learn about bitwise, shift, or
the
ternary operators, look for a more advanced piece of material. Or
encourage me to write another book. Winky face.
CHAPTER 6:
CONDITIONALS
“It’s time to get funky.” – DJ Casper
Most times your code can’t simply run top to bottom,
statement after
statement, and do anything useful. You need your code to do something
different based on what the user typed in, or what products you have in
stock, or what version of Android you’re running on, etc.
Behold, the might
if statement:
Do'stlaringiz bilan baham: