Thursday, 28 May 2015

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