Link Search Menu Expand Document

Operators

  1. Operators
    1. Arithmetic Operators (Math)
      1. Order of Precedence
    2. String Concatenation
    3. Using Operator with two different types
    4. Relational Operators (Comparison)
    5. Logical Operators (Boolean)

Material:

Arithmetic Operators (Math)

Java provides operators for the following arithmetic operations

  • addition
  • multiplication
  • subtraction
  • division
  • modulo (calculating the remainder of a division)

These operators work with all numerical types of Java e.g. int, long, double or float.

Each operator is represented by a specific character:

class Main {
    public static void main(String[] args) {
        int a = 15;
        int b = 10;

        int sum = a + b;
        System.out.println(sum);
        int difference = a - b;
        System.out.println(difference);
        int multiplied = a * b;
        System.out.println(multiplied);
        int divided = a / b;
        System.out.println(divided);
        int modulo = a % b;
        System.out.println(modulo);
    }
}

Note, that the result of the division depends on if you use a type for fractional numbers (like double) or not (like int):

  • for fractional numbers, you will get an exact result, e.g. 3.0 / 2.0 will give you back 1.5
  • for non-fractional result, for the same calculation 3 / 2 you get just 1

Order of Precedence

Note that the same rules like in normal math apply regarding which operations are computed first in a more complex formula:

  • operations are executed from left to right
  • a division or multiplication takes precedence over addition or subtraction, i.e. 2 + 5 * 2 is 12
  • you can use round brackets to explicitly define the order of operation, i.e. (2 + 5) * 2 is 14

String Concatenation

With String concatenation, you can take two String and produce a new one (you sum them up):

class Main {
    public static void main(String[] args) {
        String a = "A";
        String b = "B";

        String ab = a + b;
        System.out.println(ab);
        String ba = b + a;
        System.out.println(ba);
        String abba = a + b + b + a;
        System.out.println(abba); 
    }
}

Using Operator with two different types

So far we always used an operator with two values of the same type so that the result of our operation was also of the same type, e.g.:

  • adding two int also returns an int
  • dividing two double also returns a double
  • concatenating two String also returns a String

But what happens if we mix the types, e.g.:

  • add an int to a double?
  • divide a double by an int?
  • combine an int with a String?

what will be the resulting type?

Java follows this rule to determine that: Given one value of type A and one of type B and applying an operator on both, the type of the result will be the more expressive one of A and B

So when is a type A more expressive than a type B?

If all possible values of B are part of A but not all possible values of A are part of B!

Let us look at some examples for clarity:

  • long is more expressive than int as int only contains numbers from -2000000000 to +2000000000 while long contains both bigger and smaller numbers
  • double is more expressive than int as int can only contain numbers like 1, 2, … while double can contain also all the numbers between e.g. 1 and 2 like 1.1, 1.2, 1.25 …
  • String is more expressive than double as every double can be represented as String (e.g. 1.5 is just “1.5”) while e.g. the String “A” cannot be represented as double

Thus we can say what the following program will print:

class Main {
    public static void main(String[] args) {
        int i = 4;
        double d = 2.0;
        int t = 9;
        
        System.out.println(i + d + "42" + t); 
    }
}

The program will print 6.0429 as

  • we go from left to right
  • first we add to int i the double d and the result of this is a double so 6.0
  • then we add a String to that double, the result is of type String so we get as result the concatenation of 6.042
  • then we add the int t but as the other type is a String this will be again just treated as concatenation and we end up with the String 6.0429

We can observe a similar effect also for assignments:

Compare the following two programs:

class Main {
    public static void main(String[] args) {
        int i = 4;
        double d = i;
        System.out.println(d); 
    }
}
class Main {
    public static void main(String[] args) {
        double d = 4.0;
        int i = d;
        System.out.println(i); 
    }
}

The first program will run and print out 4.0.
The second program will not compile.
This is again due to the expressiveness of the involved types:

  • in the first program we put an int into a double. As we know, each int can be represented as double so the assignment is allowed (and the int 4 is converted into the corresponding double 4.0)
  • in the second program we try to put a double value into an int value. Java does not allow that as we might lose information (e.g. all doubles 4.0, 4.1, 4.2 cannot be represented lossless as an int => all values would be converted to just the same, a 4)

However, there might be an occasion where we actually want to perform the second case. We can achieve this but must tell Java explicitly to execute the conversion from double to int. This process is called casting (e.g. casting a double to an int) and can be expressed in code like this:

class Main {
    public static void main(String[] args) {
        double d = 4.0;
        int i = (int)d;
        System.out.println(i); 
    }
}

Relational Operators (Comparison)

Relational operators allow you to compare two values (e.g. you ask if value A is bigger/smaller than value B).

Such a comparison will always give you back a boolean.

The following code snippet shows you all possible comparison operators:

class Main {
    public static void main(String[] args) {
        int a = 3;
        int b = 7;

        boolean isASmallerB = a < b;
        boolean isAGreaterB = a > b;
        boolean isAEqualToB = a == b;
        boolean isANotEqualToB = a != b;
        boolean isASmallerOrEqualToB = a <= b;
        boolean isAGreaterOrEqualToB = a >= b; 
    }
}

Logical Operators (Boolean)

Logical operators allow you to combine two boolean expressions (either just a boolean value like true or false but also comparison like the ones from the previous section).

Logical operators will again return a new boolean value.

The following code snippet shows you all possible logical operators (try to run it to see the output):

class Main {
    public static void main(String[] args) {

        // AND operator && returns true if both given booleans are true
        System.out.println("Using AND");
        System.out.println(true && true);
        System.out.println(false && true);
        System.out.println(true && false);
        System.out.println(false && false);

        // OR operator || returns true if at least one of the given booleans are true
        System.out.println("Using OR");
        System.out.println(true || true);
        System.out.println(false || true);
        System.out.println(true || false);
        System.out.println(false || false);

        // XOR operator ^ returns true if at only exactly one of the given booleans are true
        System.out.println("Using XOR");
        System.out.println(true ^ true);
        System.out.println(false ^ true);
        System.out.println(true ^ false);
        System.out.println(false ^ false);

        // NOT operator ! takes only one boolean and returns the opposite value
        System.out.println("Using NOT");
        System.out.println(!true);
        System.out.println(!false);
    }
}

Table of contents