How do I use the diamond syntax?

In Java 7 a new feature called diamond syntax or diamond operator was introduced. This diamond syntax <> simplify how we instantiate generic type variables. In the previous version of Java when declaring and instantiating generic types we’ll do it like the snippet below:

List<String> names = new ArrayList<String>();
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

As you can see in the snippet, we were repeating our self by defining the generic type two times. We define the object type we’ll be stored in the List and the Map on both left and the right side. By using the diamond syntax the compiler will infer the type of the right side expression argument automatically. So in Java 7 we can write the above code snippet like this:

List<String> names = new ArrayList<>();
Map<String, List<Integer>> map = new HashMap<>();

This make our code simpler and more readable and by using the diamond syntax the compiler will ensure that we have the generic type safe checking available in our code. This will make any error due to type incompatibility captured at the compile time.

How do I use the || operator in Java?

The || operator or conditional OR operator operates on two boolean expressions. This operator exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

The || operator evaluate only boolean values. For an OR (||) expression it will return true if either of the operand is true. If the first operand resolves true, then the second operand will not evaluated, because the complete expression will return true.

package org.kodejava.example.fundamental;

public class ConditionalORDemo {
    public static void main(String[] args) {
        // the second operand (5<3) is not evaluated, because the
        // first operand return true, the result of complete
        // expression will be true
        boolean a = (1 == 1) || (5 < 3);

        // the first operand return false, the second operand is
        // evaluated to check the result of the second expression.
        // If the second operand resolves to true, the complete
        // expression return true, otherwise return false.
        boolean b = (5 < 3) || (2 == 3);
        boolean c = (5 < 3) || (1 == 1);

        System.out.println("result a: " + a);
        System.out.println("result b: " + b);
        System.out.println("result c: " + c);
    }
}

The program prints the following output:

result a: true
result b: false
result c: true

How do I use the boolean negation (!) operator in Java?

The ! operator is a logical compliment operator. The operator inverts the value of a boolean expression.

package org.kodejava.example.fundamental;

public class NegationOperator {
    public static void main(String[] args) {
        // negate the result of boolean expressions
        boolean negate = !(2 < 3);
        boolean value = !false;

        System.out.println("result: " + negate);
        System.out.println("value : " + value);
    }
}

Here is the result of the program:

result: false
value : true

How do I use the relational operator in Java?

Relational operators used to compare any combination of integers, floating-point numbers, or characters. The result of relational operators is always in a boolean value, true or false. It is mostly used in an if statement test.

There are four relational operators in Java:

  • > greater than
  • >= greater than or equal to
  • < less than
  • <= less than or equal to
package org.kodejava.example.fundamental;

public class RelationalDemo {
    public static void main(String[] args) {
        int value1 = 10, value2 = 25;
        int age = 15;
        double salary = 1000d;
        char char1 = 'd', char2 = 'f';

        if (value1 > value2) {
            System.out.format("%d is greater than %d %n", value1, value2);
        } else {
            System.out.format("%d is greater than %d %n", value2, value1);
        }

        if (age >= 12) {
            System.out.format("Hey, I am not a kid anymore %n");
        }

        if (char1 < char2) {
            System.out.format("%c is less than %c %n", char1, char2);
        } else {
            System.out.format("%c is less than %c %n", char2, char1);
        }

        if (salary <= 3000d) {
            System.out.println("Entry-level Staff");
        }
    }
}

An here are the result of the program:

25 is greater than 10 
Hey, I am not a kid anymore 
d is less than f 
Entry-level Staff

How do I use the equality operator in Java?

Equality operator is used to compare two similar things (numbers, characters, boolean, primitives and object references). Equality operator will always result in boolean value (true or false).

For object reference, it will return true if only both reference variables refer to the same object.

package org.kodejava.example.fundamental;

public class EqualityDemo {
    public static void main(String[] args) {
        int value1 = 10, value2 = 10, number1 = 10;
        char a = 'a', b = 'b';
        double number2 = 10d;
        Cat kitty = new Cat("Kitty");
        Cat kitten = new Cat("Kitty");
        Cat sweetie = kitty;

        if (value1 == value2) {
            System.out.println("Equal");
        }

        if (a != b) {
            System.out.println("Not Equal");
        }

        // though it have different type, but it have same value
        if (number1 == number2) {
            System.out.println("Equal");
        }

        // it's not refer to the same object, so it will return
        // false
        if (kitty == kitten) {
            System.out.format("(kitty == kitten) = " + (kitty == kitten));
        } else {
            System.out.println("(kitty == kitten) = " + (kitty == kitten));
        }

        // it's refer to the same object, so it will return true
        if (kitty == sweetie) {
            System.out.println("(kitty == sweetie) = " + (kitty == sweetie));
        }

        if (true != false) {
            System.out.println("true != false");
        }

    }
}

class Cat {
    private String name;

    Cat(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And here are the result of the program:

Equal
Not Equal
Equal
(kitty == kitten) = false
(kitty == sweetie) = true
true != false

How do I use the && operator in Java?

The && operator also known as conditional-AND operator or short circuit AND. This operator exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

The && operator evaluate only boolean values. For an AND (&&) expression to be true, both operands must be true. If the first operand resolves false, then the && operator will not evaluate the second operand, because it already know the complete expression will return false.

package org.kodejava.example.fundamental;

public class ConditionalANDDemo {
    public static void main(String[] args) {
        // second operand (2<3) is not evaluated, because the first
        // operand return false the result of complete expression
        // can't be true
        boolean a = (5 < 3) && (2 < 3);

        // first operand return true, second operand is evaluated
        // to check the result of the second expression if second
        // operand resolves to true, the complete expression return
        // false, otherwise return false
        boolean b = (1 == 1) && (2 < 3);
        boolean c = (1 == 1) && (5 < 3);

        System.out.println("result a: " + a);
        System.out.println("result b: " + b);
        System.out.println("result c: " + c);
    }
}

The result of the code snippet:

result a: false
result b: true
result c: false

How do I use the shift right “>>” operator?

The signed shift right operator >> shifts a bit pattern to the right. This operator operates with two operand, the left-hand operand to be shifted and the right-hand operand tells how much position to shift.

Shifting a 1000 bit pattern using the >> operator 2 position will produce a 0010 bit pattern. The signed shift right operator produce a result that equals to dividing a number by 2.

package org.kodejava.example.fundamental;

public class SignedRightShiftOperator {
    public static void main(String[] args) {
        // The binary representation of 32 is
        // "00000000000000000000000000100000"
        int number = 32;
        System.out.println("number       = " + number);
        System.out.println("binary       = " +
                Integer.toBinaryString(number));

        // Using the shift right operator we shift the bits
        // four times to the right which resulting the result
        // of "00000000000000000000000000000010"
        int shiftedRight = number >> 4;
        System.out.println("shiftedRight = " + shiftedRight);
        System.out.println("binary       = " +
                Integer.toBinaryString(shiftedRight));
    }
}

The result of the code snippet:

number       = 32
binary       = 100000
shiftedRight = 2
binary       = 10

How do I use the shift left “<<" operator?

The signed shift left operator << shifts a bit pattern to the left. This operator operates with two operand, the left-hand operand to be shifted and the right-hand operand tells how much position to shift.

Shifting a 0010 bit pattern using the << operator 2 position will produce a 1000 bit pattern. The signed shift left operator produce a result that equals to multiplying a number by 2, which double the value of a number.

package org.kodejava.example.fundamental;

public class SignedLeftShiftOperator {
    public static void main(String[] args) {
        // The binary representation of 2 is "0010"
        int number = 2;
        System.out.println("number      = " + number);
        System.out.println("binary      = " +
                Integer.toBinaryString(number));

        // Using the shift left operator we shift the bits two
        // times to the left. Which will shift the "0010" into
        // "1000"
        int shiftedLeft = number << 2;
        System.out.println("shiftedLeft = " + shiftedLeft);
        System.out.println("binary      = " +
                Integer.toBinaryString(shiftedLeft));
    }
}

The result of the code snippet:

number      = 2
binary      = 10
shiftedLeft = 8
binary      = 1000

How do I use the unary bitwise complement “~” operator?

The unary bitwise complement operator (~) inverts a bit pattern; it can be applied to any of the integral types, making every 0 a 1 and every 1 a 0.

For example, an integer contains 32 bits; applying this operator to a value whose bit pattern is 00000000000000000000000000001000 would change its pattern to 11111111111111111111111111110111.

package org.kodejava.example.fundamental;

public class UnaryBitwiseComplementOperator {
    public static void main(String[] args) {
        // An integer type contains 32 bit information.
        // 8 = 00000000000000000000000000001000
        int number = 8;
        System.out.println("number = " + number);
        System.out.println(Integer.toBinaryString(number));

        // Using the ~ operator inverts the number by change the
        // every "0" to "1" and every "1" to "0".
        // 00000000000000000000000000001000
        // 11111111111111111111111111110111
        //
        int invertedNumber = ~number;
        System.out.println("invertedNumber = " + invertedNumber);
        System.out.println(Integer.toBinaryString(invertedNumber));
    }
}

The result of the code snippet:

number = 8
1000
invertedNumber = -9
11111111111111111111111111110111

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.example.fundamental;

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);
    }
}