Thursday, 28 May 2015

Java Type Conversions during Assignments

Types of the left hand side variable and right hand side expression in an assignment may differ from each other as long as they are type-compatible with each other. For example all the primitive types excluding boolean are type-compatible with each other. When value of an expression is assigned to a variable, it should be converted to the type of the variable on the left hand side. The type conversion may take place automatically or we may have to convert the type explicitly using typecast operator.

Type conversions can be classified as:

  • Widening (or Broadening or UpCasting) Type Conversions
  • Narrowing (or DownCasting) Type Conversions
Widening Conversions

Widening conversion takes place when we assign a lower type expression to a higher type. There is no possibility of any data/precision loss in a widening conversion so it takes place implicitly/automatically.

Examples: The following examples will clarify this.

Suppose following variables are declared in a method/block:

int i ; byte b= 3; short s = 16; char c = 65; long l; float f; double d;

The following expressions are valid as widening conversion takes place automatically:

i  = b; l = s; f = b; d = c;

Narrowing Conversions


Narrowing conversion takes place when we assign a higher type expression to a lower type.

There is possibility of data/precision loss in a narrowing conversion. So normally a narrowing conversion does not take place implicitly/automatically. The programmer needs to explicitly typecast the higher type to lower type so that he/she is aware of the possibility of data/precision loss. However, there are some cases where even narrowing conversion takes place automatically.

Simple assignments always need explicit type conversion.

Examples: The following examples will clarify this.

Suppose following variables are declared in a method/block:

int i = 10 ; byte b; short s; char c; long l = 23; float f = 18.1f; double d = 5.77;

The following expressions are not valid, as narrowing conversions need explicit typecast:

b = i; s  = l; b = f; c = d;

To use these expressions you need to do explicit typecasting as follows:

b = (byte) i; s = (short) l; b = (byte) f; c = (char) d;

Java Arithmetic Expressions

Arithmetic expressions are formed by combining numeric types (constants, variables and expressions) using arithmetic operators. The basic concepts are same as in case of C/C++ although there are some differences.

1. Type Conversions in Expressions

Automatic type promotion takes place in arithmetic expressions according to the following rules:

  • An operand of type byte, short or char is always converted to int. This is true even if unary operator is used.  This implies that the type of the result will always be int or some higher type.
  • If the higher type between two operands is long the other is converted to long.
  • If the higher type between two operands is float the other is converted to float.
  • If the higher type between two operands is double the other is converted to double.
  • If both the operands are of same type (after byte, short  or char has been promoted to int) then no conversion takes place.
Examples: The following examples will clarify these rules.

Suppose following variables are declared in a method/block:

int i = 10; byte b= 3; short s = 16; char c = 65; long l = 100;

float f = 10.3f; double d = 4.88;

The following table demonstrates some expressions formed using above variables, their result type and the value calculated using the conversion rules defined above:

2. Integer Expressions

An Integer expression is one where all the operands are of integer type. The result of such an expression will always be integer as in case of C/C++. The fractional part is simply ignored. For example the result of expression 5/3 is 1.

While evaluating an integer expression, the following rules are applied:

1. An operand of type byte, short or char is converted to int before evaluation of the expression. This is true for unary as well as binary operators. So the operands will always be of type int or long.

2. While evaluating expressions the operators are applied according to precedence rules, which are same as in C/C++.

3. If both the operands of an operator are of type int then result will also be of type int.

4. If both the operands of an operator are of type long then result will also be of type long.

5. If one of the operands of an operator is of type int and the other is of type long then the int would be converted to long and the result will also be of type long.

Integer division including modulo (%) operator may result in an ArithmeticException (run time error).

Example: The following example illustrates what happens on division by zero.

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

  {
     int i;

     int x = 5;

      i = x / 0;  // x % 0 will also lead to exception.

      int y = i + 3;

      System.out.println(y);

  }

}

On execution of the above program, the following exception (run time error) occurs at statement

i = x/0; and the program terminates:

Exception in thread "main" java.lang.ArithmeticException: / by zero

        at ZeroDivision.main(ZeroDivision.java:5)

The reason is that division by zero is not defined in Java when both the operands are integer. In Java, it is possible to recover from a run time error and continue the execution. This is done by using exception-handling mechanism that will be discussed later.

Overflow in Integer Expressions

Except division no other integer calculations result in any exception although the result might be arithmetically incorrect. On evaluation of an operator (or complex integer expression), the result may be outside the range of the result data type. Such a situation is called overflow.  The actual result is obtained by truncating the extra bits in the result. For example, if the type of the result is
int and the result contains more than 32 bits, then 32 least significant bits in the result are kept and rest are simply truncated to obtain the result. Thus the result will not be correct and in some cases result may be of the wrong sign.

Example:

int tooBig = Integer.MAX_VALUE + 1;

MAX_VALUE is a static final constant defined in the class Integer. Its value represents the maximum positive value that can be stored in a variable of type int, which is, 2147483647. The result of the above expression will be of type int as both the operands are of type int. But the expression would lead to overflow as we are adding one to highest integer value.

In fact, on displaying value of variable tooBig, you will find that it holds the value -2147483648, which is the minimum value that an integer can hold.  The only solution to the overflow problem is to use higher data type i.e. use long type if you expect the result to exceed the limit of the int.

3. Floating-Point Expressions

These are the expressions involving floating-point types. A floating-point expression may also have integer types i.e. a mix of integer and floating-point types. If a floating-point expression has an operator whose both the operands are integer then its result will be calculated as per integer arithmetic rules. For example the expression 3.1 + 5/3 is a floating-point expression but its result will be 4.1 (3.1 + 1) and not 4.76 (3.1 + 1.66) as one might expect because the result of the expression 5/3 would still be int.

While evaluating a floating-point expression, the following rules are applied:

  • An operand of type byte, short or char type is converted to int before evaluation of the expression. This is true for unary as well as binary operators. So the integer operands will always be of type int or long.
  • While evaluating expressions the operators are applied according to precedence rules, whichare same as in C/C++.
  • If operands of an operator are of different types then the lower type operand will be promoted to the type of the higher type operand and the type of the result will be the higher type.
There are three special floating-point values infinity, minus infinity and not a number to represent out-of-range values.

In case of float type these values are represented by constants Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY and Float.NaN respectively defined in the class Float.

Similarly in case of double type these values are represented by constants
Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY and Double.NaN respectively defined in the class Double.

No exception occurs on division by zero as this is defined in case of floating point expressions.

The result of division by zero is either Infinity or –Infinity. Similarly no error occurs if the floating-point expression involves non-determinant forms like 0/0, 0/, /, /0, complex numbers etc. The result of such an expression is NaN (Not a Number).

Examples: 
The following code segments demonstrate the use of three special values.

(i) double d = 10.0/0;

System.out.println(d);

The output of the above println() statement would be Infinity.

(ii) double d = -10.0/0;

System.out.println(d);

The output of the above println() statement would be Infinity.

(iii) double d = 0.0/0;

System.out.println(d);

The output of the above println() statement would be NaN.

(iv) double d = Math.sqrt(-25);

System.out.println(d);

The output of the above println() statement would be NaN.

Note: The result will be same if we substitute the type double with float.

Overflow in Floating-Point Expressions

If the result of a floating-point expression exceeds the maximum value (magnitude) it is represented by +Infinity or –Infinity depending on the sign of the result.

Examples:

(i) double d = 1.0E+308 * 10;

System.out.println(d);
The output of the above println() statement would be Infinity. The result exceeds the

maximum value (magnitude) and its sign is positive hence it is represented as positive

Infinity.

(ii) double d = -1.0E+308 * 10;

System.out.println(d);

The output of the above println() statement would be Infinity. The result exceeds the maximum value (magnitude) and its sign is negative hence it is represented as negative Infinity.

Note: The result will be same if we substitute the type double with float and the result exceeds the maximum float value.

Underflow in Floating-Point Expressions

If the result of a floating-point expression is less than the minimum value (magnitude), it is represented by 0 (Zero).

Examples:

(i) double d = 3E-324 – 1.0E-324;

System.out.println(d);

The output of the above println() statement would be 0 (Zero). The result is less than the minimum value (magnitude) hence it is treated as 0 (Zero).

(ii) double d =  -3E-324 – 1.5E-324;

System.out.println(d);

The output of the above println() statement would be 0 (Zero). The result is less than the minimum value (magnitude) hence it is treated as 0 (Zero).

Note: The result will be same if we substitute the type double with float and the result is less than the minimum float value.

Java Shift Operators

The Java supports the following bit-wise shift operators:

<< (left shift)

>> (right shift with sign fill)

>>> (right shift with zero fill)

Both the operands must be of integer type. The type promotion rule is applied to each operand before performing the shift operation. The type of the result is same as the promoted type of the left hand operand. This means that type of result will be either int or long.

The shift distance should be in the range 0 to 31 if the promoted type of the left hand operand is int. This means you can shift the bits to left or right by at the most 31 places.

If the shift distance is more than 31 then it will be converted to a value in the range 0 to 31 by obtaining mod with 32. So shifting by 32 is equivalent to shifting by 0 i.e. no shifting al all;

shifting by 33 is equivalent to shifting by 1, and so on.

If the shift distance is negative then actual shift distance is obtained by adding some multiple of 32 to the shift distance such that it falls in the range 0 to 31. For example, if shift distance is –30

then the actual shift distance will be 2 (-30 + 1*32); if the shift distance is –44 then the actual shift distance will be 20 (-44 + 2 * 32).

The shift distance should be in the range 0 to 63 if the promoted type of the left hand operand is long. This means you can shift the bits to left or right by at the most 63 places. If the shift distance is more than 63 then it will be converted to a value in the range 0 to 63 by obtaining mod with 64. So shifting by 64 is equivalent to shifting by 0 i.e. no shifting at all; shifting by 65 is equivalent to shifting by 1, and so on.

If the shift distance is negative then actual shift distance is obtained by adding some multiple of 64 to the shift distance such that it falls in the range 0 to 63. For example, if shift distance is –60

then the actual shift distance will be 4 (-60 + 1*64); if the shift distance is –88 then the actual shift distance will be 40 (-88 + 2 * 64).

Left Shift (<<) Operator

To obtain the result of << operator, the bits in the left hand side operand (which can be any integer expression) are shifted to the left as specified by the right hand operand (which can also be any integer expression) and the empty bit positions to the right are filled with zero.  Left shifting by 1 is equivalent to multiplication by 2. It is possible that sign of the result may differ from the sign of the left hand side operand. This may happen because the sign depends on the
left-most bit, which can change from 0 to 1 or 1 to 0 hence the change in sign.

Example:

y = x << 4

To obtain the value of y, shift the bits in x by 4 positions to the left and fill the 4 right bits with zero.

Right Shift with sign fill (>>) Operator

To obtain the result of >> operator, the bits in the left hand side operand (which can be any integer expression) are shifted to the right as specified by the right hand operand (which can also be any integer expression) and the empty bit positions to the left are filled with sign bit. Right shifting by 1 is equivalent to division 2. This operator never changes the sign of the result i.e. it will be same as the sign of the left hand operand.

Example:

y = x >> 4

To obtain the value of y, shift the bits in x by 4 positions to the right and fill the 4 left bits with sign bit (i.e. with 0 if the leftmost bit before shifting is 0 or 1 if the leftmost bit before shifting is 1).

Right Shift with zero fill (>>>) Operator

To obtain the result of >>> operator, the bits in the left hand side operand (which can be any integer expression) are shifted to the right as specified by the right hand operand (which can also be any integer expression) and the empty bit positions to the left are filled with 0.  Right shifting by 1 is equivalent to division 2. If shifting tales place then result will always be positive, as the rightmost bit would become zero.

Example:

y = x >>> 4

To obtain the value of y, shift the bits in x by 4 positions to the right and fill the 4 left bits with 0.

Java Bit-wise operators

The Java supports the following bit-wise operators:

~ (1’s complement or bit-wise complement)| (bit-wise OR)

& (bit-wise AND)

^ (bit-wise exclusive OR or XOR)

The operands of these operators must be of integer type only. If any of the operand of a bit-wise operator is of type byte, short or char then it is promoted to int before being used. If one operand is of type long then other is also promoted to long. So the type of the result will always be int or long.

Note: The operators |, & and ^ behave like boolean logical operators if both the operands are of boolean type.

Bit-wise Assignment Operators

The Java supports the following Bit-wsie Assignment Operators:

&=, |=, ^=

An assignment operator has the following syntax:

<variable><operator> = <expression>

The above assignment is equivalent to:

<variable> = <variable>  <operator> (<expression>)

For example the assignment:

 i &= i1 is equivalent to i = i & i1

Here i is an integer type variable and i1 is an integer expression.

Java Assignment Operator (=)

The assignment operator has the following syntax:

<variable> = <expression>

Here variable can be of primitive type or reference type. Similarly expression may result in a primitive data value or object reference:

Example: Assignment involving primitives.

x = 10;

Example: Assignment involving reference data type.

int x[];

x = new int [100];

Here new is an operator that returns an object reference.

Multiple Assignments

The assignment operator = may be used like any other operator to form a compound expression.

The operator can appear more than once in an assignment statement as shown below:

Example:

int x = 5, y = 6 , z = 7;

x = y = z; //multiple assignment statement

Here = behaves like an operator. It is a right associative operator, hence after the execution of the assignment statement, the value of variables x, y and z will be 7.

Example:

int  x[], y[];

x = y = new int[20];

Here new operator returns reference to an array, which can hold 20 int values. The reference is first assigned to y and then to x as the = operator is right associative.

Note: Assigning a reference does not create a copy of the object. So both x and y refer to the same array in this example.

Java Ternary Conditional Operator (? :)

The ternary conditional operator has the following syntax:

<condition> ? <expr1> : <expr2>

If condition (boolean expression) is true then <expr1> is evaluated otherwise <expr2> is evaluated.

For example, the following code segment, will store the maximum of x and y into variable max:

max = (x > y) ? x : y;

Here it is assumed that the variables x, y and max are of numeric type. The type of the variable max should be higher or same as the higher type among types of x and y.

Java Conditional Operators (or Short-Circuit Logical Operators)

The Java supports the following conditional operators:

|| (conditional OR)

&& (conditional AND)

The conditional operators && and || can be used to perform logical OR or AND operations on boolean operands. The operators are similar to boolean logical operators. The only difference is that if the result is definitely known after evaluating the first operand then second operand is not evaluated as discussed in the previous section. Hence these operators are also known as short-circuit logical operators. Sometimes this proves to be very useful in avoiding run-time exceptions.

For example, the following piece of code may result in a run-time exception, if the value of x is zero (assuming that x and y are integers), as it will lead to division by zero:

x = 0;

if( x != 0 & y/x > 5)

{

----

----

}

The possibility of the run-time exception can be avoided if we use the short-circuit operator && instead of boolean logical operator & as shown below:

x = 0;

if( x != 0 && y/x > 5)

{

----

----

}

Java Boolean Logical Operators

The Java supports the following boolean logical operators:

! (logical complement)

| (logical OR)

& (logical AND)

^ (logical exclusive OR)

Logical Complement ( ! ) Operator

This is a unary operator and the operand must always be a boolean expression. This acts as the negation operator, which negates a boolean expression as shown in the following table:

Boolean Expression(b) Logical Complement(!b)
true false
false true

Logical OR ( | ) Operator

The logical OR operator is used to combine two boolean expressions to form a compound boolean expression. The value of any boolean expression in Java is either true or false no matter how complex it is. The following table shows the value of boolean expression obtained by combining two boolean expressions using logical OR operator.

Boolean Expression(b1) Logical Complement(b2) Logical Complement(b1 | b2)
false false false
false true true
true false true
true true true

If first boolean expression is true then value of the compound expression will be true irrespective of the value of the second boolean expression. Even then the second boolean expression is always evaluated. This is different from the conditional (short-circuit) OR operator where the second boolean expression is not evaluated if the result of the first boolean expression is true.

If both the operands of the | operator are of integer type then this operator behaves like bit-wise OR operator.

Logical AND ( & ) Operator

The logical AND operator is used to combine two boolean expressions to form a compound boolean expression. The value of any boolean expression in Java is either true or false no matter how complex it is. The following table shows the value of boolean expression obtained by combining two boolean expressions using logical AND operator.

Boolean Expression(b1) Logical Complement(b2) Logical Complement(b1 & b2)
false false false
false true false
true false false
true true true

If first boolean expression is false then value of the compound expression will be false irrespective of the value of the second boolean expression. Even then the second boolean expression is always evaluated. This is different from the conditional (short-circuit) AND operator where the second boolean expression is not evaluated if the result of the first boolean expression is false.

If both the operands of the & operator are of integer type then this operator behaves like bit-wise AND operator.

Logical Exclusive OR or XOR ( ^ ) Operator

The logical exclusive OR operator is used to combine two boolean expressions to form a compound boolean expression. The value of any boolean expression in Java is either true or false no matter how complex it is. The following table shows the value of boolean expression obtained by combining two boolean expressions using logical exclusive operator.

Boolean Expression(b1) Logical Complement(b2) Logical Complement(b1 ^ b2)
false false false
false true true
true false true
true true false

If both the operands of the ^ operator are of integer type then this operator behaves like bit-wise exclusive OR operator.

Boolean Logical Assignment Operators

The Java supports the following Boolean Logical Assignment Operators:

&=, |=, ^=

An assignment operator has the following syntax:

<variable><operator> = <expression>

The above assignment is equivalent to:

<variable> = <variable>  <operator> (<expression>)

For example the assignment:

 b &= b1 is equivalent to b = b & b1

Here b is a boolean variable and b1 is a boolean expression

Java Comparison Operators (Relational Operators)

The Java supports the following comparison operators:

<, <=, >, >=,  = =, != and instanceof operator

These operators can be classified into three categories:
  1. Ordinal Comparisons or Relational Operators
  2. Equality Comparisons or Equality Operators
  3. instanaceof  Operator

Ordinal Comparisons or Relational Operators

Java Supports the following ordinal comparisons/relational operators:

<, <=, >, >=

These operators are used to compare ordinal data types i.e. data types where values have numeric order.

These operators cannot be applied on boolean types and reference types as these types do not have any numeric ordering among the values.

Equality Comparisons or Equality Operators

Equality comparisons test whether two values are same. They can be applied on all Java types including boolean and reference data types.

There are certain restrictions when these operators are used to compare reference data types.

Only references of the objects, whose classes belong to common type hierarchy, can be compared.

instanaceof  Operator


The instanceof operator is used to test the class of an object. The instanceof operator has the

general form:

object   instanceof   type

Here, object is an instance of a class, and type is a class type. If object is an instance of the

specified type or instance of any sub-class of the specified type, then the instanceof operator returns true. Otherwise its result is false.

Java Increment and Decrement Operators

Java supports the increment operator ++ and the decrement operator . 

These operators behave like increment/decrement operators in C/C++.

Java Arithmetic Operators

Java has five arithmetic operators:

  1. + (Addition)
  2. - (Subtraction)
  3.  * (Multiplication)
  4. / (Division) and
  5. % (Modulus)

The operands can be integers, floating-points or both. The arithmetic operators can be applied on

all the primitive types except the boolean. If a binary operator is used to combine two operands

of similar type then the type of result will also be same. But if a binary operator is used to

combine operands of different types then operand of lower type gets converted to the higher type

before the evaluation and the type of the result will be same as that of operand of higher type.

The type conversion rules are discussed in a subsequent section.



The behavior of the +, -, *, and / operator is same as in C/C++. The modulus operator can be

applied to integer as well as floating-point types while in case of C/C++ it can be applied to

integer types only. For example the following is valid in Java:

6.4 % 2.1

The result of the above expression will be 0.1.


Arithmetic Assignment Operators

The Java supports the following Assignment Operators like C/C++:

+=, -=, *=, /=, %=

An assignment operator has the following syntax:

<variable><operator> = <expression>

The above assignment is equivalent to:

<variable> = <variable>  <operator> (<expression>)

For example the assignment:

 x += 5 is equivalent to x = x + 5

For example the assignment:

 x += a * c is equivalent to x = x + (a*c)

Java Operators, Expressions and Assignments

Java provides a rich set of operators. Operators combine constants, variables and sub-expressions

to form expressions. Most of the operators in Java behave like C/C++ but there are few

differences, which are covered here.

Java operators can be classified as:

  1. Arithmetic Operators
  2. Increment and Decrement Operators
  3. Relational Operators (Comparison Operators to be more precise)
  4. Boolean Logical Operators
  5. Conditional Operators (or Short-Circuit Logical Operators)
  6. Ternary Conditional Operator
  7. Assignment Operator
  8. Bitwise Operators
  9. Shift Operators

Monday, 18 May 2015

Java input from keyboard

Example: The following example demonstrates how to read from the keyboard. It reads two numbers from the keyboard and display their sum.

Doing input from keyboard is a bit complex in java. The program makes use of classes in java.io package. The program makes use of import statement to import the classes from the java.io package, which contains most of the classes related to Input/Output. You can compare import statement with the #include directive in C/C++ though the comparison is not exact. For example, to use input/output related functions in C/C++ you must include the compiler directive #include<stdio.h> in your program.

import java.io.*;

public class AddTwoNumbers {
public static void main(String args[]) throws IOException{
DataInputStream dataInputStream = new DataInputStream(System.in);
int n1 = 0, n2 = 0, sum = 0, len;
String number;
System.out.println("Enter first number: ");
number = dataInputStream.readLine();
n1 = Integer.parseInt(number);
System.out.println("Enter second number: ");
number = dataInputStream.readLine();
n2 = Integer.parseInt(number);
sum = n1 + n2;
System.out.println("Sum = "+ sum);
}

}

The first statement in the above program is an import statement, which imports all the classes in the package java.io so that the classes can be used without qualifying.

The program makes use of the class DataInputStream to read from the keyboard. Creating an object of this class by passing System.in as parameter to the constructor creates an input stream connected to keyboard/console. The readLine() instance method of the class DataInputStream can then be used to read one line at a time from the keyboard. The readLine() method returns the line read as a string, so it has to be converted into int before doing addition.

If you input a String containing alphabets, the program will terminate with the following run time exception:

java.lang.NumberFormatException: <<String containing alphabets>>

The above program will compile and run successfully but you will see the following warning message:

Note: AddTwoNumber.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details

The above message appears due to the use of instance method readLine() of the class DataInputStream. This method has some known bugs and therefore sun has marked this method as deprecated, which means that this method may be discontinued in the future version of Java and its use should be avoided as far as possible. A method is deprecated when It has some known bugs or has side effects, which can cause some problems or may affect the performance.

We can rewrite the above program by avoiding the use of DataInputStream class and using other classes, whose methods are not deprecated. The following example is rewritten for this purpose.

Example: 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AddTwoNumbers {
public static void main(String args[]) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n1 = 0, n2 = 0, sum = 0;
String number;
System.out.println("Enter first number: ");
number = bufferedReader.readLine();
n1 = Integer.parseInt(number);
System.out.println("Enter second number: ");
number = bufferedReader.readLine();
n2 = Integer.parseInt(number);
sum = n1 + n2;
System.out.println("Sum = "+ sum);
}
}


 

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

Sunday, 21 December 2014

Java tokens, variables, constants

Java tokens are the atomic elements of Java. Java program are a collection of Java tokens separated by white spaces and comments.

Java is a free form language so it is not must to follow any special indentation rule. The only rule, which needs to be considered, is that the java tokens must be separated by an operator or by a separator or  by at least one white space character. In java, white space is a space, tab, or new line.

More than one white space characters may also appear wherever one white space character is allowed.

Java tokens can be classified into following categories:

  • Keywords
  • Identifiers
  • Literals
  • Operators
  • Separators
Keywords


There are appox. 50 reserved keywords in java. These keywords can not be used as identifiers. All keywords are in lowercase like C/C++.

The keywords const and goto are reserved but are not being used as of now. They  are reserved for the future use.

A new keyword assert was added by jdk 1.4.

In addition to the keywords, Java reserves the following:

true, false and null

These are the literal/constant values defined by Java, you may not use these keywords as identifiers.


Identifiers

An identifier is a word used in a program to name a local variable, method, class, interface, data members, package name etc. Java identifiers are case sensitive.

Name of the identifiers must follow certain rules:


  • A Java identifier must begin with a letter, dollar sign or underscore.
  • The subsequent characters may be digits also.
  • There is no length restriction on the identifiers i.e. they can be of any length.
  • Java allows Unicode characters in identifiers.
It is suggested that following naming convention may be followed while naming java identifiers:


  • Name of all the classes and interfaces start with a leading uppercase letter and each subsequent word also starts with a leading uppercase letter. Rest of the letters must be in lower case. Example: Student, Hello, HelloWorld, EmployeeInfo etc.
  • Names of all the public data members and methods start with a leading lowercase character. When more than one words are used in a name, the second and subsequent words start with a leading uppercase letter. Example: annualSalary, grossSalary, calculateSalary etc.
  • Names of variables that represent constant values use all uppercase letters and underscores between words.


Literals/Constants

A java literal represents a constant value in java. A literal or constant is a value specified in the source as opposed to one determined at run time. Literals may appear on the right side  in an assignment, or may be passed as arguments in method calls. Literals represent constant values so you can not assign a value to any literal i.e. they can not appear on the left side in an assignment.

Literals represent integer (byte, short, int, long) constants, floating point (float, double), constants, Character (char) constants and Boolean (boolean) constants in Java. Java also supports a literal null, which represents a null reference.

Examples:

Integer Literals: 200, -600, 0x1A, 015, 564L

Floating point Literals: 6.89, -3.15, 2.45f, 3.45d, 1.34E-01, 4.56E11

Character Literals: 'x', 'X', '\101', '\n'

Boolean Literals: true, false

String: "Hello", "abc", "xyz"

Java source file structure

All java source files must end with the extension ".java". A source file may contain at the most one top level public class. If a public class is present, the un-extended file name should be same as the class name i.e. if the class name is Hello then the source file name should be Hello.java. If a source file does not contain any public class then name of the source file can be anything.

A source file may contain an unlimited number of non-public class definitions.

There are four top level elements that may appear in a file. None of these elements is must. If they are present, then they must appear in the following order:

  1. Package definitions
  2. import statements
  3. class and/or interface definitions
A source file may have at the most one package statement. If a package statement is present it must be the first statement in the java program. Only comments may appear before the package statements.

A source file may have zero or more import statements. As of now you can think of import statements to be like #include statements in the Java Program. If present, all the import statements must come after the package statement and before the class/interface definitions.

A source file may have any number of class and/or interface definitions but there can be at the most one public class or interface.

main() method

A source file may or may not contain a class having main() method but a standalone java program always starts its execution from main() just like a C/C++ program. So the class from which we want to start the execution  must have the main() defined in it.

The main() method must always have the following signature:

public static void main(String args[])

Note: Method prototype is referred to as signature in Java.

The void keyword preceding main() method indicates that it does not return any value. The keyword public indicates that the main method can be accessed from anywhere. The main() method must be declared public as it is called by the code, which is part of the JVM and is outside the class containing the main() method.

The main() method takes one argument, which is the array of strings. Each element of the array represents one command line argument.

The main() method can also be invoked like any other static method form anywhere in the java program. It can also be overloaded like any other Java method.

It is very common to get an exception indicating that the main() method is not present while running a java program event when the main() method is present. This happens when the signature of the main() method differs from the above mentioned signature.

Comments

A program can be documented by inserting comments wherever required. The comments are simply ignored by the compiler.

Java provides three types of comments for documentation:
  1. Single line comment
  2. Multi line comment
  3. Documentation comment
Single line Comment






A single line comment spans only one line. It can be given on any line followed by the character "//". The syntax is similar to C++.

Example

// This line is a comment and will be ignored by the compiler
x = 4*y // This is also a comment but appears after assignment statement

Multi line Comment

The syntax of multi line comment is same as C/C++. A multi line comment  is enclosed between "/*" and "*/".



Features of Java

Simple and Familiar
  1. Java does not support operator overloading.
  2. Java does not support multiple inheritence
  3. Java does not use pointers.
  4. Java code does not support global variables.
Secure

Java programs run within the JVM and they are inaccessible to other java parts. This greatly improves the security. A java program rarely hangs due to this feature. It is quite unlike C/C++ program, which hangs frequently. Java's security model has three primary compenents:
  • Class loader
  • Bytecode verifier
  • Security manager
Java uses different class loaders to load class files (executable files) from local machine and remote machines. The class loaded from remote machines like Applet classes are not allowed to read or write files on the local machine. This prevents a malicious program from damaging the local file system.

Bytecode verifier verifies the bytecode as soon as class loader completes its work. It ensures that bytecode is valid java code. It almost eliminates the possibility of java program doing some malicious activity like accessing the memory outside the JVM.

The Security Manager controls many critical operations like file deletion, creation of threads etc. These operations are allowed only if the java program have sufficient permissions otherwise security manager does not allow the operations and generates Security Exception.

Platform Independent and Portable

Java programs are platform independent. They follow the paradigm write-once-run-anywhere.
A java program written for Windows platform can be run on any other platform (Unix, Linux, Solaris etc.) simply by copying the bytecode (".class" files). You do not have to copy the source code and compile it again as in case of a C/C++ program. This feature has made the java a powerful language. You can run bytecode on any machine provided that the Java Virtual Machine. Java Virtual Machine itself is platform dependent. It is actually the jvm, which converts the bytecode into the machine code and execute them.

So we can say that Java is a portable language. one more feature which makes Java highly portable, is that Primitive data types are of fixed length irrespective of the Platform. for example an int will be always of 4 bytes in Java. This is unlike C/C++ where size of int can be 2 bytes on some machines and 4 bytes on other machines.

 Object Oriented

Java is almost pure object oriented language but it supports primitive data types like byte, short, int, long, float, double, char, boolean for the performance reasons.

Memory Management and Garbage Collection 

Memory allocation for the Java objects is completely dynamic but Java does not have support for pointer arithmetic like C/C++, which simplifies the things. Moreover you do not have to worry about freeing the memory while writing java programs.  Whenever you run a java program, JVM also run another java program (thread to be more precise) called Garbage Collector in the background. Garbage collector keeps check on the java objects. Whenever a java object is not being used it is garbage collected by the Garbage Collector i.e. the memory allocated for the object is added to the pool/heap of free memory  and can be reused. This simplifies the task of the programmer to a large extent. This also eliminates lots of bugs caused due to improper use of pointer and memory management features like freeing memory explicitly.



Multi-threaded

Java was designed to meet the real world requirement of creating interactive, networked programs. Java provides support for writing multi threaded programs to achieve this. This allows the programmer to write programs that can do many thins concurrently. For example a GUI based application might be listening to user events and taking appropriate action, a separate thread might be doing printing and a separate thread might be downloading a file from some machine across the network, all of this being concurrently. This results in better performance and better CPU utilization.

It is possible to write multi-threaded programs in other language also but it is achieved only by making use of System calls while in case of java it can be achieved by using features of the language itself.

Rich API (Application Programmer's interface) / Class Library

Java API is very rich as compared to other languages specially when it comes to Network Programming.



Robust

Most programs fail for one of the two reasons:
  1. Memory Management
  2. Exceptional conditions at run time
While designing the language one of the aim was to ensure that java programs are as robust as possible i.e. they should rarely fail. So due importance was given to the above two factors in the Java.

In Java memory allocation and de-allocation is handled in language itself, which eliminates many problems caused due to dynamic memory management features in C/C++. Java also supports object oriented exceptional handling features to handle exceptional conditions, which occur at run time. This allows a java program to recover and continue execution event after an exceptional condition occurs.

Distributed

Java is designed for the distributed environment of the Internet. Java has built in support for various TCP/IP based protocols for this purpose. In fact, accessing a resource using a URL is similar to accessing a file on the local machine. Java also has features for Remote Method Invocation, which is somewhat similar to Remote Procedure Calls (RPC), This allows objects on different computers to execute procedures remotely. Java has built in API's for this purpose called RMI, Which stands for Remote Method Invocation.

Dynamic

Every java class is a separate unit of execution. A class is loaded at the run time only when it is needed. This is normally allows us to update a class without modifying the code using it. Default mechanism for binding methods in Java is also dynamic (run time binding).



Set Jdk path

If you install the JDK in folder c:\jdk\bin Type the command below:

SET PATH=%PATH%;C:\JDK\BIN;

Saturday, 20 December 2014

Running a Java Application

When a program is compiled (C or C++ program), it is directly translated into machine code that is specific to a platform/processor. But running a java program is a two-step process. In java translation from source code to the executable code is achieved using two translators:

Java Compiler: A java program is first compiled by the java compiler to generate bytecode. Bytecode resemble machine code but it is not specific to any platform i.e. it can not be executed on a computer without further translation.


Java Interpreter: Java interpreter executes the byte code after interpreting and converting into machine code.

Example: the following java program just displays the message "Hello World" on the monitor/console.

Step1: Write the following code into file "Hello.java" using any text editor:

public class Hello{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

Note: Java is a case sensitive language


Step 2: Compile the above written java program using the command:
javac Hello.java

Step 3: Run the java program
java Hello


Output: Hello World



Java: Type of applications

  1. Standalone applications
  2. Applets
  3. Web Applications
  4. Distributed Applications

1. Standalone applications: A standalone application is a program that runs on your computer. It is more or less like a C or C++ program.

2.  Applets: An applet is a application designed to travel over the internet and to be executed on the client machine by Java compatible web browser like Firefox or google chrome. Applets are also java programs but they reside on the servers. An applet can not be executed like standalone application. Applet can be executed only by embedding it into an HTML page like an image or sound file. To run an applet you need to access an HTML page which has applet embedded into it. When the web browser downloads such an HTML page, It subsequently loads the executable file, which contains Applet and then executes it on the local machine.

3. Web Applications: Web applications run on the web server. Web applications are accessed through web clients i.e. web browsers like firefox and google chrome. Whenever you access some web site by specifying the url, you are accessing some web application written in java.

Java servlets
Java server pages
HTML

Introduction to Java

Java is an object-oriented programming language developed by Sun Microsystems Inc in 1991.

Java has become the widely used programming language for the internet. Although while designing the language, the primary objective was to develop a programming language that is platform independent.

Sunday, 16 November 2014

Web SQL DB create, read, update and delete operations example

Here is the simplified example for web sql db create, read, update and delete operations:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db;
function createDatabase(dbName){
db = openDatabase(dbName, '1.0', 'Test DB', 2 * 1024 * 1024);
}

function createTable(tableName, arrFields){
db.transaction(function (tx) {
var fields = "";
for(f=0;f<arrFields.length;f++){
fields += arrFields[f] + ',';
}

fields = fields.substring(0, fields.length-1);

tx.executeSql('CREATE TABLE IF NOT EXISTS '+ tableName + ' (' + fields + ')');
});
}

function insertRecord(query){
db.transaction(function (tx) {
tx.executeSql(query);
});
}

function selectRecord(query, callBack){
var empArr = new Array();
db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, results) {
var len = results.rows.length;

// Create the object of emp
for(i=0;i<len;i++){
var emp = {
id:results.rows.item(i).id,
name:results.rows.item(i).name,
salary:results.rows.item(i).salary
};

// Add objects to array
empArr[i] = emp;
}
callBack(empArr); // This is the callback
});
});
}

createDatabase('db_emp');
createTable('emp', ["id", "name", "salary"]);
insertRecord('INSERT INTO emp (id, name, salary) VALUES (1, "Rahul", 5000)');

// We are using callback in this method
selectRecord('select * from emp', function (results){
console.log(results);
});
</script>
</head>
<body>
</body>
</html>

Friday, 14 November 2014

Order by filter in js controller

Below code will sort the list listLeaves in the descending order of date field .

$scope.listLeaves = $filter('orderBy')($scope.listLeaves, "-date")

Friday, 10 October 2014

Simple Coding Rules

1. Code should be proper indented.
2. Meaning full name of variables and constants.
3. Meaning full name of methods and classes.
4. No duplicate code.
5. No inline css.
6. No inline java script.
7. Html, css and java script code also be indented.
8. No html code should come with java services.
9. If you find a code two times in a class than make a separate method using that code.
10. If you find same code in two or more classes than make a separate class using that code and use       that class.