-
Notifications
You must be signed in to change notification settings - Fork 2
3) Math and Variables
Basic math includes addition (a + b), subtraction (a - b), multiplication (a * b), and division (a / b). Other primitive operations also include the modulus (a % b) operator, an important tool for finding divisibility. Other more advanced functions, such as trigonometry, exponentiation, and even rounding, are found in the Math library, and we will cover how to use libraries in a later section.
Yes, I know logic doesn't sound like math, but logic operators are an important part of Java. The == (equals-equals) operator is used to compare two things (e.g. 1 == 1 means "Does 1 equal 1?"). The != (not-equals) operator is used when you want to see if two things aren't equal (e.g. denominator != 0 means "Does the denominator not equal 0?"). The ! (not) operator is used when you want to negate the true/false value of something (e.g. !true means "not true" or simply false).
You have already been introduced to variables in the previous section. A variable declaration in Java consists of 2 things: the declaration and the initialization. In order to create a new integer in the main method, you write int i=0;
. The first part of the declaration reserves space in the computer's memory to put the value of the variable. The second part actually sets it equal to the value. By writing this, you make the variable named i, and its value is set to 0. This works with any other Object in Java. If you want to check the value of the new integer, type System.out.println(i)
. You should get 0 in the output console.
Changing the variable is as easy as re-initializing it. For example, 'i = 4;` The value has now changed to 4, and you can check this by outputting the value of the variable into the console using System.out.println. This same technique works with all variables as long as you setting the variable to something it can actually be. For example, you can't set an integer to equal 1.5, nor can you set a String to be an integer.
Strings work similarly; to make a String object, you type String s = "My new string";
You will notice that here we had to use the double quotation marks to tell the Java compiler that My new string is a string and NOT a bunch of other variables. Keep this in mind when using Strings. Characters are similar, except you use single quotes to initialize them.