Saturday, 3 January 2015

Java Arrays

An array in Java is an ordered collection of the similar type of variables. Java allows creating arrays of any dimensions. An array in Java is a bit different from C/C++. You can not specify the size of the array at the time of declaration. The memory allocation is always dynamic. Every array in Java is treated as an object with one special attribute length, which specifies the number of elements in the array.

One Dimensional array

Declaration

A one dimensional array is declared as:

type variable_name[];

The type specifies the base type of array elements, which specifies what type of elements can be stored in the array.

For example, the following array can be used to store int elements:

int marks[]; or int[] marks;

Declaration just specifies that array marks can be used to store integers but no memory allocation takes place at point of declaration.

Memory Allocation

Memory allocation for a Java array is done using operator new. The general form of the operator new is as follows:

var = new type[size];

The variable var is the name of an array, declared using the syntax as mentioned above. The type refers to the type of the elements that can be stored in the array. Size refers to the number of elements for which the memory is to be allocated dynamically.

For example, following array can store 20 elements:

marks = new int[20];

Thus obtaining an array in Java is a two step process:

1. declaration
2. memory allocation

A third step may be initializing the array elements.

The above two steps can be combined into one as follow:

int marks[] = new int[20];

Initialization

Third step is to initialize the array elements. For example the array allocated above can be initialized as:

for(int i=0; i<20; i++){
    marks[i] = 0;
}

The initialization with zero is not must as all the arrays of numeric types are initialized with 0.

Note: Array declaration, memory allocation and initialization steps can be combined into one as shown below:

int marks[] = {10, 2, 17, 77, 99, 90, 22, 34};

Array Length

In Java, all arrays store the allocated size in a variable named length. We can access the length of the array marks using the attribute length.

int len = marks.length;

Example: The following example demonstrate the use of attribute length and also demonstrates how to access the command line arguments.

class cmdLineDemo{
    public static void main(String args[]){
        int len = args.length;
        for(int i=0;i<len;i++){
            System.out.println(args[i]);
        }
    }
}

The JVM calls the main() and passes the command line arguments to it as an array of Strings. The length of the array (i.e. the number of the command line arguments) is obtained using attribute length in the above example. the for loop displays the command line arguments on the console/monitor.

Two dimensional array

Declaration

A two dimensional array is declared as:

type variable_name[][];

The type specifies the base type of array elements as in the case of one-dimensional array. For example, The following array can be used to store int elements:

int marks[][]; or int[][] marks;

Declaration just specifies that array marks can be used to store integers but no memory allocation takes place at point of declaration.

Memory Allocation

The general form of the operator new is as follows:

var = new type[rows][columns];

The variable var is the name of two dimensional array. the type refers to the type of the elements that can be stored in the array. The first index indicates the number of rows and the second index indicates the number of columns in the two dimensional array to be allocated dynamically.

For example, following array can store a table consisting of 5 rows and 4 elements:

marks = new int[5][4];

The above two steps can be combined into one as follows:

int marks[][] = new int[5][4];

Java Literals

Integer Literals

An integer literal/constant can be of any one of the following types. It is like C/C++.


  • int (187, -98, 0 etc.)
  • long (897, 776L, -656L)
  • octal (017, 033, -034 etc.)
  • hexadecimal (0x11, 0x1B etc.)
A decimal integer  constant is treated as an int by default. If a decimal integer constant is larger than the range of the int, it is declared to be of type long. A decimal integer constant can be made long by appending l or L to it. A leading zero placed at the beginning of an integer constant indicates that it is an octal integer constant. A leading 0x or 0X placed at the beginning of an integer constant indicates that it is a hexadecimal constant.

Floating Point Literals

Floating point literals represent real values. They may have a fractional part in addition to the integral part. The default data type of a floating-point literal is double, but it can be explicitly designated by appending the suffix d (or D) to the real constant. A floating-point literal can be specified to be a float by appending the suffix f (or F).

Boolean literals

Java defines two boolean literals  true and false.

Character Literals

There are many ways of expressing character literals:

  • Enclosing character within single quotes (as in C/C++)
  • Escape sequences  (as in C/C++)
  • Octal Notation  (as in C/C++)
  • Unicode Notation  (different from C/C++)
Characters literals can be expressed by enclosing the character in single quotes:

'A', 'B', 'a' etc.

Character literals can also be expressed using escape sequence:

'\n', '\t', '\r', '\b' etc.

Characters can be expressed using octal notation. The ASCII code of the character is enclosed in single quote prefixed with '\':

'\71', '\101' etc.

A Java character is of two bytes. Escape sequence and octal notation can be used only to represent ASCII characters. Unicode characters can be represented using Unicode notation:

'\u000a', 'ufff', '\u001A' etc.

Unicode as specified above consists of 4 hexadecimal digits so its range can be from 0 to ffff (0 to 65535).

String Literals

A String is a sequence of characters. A String literal is a set of characters that is enclosed within double quotes.

When a String literal is declared, Java automatically creates an instance of the class String and initializes it with the literal value.

Java Local variable Scope and Life Time

A local variable's scope is restricted to the block or method in which it is declared. It can be accessed only in the block/method in which it is declared, from the point of declaration till the end of the block/method.

A local variable comes into existence when the code of the block/method containing the declaration is executed and the declaration is encountered during execution. The variable exists only till the flow of control reaches to the end of the block/method containing it.

One important scope rule in Java that a local variable in some inner block can not hide the variable of the same name in the outer block. This is allowed in C++ and the reference to outer block variables is resolved using scope resolution operator but it is not allowed in Java.

Example: The following program will not compile.

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

        int i=5;
        {
            int i=10;
            System.out.println(i);
        }
    }
}

On compiling this program you will see following error messages:

i is already defined in main(java.lang.String[])

The reason is that i in the inner block hides i of the outer block which is not allowed in Java.

The following program will compile successfully though local variable  i has multiple declarations. The reason is that both the blocks in which i is declared are at the same level.

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

        for(int i=0;i<5;i++){
            System.out.println(i);
        }

        for(int i=0;i<7;i++){
            System.out.println(i);
        }
  }

}

Java Local Variables

Declaration

Declaration of local variables is similar to C/C++. A local variable can be declared anywhere in a method or block and can be initialized during declaration. It is not must to initialize a local variable during declaration but it must be initialized in the same block in which it is declared before the first use. More than one variables of the same type can be declared using single declaration statement by separating the variable names with comma.

Examples:

long x, y, z;
float d;
int a=0, b=10, c=5;

Example: The following program demonstrates the declaration and use of local variables.

Step 1: Open a new file named Local.java and type the following Java Program

class LocalVarDemo{
   
     public static void main(String args[]){
          int num1;
          int num2 = 10;
          int sum, product;
          float f1 = 3.5f; f2 = 6.9f, sumf;

          num1 = 15;
          sum = num1+num2;
          System.out.println("Sum of two integer values = " + sum);
         
          sumf = f1+f2;
          System.out.println("Sum of two floating point values = " + sumf);
     }
}

Step 2: Compile above Java program using command javac Local.java in the command window.

Step 3: Execute the program using command java LocalVarDemo in the command window.

The output of the program will be:

          Sum of two integer values = 25
          Sum of two floating point values = 10.4

Java Variables

Variables are the names of the memory locations that can store values. A variable must be declared before we can store value in it.

Java has three kind of variables:


  • Local variables
  • Instance variables
  • Class variables
Local variables are used inside blocks or methods. Instance variables are used to define attributes or state of an object. Class variables are used to define attributes/state, which is common for all the objects of a class.

All the three types of variables are declared in similar manner but use of class and instance variables differ from the use of local variables. There are also differences in terms of the modifiers (e.g. visibility / access modifiers), which can be used with the variables.

Java Character Data Type

Java uses data type char to store individual characters. Java characters are encoded using 16-bit Unicode character set. The char data type is unsigned and the range of values that can be stored in a char vary from 0 to 65535.

The first 128 characters of the Unicode set are the same as the 128 characters of 7-bit ASCII character set and the first 256 characters of the Unicode correspond to the 256 characters of the extended ASCII (8-bit ISO Latin-1) character set.

Java characters can also be used in integer expressions. The Unicode value of the character is used when it is part of an integer expression.

Java Boolean Data Type

Java has a data type boolean. It is used to store boolean values true and false. You can not use zero to represent false or a non-zero value to represent true like C/C++. Boolean values in Java can not be treated like integers and vice-versa.

The size of the boolean data type is undefined but irrespective of the internal storage boolean data type is used to hold just true and false. Boolean values are produced by all relational, conditional and boolean logical operators and are primarily used to govern flow of control during program execution.

Java Floating data types

Floating point data types are similar to C/C++. They are used to store the real numbers. There are two floating-point data types in Java.


Data type Size Range (Absolute value)
float 4 bytes / 32 bits 1.401298464324817E-45f to 3.4028234663852886E38f
long 8 bytes / 64 bits 4.9E-324d to 1.7976931348623157E308d

Java integer data types

Integer data types in Java are quite similar to C/C++. There are four integer types in Java as mentioned above. Java has one additional integer data type "byte".

All the integers are signed values in Java i.e. they can hold positive as well as negative values.

We choose the data type depending on the range of values to be stored.

The range of values for different integer data types is as follows:


Integer Data type Size Range
byte 1 byte / 8 bits -128 to -127
short 2 bytes / 16 bits -32768 to 32767
int 4 bytes / 32 bits -2147483648 to 2147483647
long 8 bytes / 64 bits -9223372036854775808 to 9223372036854775807

Java Data Types

Data types in Java can be broadly classified in two categories

1. Primitive data types / Simple data types
2. Non-primitive data types / Derived data types or Referenced data types

Primitive Data Types

Although java is an object oriented language, but the primitive data types are not objects. They are kept in java for performance reason. They form the basis for all other types of data that you define in your java programs.

The primitive data types may be further classified as:

1. Numeric data types

-- Integer data types - byte, short, int, long
-- Floating data types - float, double

2. Boolean data type - boolean

3. Character data type - char

Reference Data Types

Reference are also called derived data types as they are derived from the primitive data types. Reference data types can be further classified as:

1. Classes
   Built-in / Library classes
   User-Defined classes

2. Interfaces
   Built-in / Library classes
   User-Defined classes

3. Arrays

Array are treated as objects in Java, which is different from C++.

Java Separators

The Java separators are more or less same as C/C++ separators.

;          Semicolon
,          Comma
.          Period
[]         Square Brackets
()         Parenthesis
{}        Braces