Mathematics and various mathematical functions are an important part in programming. We will discuss them in this post.

If you read my previous posts you already met the “+” operator. Here are the rest of operators at our disposal:

  • + adds 2 numbers
  •  subtracts two numbers
  • * multiplication sign
  • / total division
  • % rest from sharing

The code below shows their operation:

Of course, you can also do something like this:

How about when we devide 9/4 = 2.25, not 2. In this case, it is enough to declare at least one of the variables as a floating-point type.

There are also very useful shortcut operators:

As you can see, they allow you to quickly perform operations on two variables. However, the action is identical to the one given after the comment sign.

Increment and decrement operators also play a very important role in programming. They are used to increase / decrease the value of the variable by 1. They are very often used in loops.

There are two types:

  • prefix – increase the value before assigning
  • postfix – increase the value of the variable after assignment

The bracket in the last line has been inserted for readability, you might as well write +++. The sign — (two cons) is analogous. Expressions in Java are processed from left to right.

There are also comparison and logical operators.

The following operators can be used to compare:

  • == checks equality
  • ! = different
  • > = greater than
  • ,

They return a true or false logic.

There are also logical operators, i.e. the && conjunction and the alternative || .
The three-argument character operator is also useful:

condition? expression1: expression2;
If the condition returns true, expression1 is executed otherwise expression2.

In addition, we must note here that we should not compare strings or other object types with the help of the “==” operator. The “.equals” method is used for this. The operator “==” in the case of object types compares the references, not the actual objects. There is also a small catch here. Take a look at the example below and think about what would appear on the screen?

You probably expect the compare1 to me false and the compare2 to be true. We get them both true, becasue the virtual machine realized that both strings are identical and it saved the varialbes in the same place in memory. This should not be practiced, it is a very bad habit and can lead to errors that will be difficult to detect. To compare String and other objects always use the .equals method.


Please enter your comment!
Please enter your name here