Navigation

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
            

Hello World For Eclipse IDE.

Hello World For Eclipse IDE

1. Prerequisite

To write your first program, you'll need:

  • The Java SE Development Kit.

  • The Eclipse IDE.

If you have not set the above prerequisite refer Introduction to Java to set your environment.

2. Create JAVA Project

Open your Eclipse and select your Workspace (Folder where your projects will be saved).

Image selects workspace location.

You will be greeted with welcome screen, close the welcome screen and your screen looks similarly like one below,

Image shows Eclipse home screen.

We can create our First Java Project,

Choose File -> New -> Other -> Java Project

Click Next

Image selects Java Project from New Wizard Dialog.

Enter Project name as “Hello World” and keep rest of the settings as it is.

Click Finish

Enter Project Name in New Java Projet Wizard.

Our Project will be successfully created in Eclipse.

Image shows Project structor of our Hello World application.

3. Create Java Package

A package is a namespace that organizes a set of related classes and interfaces.

To create Package,Right click on 'src' folder and select from context menu New -> Package.

Image shows how to create new java package.

Enter Package Name.

Click Finish

Image shows how to create new java package.

Our package will be successfully created.

Image shows newly create package in project directory.

4. Create Java Class

Java Class is the file (.java) where we will write all our Java source code.

Right click on our package 'com.helloworld.example’ and select from context menu New -> Class.

Image shows how to create new java class

Write "HelloWorld" in the 'Name' field and select the check-box for 'public static void main(String[] args)'.

public static void main(String[] args) – Is a Main method from where our program execution starts.

Image shows how to create new java class

Click "Finish" button. Eclipse will generate a java class and open the same in the java editor as shown below.

Image shows newly java class

5. Write Java Code

Edit the generated 'HelloWord' java class to simple print “Hello World” to Console.

                package com.hellowworld.example;
                /**
                 * My First Java Class.
                 * 
                 * @author vasanth
                 *
                 */
                public class HelloWorld {
                    /**
                     * A Main method from which program exection starts.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        // Simply print 'Hello World' to Console.
                        System.out.println("Hello World");
                    }
                }
            

6. Run Our Code

To Run our Code, Right click on 'HelloWorld.java' and select from context menu 'Run As' --> 'Java Application'.

Image shows how to run java application

7. Console Output

Our code will print 'Hello World' in the eclipse console.

Image shows 'hello world' printed in eclipse console

We have successfully created our first Java Project.