How do I use the unary operators?

The unary operators requires only one operand to operate on, it can perform operations such as incrementing or decrementing value by one, negating a value or inverting a value of a boolean expression.

The unary operators use the following symbols:

Symbol Description
+ unary plus operator; indicates positive value
- unary minus operator; negates a value
++ unary increment operator; increments value by one
-- unary decrement operator; decrements value by one
! unary logical complement operator; inverts a boolean value
package org.kodejava.basic;

public class UnaryOperatorsDemo {
    public static void main(String[] args) {
        int result = +10;  // result = 10
        System.out.println("result = " + result);
        result--;          // result = 9
        System.out.println("result = " + result);
        result++;          // result = 10
        System.out.println("result = " + result);
        result = -result;  // result = -10;
        System.out.println("result = " + result);

        // The increment and decrement operators can be applied
        // before (prefix) or after (postfix) the operand. Both
        // of them will increment or decrement value by one. The
        // different is that the prefix version evaluates to the
        // incremented or decremented value while the postfix
        // version evaluates to the original value;
        --result;
        System.out.println("result = " + result);
        ++result;
        System.out.println("result = " + result);

        boolean status = result == -10;  // status = true
        System.out.println("status = " + status);
        status = !status;                // status = false;
        System.out.println("status = " + status);
    }
}

How do I use the arithmetic operators?

The following example show you how to use Java arithmetic operators. The operators consist of the multiplicative operators (* for multiplication, / for division), % for remainder of division) and the additive operators (+ for addition,- for subtraction).

You’ll also see we are using a combination of a simple assignment operator with the arithmetic operators to create compound assignments.

package org.kodejava.basic;

public class ArithmeticOperatorsDemo {
    public static void main(String[] args) {
        int result = 5 + 4;  // result = 9
        System.out.println("result = " + result);

        result = result - 2; // result = 7
        System.out.println("result = " + result);

        result = result * 4; // result = 28
        System.out.println("result = " + result);

        result = result / 7; // result = 4
        System.out.println("result = " + result);

        result = result % 3; // result = 1
        System.out.println("result = " + result);

        // Combining the arithmetic operators with a simple assignment
        // operators give us a compound assignment. We can write the
        // operation above in the following form. But as you can see
        // the above snippets is easier to read.
        result = 5 + 4; // result = 9
        System.out.println("result = " + result);

        result -= 2;    // result = 7
        System.out.println("result = " + result);

        result *= 4;    // result = 28
        System.out.println("result = " + result);

        result /= 7;    // result = 4
        System.out.println("result = " + result);

        result %= 3;    // result = 1
        System.out.println("result = " + result);
    }
}

How do I get the remainder of a division?

The remainder or modulus operator (%) let you get the remainder of a division of two numbers. This operator can be used to obtain a reminder of an integer or floating point types.

package org.kodejava.basic;

public class RemainderOperatorDemo {
    public static void main(String[] args) {
        int a = 10;
        double b = 49;

        // The reminder operator (%) gives you the remainder of
        // an integer or floating point division operation.
        System.out.println("The result of " + a + " % 5 = " + (a % 5));
        System.out.println("The result of " + b + " % 9.5 = " + (b % 9.5));
    }
}

Here is the result of the program:

The result of 10 % 5 = 0
The result of 49.0 % 9.5 = 1.5

How do I use the ternary operator?

The ternary operator or conditional operator can be use as a short version of the if-then-else statement. When you have a simple if-then-else statement in your code that return a value you might use the ternary operator, it can make your code easier to read.

The ternary operator is written using the symbol of ?: and it has the following syntax:

result = testCondition ? value1 : value2;

When the test condition evaluates to true the expression value1 will be returned else the expression value2 will be returned. The value1 or value2 is not only for a simple field or variable, it can be a call to a method for example. But it is advisable to use the ternary operator for a simple thing, because if you over do it, it will make your code harder to read.

Let’s see the following code:

package org.kodejava.basic;

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

        // Get the maximum value
        int min = a < b ? a : b;

        // The use of ternary operator above is an alternative
        // of the following if-then-else statement.
        int minValue;
        if (a < b) {
            minValue = a;
        } else {
            minValue = b;
        }

        // Get the maximum value.
        int max = a > b ? a : b;

        // Get the absolute value.
        int abs = a < 0 ? -a : a;

        System.out.println("min      = " + min);
        System.out.println("minValue = " + minValue);
        System.out.println("max      = " + max);
        System.out.println("abs      = " + abs);
    }
}

The output of the code snippet above:

min      = 10
minValue = 10
max      = 20
abs      = 10

How do I do bitwise exclusive OR operation?

package org.kodejava.lang;

public class XorDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 32;

        // Operator ^ is used for doing bitwise exclusive OR operation
        int result = numberA ^ numberB;

        System.out.println(numberA + " ^ " + numberB + " = " + result);

        // Print the result in binary format
        System.out.println(Integer.toBinaryString(numberA) +
                " ^ " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}

The program prints the following output:

16 ^ 32 = 48
10000 ^ 100000 = 110000

How do I do bitwise OR operation?

package org.kodejava.lang;

public class OrDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 4;

        // Operator "|" is used for doing bitwise OR operation
        int result = numberA | numberB;

        System.out.println(numberA + " | " + numberB + " = " + result);

        // Print the result in binary format
        System.out.println(Integer.toBinaryString(numberA) +
                " | " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}

The result of the code snippet:

16 | 4 = 20
10000 | 100 = 10100

How do I do bitwise AND operation?

package org.kodejava.lang;

public class AndDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 16;

        // Operator "&"  is used for doing bitwise AND operation
        int result = numberA & numberB;

        System.out.println(numberA + " & " + numberB + " = " + result);

        // Print the result in binary format
        System.out.println(Integer.toBinaryString(numberA) +
                " & " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}

The result of the code snippet:

16 & 16 = 16
10000 & 10000 = 10000

How do I know the class of an object?

For instance, you have a collection of objects in an List object, and you want to do some logic based on the object’s class. This can easily be done using the instanceof operator. The operator returns true if an object is an instance of a specified class, if not it will return false.

The instanceof operator is most likely used when implementing an equals(Object o) method of an object to check if the compared object is from the same class.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class InstanceOfExample {
    public static void main(String[] args) {
        Person person = new Person("John");
        Animal animal = new Animal("Highland");
        Thing thing = new Thing("Red");
        String text = "hello";
        Integer number = 1000;

        List<Object> list = new ArrayList<>();
        list.add(person);
        list.add(animal);
        list.add(thing);
        list.add(text);
        list.add(number);

        for (Object o : list) {
            if (o instanceof Person) {
                System.out.println("My name is " + ((Person) o).getName());
            } else if (o instanceof Animal) {
                System.out.println("I live in " + ((Animal) o).getHabitat());
            } else if (o instanceof Thing) {
                System.out.println("My color is " + ((Thing) o).getColor());
            } else if (o instanceof String) {
                System.out.println("My text is " + o.toString());
            } else if (o instanceof Integer) {
                System.out.println("My value is " + ((Integer) o));
            }
        }
    }
}

class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

class Animal {
    private final String habitat;

    public Animal(String habitat) {
        this.habitat = habitat;
    }

    public String getHabitat() {
        return habitat;
    }
}

class Thing {
    private final String color;

    public Thing(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

The result of the code snippet above:

My name is John
I live in Highland
My color is Red
My text is hello
My value is 1000

How do I check string for equality?

To compare strings for their content equality we must use the String.equals() method. This method ensures that it will compare the content of both string instead of the object reference of the both string. This method returns true if both string in comparison have the same content.

Do not, never, use the == operator to compare string for its content. The == operator check for object reference equality, it returns true only if both objects point to the same reference. This operator returns false if the object doesn’t point to the same references.

package org.kodejava.lang;

public class StringEquals {
    public static void main(String[] args) {
        String s1 = "Hello World";
        String s2 = new String("Hello World");

        // This is good!
        if (s1.equals(s2)) {
            System.out.println("1. Both strings are equals.");
        } else {
            System.out.println("1. Both strings are not equals.");
        }

        // This is bad!
        if (s1 == s2) {
            System.out.println("2. Both strings are equals.");
        } else {
            System.out.println("2. Both strings are not equals.");
        }
    }
}

In the example above we deliberately create an instance of s2 string using the new operator to make sure that we have a different object reference. When you run the program it will give you the following result:

1. Both strings are equals.
2. Both strings are not equals.