Navigation

Control Flow Statements

Control Flow Statements

1. Introduction

The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.

This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language.

2. The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true.

Example

                /**
                 * A Class used to demonstrate If-Then Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class IfThenStatementDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int a = 10, b = 20;
                        if (a > b) {
                            System.out.println("a is Greater than b");
                        }
                    }
                }
            

If this test evaluates to false (meaning that a is not greater than b), control jumps to the end of the if-then statement.

Our above condition we can write in two ways,

                if (a > b) {
                    System.out.println("a is Greater than b");
                }
            

Or

                if (a > b)
                System.out.println("a is Greater than b");
            

We can omit braces if we have only one statement to execute with in our condition else if we have more than one statement to be executed then we need to have braces.

3. The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.

Example

                /**
                 * A Class used to demonstrate If-Then-Else Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class IfThenElseStatementDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int a = 10, b = 20;
                        if (a > b) {
                            System.out.println("a is Greater than b");
                        } else {
                            System.out.println("b is Greater than a");
                        }
                    }
                }
            

Output

    b is Greater than a

4. The switch Statement

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.

Example

                /**
                 * A Class used to demonstrate Switch Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class SwitchDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int month = 8;
                        String monthString;
                        switch (month) {
                        case 1:
                            monthString = "January";
                            break;
                        case 2:
                            monthString = "February";
                            break;
                        case 3:
                            monthString = "March";
                            break;
                        case 4:
                            monthString = "April";
                            break;
                        case 5:
                            monthString = "May";
                            break;
                        case 6:
                            monthString = "June";
                            break;
                        case 7:
                            monthString = "July";
                            break;
                        case 8:
                            monthString = "August";
                            break;
                        case 9:
                            monthString = "September";
                            break;
                        case 10:
                            monthString = "October";
                            break;
                        case 11:
                            monthString = "November";
                            break;
                        case 12:
                            monthString = "December";
                            break;
                        default:
                            monthString = "Invalid month";
                            break;
                        }
                        System.out.println(monthString);
                    }
                }
            

Output

    August

The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

You could also display the name of the month with if-then-else statements. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

In Java SE 7 and later, you can use a String object in the switch statement's expression. The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.

5. The while and do-while Statements

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

                while (expression) {
                     statement(s)
                }
            

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

Example

Using the while statement to print the values from 1 through 10

                /**
                 * A Class used to demonstrate While Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class WhileDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int count = 1;
                        while (count < 11) {
                            System.out.println("Count is: " + count);
                            count++;
                        }
                    }
                }
            

Output

    Count is: 1
    Count is: 2
    Count is: 3
    Count is: 4
    Count is: 5
    Count is: 6
    Count is: 7
    Count is: 8
    Count is: 9
    Count is: 10

The Java programming language also provides a do-while statement, which can be expressed as follows:

                do {
                     statement(s)
                } while (expression);
            

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

Example

                /**
                 * A Class used to demonstrate Do-While Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class DoWhileDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int count = 1;
                        do {
                            System.out.println("Count is: " + count);
                            count++;
                        } while (count < 11);
                    }
                }
            

Output

    Count is: 1
    Count is: 2
    Count is: 3
    Count is: 4
    Count is: 5
    Count is: 6
    Count is: 7
    Count is: 8
    Count is: 9
    Count is: 10

6. The for Statement

The for statement provides a compact way to iterate over a range of values. The general form of the for statement can be expressed as follows:

                for (initialization; termination; increment) {
                    statement(s)
                }
            

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.

  • When the termination expression evaluates to false, the loop terminates.

  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

Example

                /**
                 * A Class used to demonstrate For Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class ForDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        for (int i = 1; i < 11; i++) {
                            System.out.println("Count is: " + i);
                        }
                    }
                }
            

Output

    Count is: 1
    Count is: 2
    Count is: 3
    Count is: 4
    Count is: 5
    Count is: 6
    Count is: 7
    Count is: 8
    Count is: 9
    Count is: 10

The for statement also has another form designed for iteration through Collections and arrays. This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.

Example

                /**
                 * A Class used to demonstrate Enhanced For Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class EnhancedForDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                        for (int item : numbers) {
                            System.out.println("Count is: " + item);
                        }
                    }
                }
            

Output

    Count is: 1
    Count is: 2
    Count is: 3
    Count is: 4
    Count is: 5
    Count is: 6
    Count is: 7
    Count is: 8
    Count is: 9
    Count is: 10

7. Branching Statements

The break Statement

The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop.

Example

This program searches for the number 12 in an array. The break statement, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop.

                /**
                 * A Class used to demonstrate Break Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class BreakDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
                        int searchfor = 12;
                        int i;
                        boolean foundIt = false;
                        for (i = 0; i < arrayOfInts.length; i++) {
                            if (arrayOfInts[i] == searchfor) {
                                foundIt = true;
                                break;
                            }
                        }
                        if (foundIt) {
                            System.out.println("Found " + searchfor + " at index " + i);
                        } else {
                            System.out.println(searchfor + " not in the array");
                        }
                    }
                }
            

Output

    Found 12 at index 4

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

Example

The following program, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):

                /**
                 * A Class used to demonstrate Break with label Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class BreakWithLabelDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 },
                                { 622, 127, 77, 955 } };
                        int searchfor = 12;
                        int i;
                        int j = 0;
                        boolean foundIt = false;
                        search: for (i = 0; i < arrayOfInts.length; i++) {
                            for (j = 0; j < arrayOfInts[i].length; j++) {
                                if (arrayOfInts[i][j] == searchfor) {
                                    foundIt = true;
                                    break search;
                                }
                            }
                        }
                        if (foundIt) {
                            System.out.println("Found " + searchfor + " at " + i + ", " + j);
                        } else {
                            System.out.println(searchfor + " not in the array");
                        }
                    }
                }
            

Output

    Found 12 at 1, 0

The continue Statement

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

Example

The following program , steps through a String, counting the occurrences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.

                /**
                 * A Class used to demonstrate Continue Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class ContinueDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        String searchMe = "peter piper picked a " + "peck of pickled peppers";
                        int max = searchMe.length();
                        int numPs = 0;

                        for (int i = 0; i < max; i++) {
                            // interested only in p's
                            if (searchMe.charAt(i) != 'p')
                                continue;

                            // process p's
                            numPs++;
                        }
                        System.out.println("Found " + numPs + " p's in the string.");
                    }
                }
            

Output

    Found 9 p's in the string.

A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Example

The following example program, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, uses the labeled form of continue to skip an iteration in the outer loop.

                /**
                 * A Class used to demonstrate Continue With Label Statement.
                 * 
                 * @author vasanth
                 *
                 */
                public class ContinueWithLabelDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        String searchMe = "Look for a substring in me";
                        String substring = "sub";
                        boolean foundIt = false;
                        int max = searchMe.length() - substring.length();
                        test: for (int i = 0; i <= max; i++) {
                            int n = substring.length();
                            int j = i;
                            int k = 0;
                            while (n-- != 0) {
                                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                                    continue test;
                                }
                            }
                            foundIt = true;
                            break test;
                        }
                        System.out.println(foundIt ? "Found it" : "Didn't find it");
                    }
                }
            

Output

    Found it

The return Statement

The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.

return ++count;

The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.

return;


Expression, Statements and Blocks

Expression, Statements and Blocks

1. Introduction

Operators may be used in building expressions, which compute values.

Expressions are the core components of statements.

Statements may be grouped into blocks.

2. Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language that evaluates to a single value.

Examples of expressions, illustrated in bold below:

    int speed = 0;

The data type of the value returned by an expression depends on the elements used in the expression.

The expression speed = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, speed is an int.

    // Expression Returns String
    System.out.println("Element 1 at index 0: " + anArray[0]);

    //Expression Returns Boolean
    if (value1 == value2)

Compound Expression.

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:

    1 * 2 * 3

In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first:

    x + y / 100 // ambiguous

You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following:

    (x + y) / 100 // unambiguous, recommended

If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator.

When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.

3. Statements

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.

There are three types of statements,

  1. Expression Statement

  2. Declaration Statement

  3. Control Flow Statements

Expression Statement

The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

  • Assignment expressions

  • Any use of ++ or --

  • Method invocations

  • Object creation expressions

Such statements are called expression statements. Here are some examples of expression statements.

    // assignment statement
    aValue = 8933.234;

    // increment statement
    aValue++;

    // method invocation statement
    System.out.println("Hello World!");

    // object creation statement
    Bicycle myBike = new Bicycle();

Declaration Statement

A declaration statement declares a variable.

    // declaration statement
    double aValue = 8933.234;

Control Flow Statement

Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next post.

4. Blocks

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

Example

                /**
                 * A Class used to demonstrate Blocks.
                 * 
                 * @author vasanth
                 *
                 */
                public class BlogDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        boolean condition = true;
                        if (condition) { // begin block 1
                            System.out.println("Condition is true.");
                        } // end block one
                        else { // begin block 2
                            System.out.println("Condition is false.");
                        } // end block 2
                    }
                }
            

Java Operators

Java Operators

1. Operators

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

2. Operator Precedence

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order.

Operators with higher precedence are evaluated before operators with relatively lower precedence.

When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

3. The Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator "=".

                int speed = 0;
                int gear = 1;
            

This operator can also be used on objects to assign object references.

4. The Arithmetic Operator

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.

Arithmetic Operator
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

Example for Arithmetic Operator

                    /**
                     * A Class used to demonstrate Arithmetic Operators.
                     * 
                     * @author vasanth
                     *
                     */
                    public class ArithmeticOperatorDemo {

                        /**
                         * Main.
                         * 
                         * @param args
                         */
                        public static void main(String[] args) {

                            // Initialize Two numbers.
                            int num1 = 10;
                            int num2 = 3;

                            // Create variable to save result.
                            int result;

                            // 1. Addition '+'.
                            result = num1 + num2;
                            System.out.println(num1 + " + " + num2 + " = " + result);

                            // 2. Subtraction '-'.
                            result = num1 - num2;
                            System.out.println(num1 + " - " + num2 + " = " + result);

                            // 3. Multiplication '*'.
                            result = num1 * num2;
                            System.out.println(num1 + " * " + num2 + " = " + result);

                            // 4. Division '/'.
                            result = num1 / num2;
                            System.out.println(num1 + " / " + num2 + " = " + result);

                            // 1. modulus '%'.
                            result = num1 % num2;
                            System.out.println(num1 + " % " + num2 + " = " + result);

                        }
                    }
                

Output

    10 + 3 = 13
    10 - 3 = 7
    10 * 3 = 30
    10 / 3 = 3
    10 % 3 = 1

5. The Unary Operator

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Unary Operator
Operator Description
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean

Example for Unary Operator

                /**
                 * A Class used to demonstrate Unary Operator
                 * 
                 * @author vasanth
                 *
                 */
                public class UnaryOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {

                        // Create variables.
                        int num1;
                        int result;

                        // 1. Unary plus operator '+'.
                        num1 = 1;
                        result = +(num1);
                        System.out.println("+ (" + num1 + ") = " + result);

                        // 2. Unary minus operator '-'.
                        num1 = 1;
                        result = -(num1);
                        System.out.println("- (" + num1 + ") = " + result);

                        // 3. Increment operator '++'.
                        num1 = 1;
                        result = ++num1;
                        System.out.println("++ 1 = " + result);

                        // 4. Decrement operator '--'.
                        num1 = 1;
                        result = --num1;
                        System.out.println("-- 1 = " + result);

                        // 5. Logical complement operators '!'.
                        boolean inputBoolean = true;
                        boolean resultBoolean = !(inputBoolean);
                        System.out.println("!(true) = " + resultBoolean);
                    }
                }
             

Output

    + (1) = 1
    - (1) = -1
    ++ 1 = 2
    -- 1 = 0
    !(true) = false

Post increment/decrement (n++ / n--) and Pre increment/decrement (++n/ n--)

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.

Post Increment (n++) : First execute the statement then increase the value by one.

Pre Increment (++n) : First increase the value by one then execute the statement.

Example for Post & Pre Increment

                /**
                 * A Class used to demonstrate difference between
                 * 
                 * @author vasanth
                 *
                 */
                public class PrePostDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        System.out.println("***Post increment test***");
                        int n = 10;
                        System.out.println(n); // output 10
                        System.out.println(n++); // output 10
                        System.out.println(n); // output 11

                        System.out.println("***Pre increment test***");
                        int m = 10;
                        System.out.println(m); // output 10
                        System.out.println(++m); // output 11
                        System.out.println(m); // output 11
                    }
                }
            

Output

    ***Post increment test***
    10
    10
    11
    ***Pre increment test***
    10
    11
    11

6. The Equality & Relational Operator

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.

    ==      equal to
    !=      not equal to
    >       greater than
    >=      greater than or equal to
    <       less than
    <=      less than or equal to

Example for Comparison Operator

                /**
                 * A Class used to demonstrate Comparison Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class ComparisonOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int value1 = 1;
                        int value2 = 2;
                        if (value1 == value2)
                            System.out.println("value1 == value2");
                        if (value1 != value2)
                            System.out.println("value1 != value2");
                        if (value1>value2)
                            System.out.println("value1 > value2");
                        if (value1<value2)
                            System.out.println("value1 < value2");
                        if (value1<= value2)
                            System.out.println("value1 <= value2");
                    }
                }
            

Output

    value1 != value2
    value1 < value2
    value1 <= value2

7. The Conditional Operator

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.

These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND

|| Conditional-OR

Conditional Operator
A B A && B A || B
False False False False
False True False True
True False False True
True True True True

Example for Conditional Operator

                /**
                 * A Class used to demonstrate Conditional Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class ConditionalOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int value1 = 1;
                        int value2 = 2;
                        if ((value1 == 1) && (value2 == 2))
                            System.out.println("value1 is 1 AND value2 is 2");
                        if ((value1 == 1) || (value2 == 1))
                            System.out.println("value1 is 1 OR value2 is 1");
                    }
                }
            

Output

    value1 is 1 AND value2 is 2
    value1 is 1 OR value2 is 1

Ternary Operator

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in later lesson). This operator is also known as the ternary operator because it uses three operands.

In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Example for Ternary Operator

            /**
             * A Class used to demonstrate Ternary Operator.
             * 
             * @author vasanth
             *
             */
            public class TernaryOperatorDemo {

                /**
                 * Main.
                 * 
                 * @param args
                 */
                public static void main(String[] args) {
                    int value1 = 1;
                    int value2 = 2;
                    int result;
                    boolean someCondition = true;
                    result = someCondition ? value1 : value2;

                    System.out.println(result);
                }
            }
            

Output

    1

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable.

8. The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.

Example for instanceof

                /**
                 * A Class used to demonstrate InstanceOf Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class InstanceOfOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        Parent obj1 = new Parent();
                        Parent obj2 = new Child();

                        System.out.println("obj1 instanceof Parent: "
                                + (obj1instanceof Parent));
                        System.out.println("obj1 instanceof Child: " + (obj1instanceof Child));
                        System.out.println("obj1 instanceof MyInterface: "
                                + (obj1instanceof MyInterface));
                        System.out.println("obj2 instanceof Parent: "
                                + (obj2instanceof Parent));
                        System.out.println("obj2 instanceof Child: " + (obj2instanceof Child));
                        System.out.println("obj2 instanceof MyInterface: "
                                + (obj2instanceof MyInterface));
                    }
                }
                class Parent {}
                class Child extends Parent implements MyInterface {}
                interface MyInterface {}
            

Output

    obj1 instanceof Parent: true
    obj1 instanceof Child: false
    obj1 instanceof MyInterface: false
    obj2 instanceof Parent: true
    obj2 instanceof Child: true
    obj2 instanceof MyInterface: true

When using the instanceof operator, keep in mind that null is not an instance of anything.

9. Bitwise and Bit Shift Operators

Bitwise and Bit Shift operators in Java are powerful set of operators which allows you to manipulate bits on integral types like int, long, short, bytes and boolean data types in Java.

Basics

Before exploring bitwise and bit shift operator in Java, its prerequisite that you must be familiar with binary format.

  1. Binary format has just two bit, 0 and 1 and that's why is called binary.

  2. In binary arithmetic :

    0 + 0 = 0

    0 + 1 = 1

    1 + 0 = 1

    1 + 1 = 10

  3. Integral types in Java (int, long, short and byte) are signed numbers in Java where most significant bit (MSB) represent sign of number. 1 will denote a negative number and 0 as MSB will denote a positive numbers.

  4. Negative numbers in Java are represented as 2's complement of number. 2's complement of a number is 1's complement + 1 and 1's complement means all zero will turn to 1 and all 1 turned to zero in a binary number e.g. 1's complement of 10 would be 01. and 2's complement of 10 would be 10+1 = 11 (all in binary).

Bitwise operators in Java

In this section we will see example of each of bitwise operator e.g. bitwise negation or complement operator (~), bitwise AND (&), bitwise OR(|) and bitwise XOR(^) operator in Java.

Bitwise unary 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".

Example

                int number = 2; // 0010
                System.out.println(" value of number before: " + number); //0010 
                System.out.println(" value of number after negation: " + ~number); //1101
            

Ouput

    value of number before: 2
    value of number after negation: -3

Bitwise AND operator (&)

The bitwise & operator performs a bitwise AND operation.

Bitwise AND operator
A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println("Result of a&b  is " + (a & b)); // 0000
            

Output

    Result of a&b  is 0

Bitwise OR operator (|)

The bitwise | operator performs a bitwise inclusive OR operation.

Bitwise OR operator
A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println(" value of A bitwise OR B in Java : " + (a | b)); // 0110

            

Output

    value of A bitwise OR B in Java : 6

Bitwise XOR operator (^)

The bitwise ^ operator performs a bitwise exclusive OR operation.

Bitwise XOR operators will return 1 if both bits are different and return 0 if both bits are same.

Bitwise XOR operator
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println(" value of a XOR B in Java : " + (a ^ b)); // 0110
            

Output

    value of a XOR B in Java : 6

Bit Shift Operators

Bit shift operators, which can be used to shift bit from one position to another on both left and right side in a number.

An int in Java ranges from the pattern:

10000000000000000000000000000000 (in decimal it's the number -2147483648)

To the pattern:

01111111111111111111111111111111 (in decimal it's the number 2147483647)

We can see how the integer numbers has been expressed in binary format,

+8 : 1000

-8 : 1111 1111 1111 1111 1111 1111 1111 1000

You can see above that positive number is straightforward but negative number has been expressed in 2’s compliment.

Negative numbers in Java are represented as 2's complement of number. 2's complement of a number is 1's complement + 1 and 1's complement means all zero will turn to 1 and all 1 turned to zero in a binary number.

Example to find binary representation of -8:

  • Binary representation of 8 = 0000 0000 0000 0000 0000 0000 0000 1000

  • 1's complement of 8 = 1111 1111 1111 1111 1111 1111 1111 0111

  • 2's complement of 8 = -8 = (1's complement of 8) + 1 = 1111 1111 1111 1111 1111 1111 1111 1000

To represent a negative number in base 2, we have a control bit, that is the bit that stays most to the left, so if a binary number starts with 1, we’re talking about a negative number, if it starts with a 0, we’re talking about a positive one.

Java provides three bit shift operator,

  • Signed left shift operator " << "

  • Signed right shift operator ">>"

  • Unsigned right shift operator ">>>".

As per syntax of bitshift operator, left hand side of operand is the number whose bit needs to be shift and right hand side of operator is how many bits needs to shift.

Example : (n >> 1)

Left Shift Operator "<<"

Left shift operator with sign, shifts bit into left.

Left shift operator (<<) is used to shift a bit pattern to the left preserving the sign bit.

Left shift operator (<<) is used to shift a bit pattern to the left preserving the sign bit, which means that everything else gets shifted, but the control bit stays put. If it was a 0 it remains as 0, and if it was a 1 it remains as 1.

Example :

    +9 << 2
    +9  = 0 0000 1001
    +9 << 2 = 0 0010 0100 = 36

Example :

    -9 << 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 << 2 = 1 1101 1100 = -36

Explanation :

-9 is expressed as :

1 1 1 1 1 0 1 1 1

Shift two bits left

1 1 1 0 1 1 1 0 0

Since MSB (Most Significant Bit) is 1, hence result is negative number so apply 2’s complement to get actual number.

2’s Complement of 1101 1100 = 0010 0100 = -36

Don’t take in account MSB.

Left Shift Operator
Number Number << 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 16 (0000 0000 0000 0000 0000 0000 0001 0000)
-8 (1111 1111 1111 1111 1111 1111 1111 1000) -16 (1111 1111 1111 1111 1111 1111 1111 0000)

Example

                    int number = 8; // 0000 1000
                    System.out.println("Original number : " + number);

                    // left shifting bytes with 1 position
                    number = number << 1; // should be 16 i.e. 0001 0000

                    // equivalent of multiplication of 2
                    System.out.println("value of number after left shift: " + number);
                

Output

    Original number : 8
    value of number after left shift: 16

Right Shift Operator ">>"

Right shift operator with sign, shifts the bit on right side.

Right shift operator (>>) is used to shift a bit pattern to the right preserving the sign bit.

Right shift operator (>>) is used to shift a bit pattern to the right preserving the sign bit, which means that everything else gets shifted, but the control bit stays put. If it was a 0 it remains as 0, and if it was a 1 it remains as 1.

Example :

    -9 >> 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 >> 2 = 1 1101 1100 = -36

Example :

    -9  >> 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 >> 2 = 1 1111 1101 = -3

Explanation :

-9 is expressed as :

1 1 1 1 1 0 1 1 1

Shift two bits right

1 1 1 1 1 1 1 0 1

Since MSB (Most Significant Bit) is 1, hence result is negative number so apply 2’s complement to get actual number.

2’s Complement of 1111 1101 = 0000 0011 = -3

Don’t take in account MSB.

Right Shift Operator
Number Number >> 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 4 (0000 0000 0000 0000 0000 0000 0000 0100)
-8 (11111111111111111111111111111000) -4 (11111111111111111111111111111100)

Example

                    int number = 8; // 0000 1000
                    System.out.println("Original number : " + number);

                    // right shifting bytes with sign 1 position
                    number = number >> 1; // should be 4 i.e. 0000 0100

                    // equivalent of division of 2
                    System.out.println("value of number after right shift with sign: " + number);
                

Output

    Original number : 8
    value of number after right shift with sign: 4

Unsigned Right Shift Operator ">>>"

Unsigned right shift operator ">>>" right shift without sign operator will only shift the bit towards right without preserving sign of number.

Unsigned right shift operator ">>>" does not preserve the sign bit, everything gets shifted, no matter where it is.

For positive number it is straightforward i.e. bits gets shifted to the right.

But for Negative number also bits get shifted to the right, hence sign of the number is not preserved.

Unsigned Right Shift Operator
Number Number >>> 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 4 (0000 0000 0000 0000 0000 0000 0000 0100)
-8 (1111 1111 1111 1111 1111 1111 1111 1000) 2147483644 (0111 1111 1111 1111 1111 1111 1111 1100)

Example

                    int number = -8; // 1111 1111 1111 1111 1111 1111 1111 1000
                    System.out.println("Original number : " + number);

                    // unsigned right shifting bytes with out sign 1 position
                    number = number >>> 1; // should be 2147483644 i.e. 0111 1111 1111 1111 1111 1111 1111 1100

                    System.out.println("value of number after unsigned right shift with out sign: " + number);
            

Output

    Original number : -8
    value of number after unsigned right shift with out sign: 2147483644

Java Variables

Java Variables

1. What is Variables?

Object stores its state in fields.

            
                int speed = 0;
                int gear = 1;

            

2. Different Kinds of Variables in Java

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields)

    Objects store their individual states in "non-static fields", that is, fields declared without the static keyword.

    Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

  • Class Variables (Static Fields)

    A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

    A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.

    The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.

  • Local Variables

    Similar to how an object stores its state in fields, a method will often store its temporary state in local variables.

    The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method.

    As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

  • Parameters

    The main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields".

    Parameters are similar to local variable, Parameters are only visible to the methods in which they are passed; they are not accessible from the rest of the class.

3. Java Variable Naming Conventions

The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of letters, digits, dollar signs "$", or underscore characters "_", beginning with a letter, the dollar sign "$", or the underscore character "_".

  • The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

  • Subsequent characters may be letters, digits, dollar signs, or underscore characters.

  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention.

  • If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

4. Primitive Data Types

A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

  • byte

    The byte data type is an 8-bit signed two's complement integer.

    It has a minimum value of -128 and a maximum value of 127 (inclusive).

    Default Value - 0

    Example : byte a = 100;

  • short

    The short data type is a 16-bit signed two's complement integer.

    It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).

    Default Value - 0

    Example : short s = 10000;

  • int

    By default, the int data type is a 32-bit signed two's complement integer.

    It has a minimum value of -231 and a maximum value of 231-1.

    Default Value - 0

    Example : int a = 100000;

  • long

    The long data type is a 64-bit two's complement integer.

    The signed long has a minimum value of -263 and a maximum value of 263-1.

    Default Value – 0L

    Example : long a = 100000L;

  • float

    The float data type is a single-precision 32-bit IEEE 754 floating point.

    The minimum/maximum value of float is not the same as that of the int data type (despite both being made of 32-bits). The full range of float values is beyond the scope of this tutorial. For now, the only thing you need to know is that you’ll use float (and double – see below) for saving decimal values.

    Default Value – 0.0f

    Example : float f1 = 234.5f;

  • double

    The double data type is a double-precision 64-bit IEEE 754 floating point.

    As with float, discussing the minimum/maximum value of double data type is beyond the scope of this article. What you should know is that double is a much more precise type than float. For all practical purposes, it is recommended that you use double instead of float for storing decimal values.

    Default Value – 0.0d

    Example : double d1 = 123.4;

  • boolean

    The boolean data type has only two possible values: true and false.

    Use this data type for simple flags that track true/false conditions.

    This data type represents one bit of information, but its "size" isn't something that's precisely defined.

    Default Value - false

    Example : boolean one = true;

  • char

    The char data type is a single 16-bit Unicode character.

    It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

    Default Value - '\u0000'

    Example : char letterA ='A';

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such.

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

5. Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.

Image shows Array of 10 elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

Declaring a Variable to Refer to an Array

            
                // declares an array of integers
                int[] anArray;

            

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name.

  • An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).

  • An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types.

The declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types (byte, char, long etc)

You can also place the brackets after the array's name:

             
                // this form is discouraged
                float anArrayOfFloats[];

             

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating an Array

One way to create an array is with the new operator.

            
                // create an array of integers
                anArray = new int[10];

            

Alternatively, you can use the shortcut syntax to create and initialize an array:

            
                int[] anArray = { 
                100, 200, 300,
                400, 500, 600, 
                700, 800, 900, 1000
                };

            

Here the length of the array is determined by the number of values provided between braces and separated by commas.

Initializing an Array

The next few lines assign values to each element of the array:

            
                anArray[0] = 100; // initialize first element
                anArray[1] = 200; // initialize second element
                anArray[2] = 300; // and so forth

            

Accessing an Array

Each array element is accessed by its numerical index:

            
                System.out.println("Element 1 at index 0: " + anArray[0]);
                System.out.println("Element 2 at index 1: " + anArray[1]);
                System.out.println("Element 3 at index 2: " + anArray[2]);

            

Example for an Array

            
                /**
                 * A class used to demonstrate usage of Array.
                 * 
                 * @author Vasanth
                 * 
                 */
                public class ArrayDemo {
                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        // declares an array of integers
                        int[] anArray;

                        // allocates memory for 10 integers
                        anArray = new int[10];

                        // initialize first element
                        anArray[0] = 100;
                        // initialize second element
                        anArray[1] = 200;
                        // and so forth
                        anArray[2] = 300;
                        anArray[3] = 400;
                        anArray[4] = 500;
                        anArray[5] = 600;
                        anArray[6] = 700;
                        anArray[7] = 800;
                        anArray[8] = 900;
                        anArray[9] = 1000;

                        System.out.println("Element at index 0: " + anArray[0]);
                        System.out.println("Element at index 1: " + anArray[1]);
                        System.out.println("Element at index 2: " + anArray[2]);
                        System.out.println("Element at index 3: " + anArray[3]);
                        System.out.println("Element at index 4: " + anArray[4]);
                        System.out.println("Element at index 5: " + anArray[5]);
                        System.out.println("Element at index 6: " + anArray[6]);
                        System.out.println("Element at index 7: " + anArray[7]);
                        System.out.println("Element at index 8: " + anArray[8]);
                        System.out.println("Element at index 9: " + anArray[9]);
                    }
                }
                
            

Output for the program is

                Element at index 0: 100
                Element at index 1: 200
                Element at index 2: 300
                Element at index 3: 400
                Element at index 4: 500
                Element at index 5: 600
                Element at index 6: 700
                Element at index 7: 800
                Element at index 8: 900
                Element at index 9: 1000
            

Multi-Dimensional Array

The arrays you have been using so far have only held one column of data. But you can set up an array to hold more than one column. These are called multi-dimensional arrays.

As an example, think of a spreadsheet with rows and columns. If you have 3 rows and 3 columns then your spreadsheet can hold 9 numbers. It might look like this:

Image shows Multi-Dimensional Array of 3*3 elements

Example for an Multi-Dimensional Array.

            
                /**
                 * A class used to demonstrate usage of Multi-Dimensional Array.
                 * 
                 * @author Vasanth
                 * 
                 */
                public class MultiDimensionalArrayDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {

                        // declares an multi-dimensional array of integers
                        int[][] anMultiArray;

                        // create a multi-dimensional array of 3*3
                        anMultiArray = new int[3][3];

                        // initialize multi-dimensional array
                        // initialize first row.
                        anMultiArray[0][0] = 10;
                        anMultiArray[0][1] = 12;
                        anMultiArray[0][2] = 43;

                        // initialize second row.
                        anMultiArray[1][0] = 20;
                        anMultiArray[1][1] = 45;
                        anMultiArray[1][2] = 56;

                        // initialize third row.
                        anMultiArray[2][0] = 30;
                        anMultiArray[2][1] = 67;
                        anMultiArray[2][2] = 32;

                        // Accessing multi-dimensional array.
                        System.out.println("Element at row 0 col 0: " + anMultiArray[0][0]);
                        System.out.println("Element at row 0 col 1: " + anMultiArray[0][1]);
                        System.out.println("Element at row 0 col 2: " + anMultiArray[0][2]);
                        System.out.println("Element at row 1 col 0: " + anMultiArray[1][0]);
                        System.out.println("Element at row 1 col 1: " + anMultiArray[1][1]);
                        System.out.println("Element at row 1 col 2: " + anMultiArray[1][2]);
                        System.out.println("Element at row 2 col 0: " + anMultiArray[2][0]);
                        System.out.println("Element at row 2 col 1: " + anMultiArray[2][1]);
                        System.out.println("Element at row 2 col 2: " + anMultiArray[2][2]);
                    }
                }

            

Output for the program is

                Element at row 0 col 0: 10
                Element at row 0 col 1: 12
                Element at row 0 col 2: 43
                Element at row 1 col 0: 20
                Element at row 1 col 1: 45
                Element at row 1 col 2: 56
                Element at row 2 col 0: 30
                Element at row 2 col 1: 67
                Element at row 2 col 2: 32
            

In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

            
                public class MultiDimArrayDemo {
                    public static void main(String[] args) {
                        String[][] names = { { "Mr. ", "Mrs. ", "Ms. " }, { "Smith", "Jones" } };
                        // Mr. Smith
                        System.out.println(names[0][0] + names[1][0]);
                        // Ms. Jones
                        System.out.println(names[0][2] + names[1][1]);
                    }
                }
            
            

Output for the program is

                Mr. Smith
                Ms. Jones