People associate computers with math, and that association is certainly warranted. A lot of code involves explicitly doing math, and behind the scenes, there’s even more math going on that you don’t see, but which is very important.
Let’s start learning how to do math in Java.
Create a new class. This time, let’s call it MathLesson.
public class MathLesson{
}
As before, give yourself a main method:
public class MathLesson{
public static void main (String[] args){
}
}
Now, we briefly need to take a detour from Math to look at data types.
Every variable in Java has 3 things: a name, a type, and a
value. Let’s start in plain English: “every box has a name, a thing that it can
hold, and the information in that thing.”
In Java, there are two types of variables: primitive types, and object types.
You can easily distinguish primitives from objects by the capitalization (or
not) of the names of the types.
There are exactly 8 primitive types in Java:
- int: for whole numbers between (and including) -2,147,483,648 to 2,147,483,647
- double: for decimal numbers between (and including) -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- float: for numbers with decimals between (and including) -2,147,483,648 to 2,147,483,647
- long: for whole numbers between (and including) -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- short: for whole numbers from -65536 to 65535
- byte: for whole numbers from -128 to 127
- char: for single characters, like a, {, <, and so on
- boolean: only true or false (represented like this: always all lowercase)
Anything else is not a primitive, which makes it an object. Long
sequences of characters (called a String—note the capitalization of String, so
it isn’t primitive) are one of these (as in public static void main(String[] args).
String here is an object type.
For the simple math we want to deal with here, we only need the 8 primitive
types.
In Java, we operate on the following principle: “Put what is
on the right into the ‘box’ on the left.” In grade school, you might have seen
2x + 3 = y, or y = 2x + 3. Mathematically, those are equivalent, but the “gets”
operation (called “assignment”, denoted with the equals sign—we check for
equality by another way moves right to left.
Some basic operations (always with assignment) we might want to do are:
·
add two numbers and assign the result into a
third
·
add a and b, and put the result back in a
·
multiply two numbers
·
divide two numbers
·
subtract two numbers
·
find the remainder after one number is divided
by another
·
check if two numbers are equal
Addition is represented with +, subtraction with -, multiplication
with *, division with /, and the modulus/remainder operator with %.
3 + 1 is 4
3 * 2 is 6
10 % 3 is 1 (this means that 10 divided by 3 leaves 1 left over)
3 – 2 is 1
3 / 1 is 3
Inside main, let’s declare 2 variables, x and y, and give
them the values 10 and 5.
public class MathLesson{
public static void main (String[] args){
int x = 10;
int y = 5;
}
}
Now, using the System.out.println() we learned in the last
lesson, let’s just print them out. You can pass the names of variables into
println, and it will display their values.
public class MathLesson{
public static void main (String[] args){
int x = 10;
int y = 5;
System.out.println(x);
System.out.println(y);
}
}
This, line by line: creates x, lets it store integers, and puts 10 in that box;
creates y, lets it store integers, and puts 5 in that box; then displays x (10)
to the screen and displays y (5).
Now, let’s create a few more variables, all integers: res1,
res2, res3, res4, res5.
public class MathLesson{
public static void main (String[] args){
int x = 10;
int y = 5;
System.out.println(x);
System.out.println(y);
int res1;
int res2;
int res3;
int res4;
int res5;
}
}
Now, let’s do each operation with 10 and 5, and save each
one into a different variable.
public class MathLesson{
public static void main (String[] args){
int x = 10;
int y = 5;
System.out.println(x);
System.out.println(y);
int res1;
res1 = x + y;
int res2;
res2 = x * y;
int res3;
res3 = x – y;
int res4;
res 4 = x / y;
int res5;
res5 = x % y;
}
}
Print them, just as we printed x and y, with System.out.println().
res1 will be 15, res2 will be 50, res3 will be 5, res4 will be 2, and res5 will
be 0.
Now, change all instances of int to something else (double, float, long, short, or byte) and try again.
It is common practice—and your code looks better—if you
combine declarations and assignments into one line. You can, of course, say
int res1;
res1 = x + y;
But it saves a few keystrokes and is much more common to simply say
int res1 = x + y;
The other approach, though, with split declarations and assignments, is important.
It reveals something key about variables. Once you declare them with a type,
you don’t reference them by their type again. (And since this is Java, that
type won’t change.) In this example, res1 will always be an integer. At the
moment it was created, it got the value 0 by default, but one line later, it
was assigned the value of the expression x plus y, which in this case is 10 + 5
is equal to 15.
It is perfectly reasonable, let’s say, to want to check if the result of x
times y (which we stored in res2, as above) is 100 or not. (Spoiler alert, it’s
5 times 10, which is obviously 50, which is not 100).
For this, we need two things:
1.
A variable that can store the answer to yes/no,
true/false, on/off questions—these are booleans
2.
A way to represent “checking if something is
equal” given we’ve already used one single = sign to mean “gets the value of.” The
expression x = y does not mean “x is equal to y” as in mathematics. It means “give
the variable x the value of the variable y.”
We can say, inside our main method something like the
following (after res2 has been declared – so it exists—and initialized, so it
has a non-zero/non-default value):
boolean answer = res2 == 100;
This means, in plain English, the following.
- Make me a box somewhere in memory that stores yes/no, true/false, on/off values
- Call that box “answer”
- Give it the value of “does res2 equal 100?” (false)
For clarity, you could see this:
boolean answer = (res2 == 100);
This just makes things easier on the eyes. Parentheses work just as they do in math.
That is, do the check first, then assign the value (true or false—false here)
into answer.
There is one more trivial operation I want to cover now. Going through high
school and my undergrad, I’ve probably used this 10,000 times already, and
someone with decades of experience could easily have written this 100,000 times
or more: a shortcut to add 1.
Of course, let’s say you have an integer called addToMe and it current has a
value 6. That looks like
int addToMe = 6;
If you wanted to add one to addToMe, you could certainly say
that
addToMe = addToMe + 1;
(Remember, this is not algebra class; we are not saying that 6 equals 7; we are
saying that we’re going to look in the box called addToMe, find its value, increase
it by 1, and put the new value back in that same box.)
This is perfectly valid, but there’s a much more common and elegant way to do
this in Java: by using another operator, which is ++
++ only works to add 1. (Any other number being added besides 1 must still be
in the form x = x + y;)
I can say
int addToMe = 6;
and then I can print it, and get 6.
then I can say
addToMe++;
And print it—and now the value will be 7.
If I say again, another line later,
addToMe++;
now, we are “plus-plus-ing” 7, so printing addToMe a third time would show 8. This
is more properly called “incrementing.”
Just as there is ++ to add one, there is -- to subtract one.
Now, imagine we have
int subFromMe = 10;
if we print it, we get back 10.
if we now say
subFromMe--;
and print again, we’ll see 9
This should give you a really solid base for how to do
simple math in Java. There’s more complex math coming later, don’t worry! But for
now, look at this code, try to change some values, see what happens, and
understand why! The best way to get better at Java is to practice!
No comments:
Post a Comment