Thursday, 28 May 2015

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

}