Friday, 10 July 2009

Operator precedence

Operator precedence

postfix
expr++ expr--
unary
++expr --expr +expr -expr ~ !
multiplicative
* / %
additive
+ -
shift
<< >> >>>
relational
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR

logical AND
&&
logical OR
ternary
? :
assignment
= += -= *= /= %= &= ^= = <<= >>= >>>=

To avoid confusion, it is recommended to use parenthesis ()
in expressions to avoid unexpected results

Boolean Logical Operators

Boolean Logical Operators
These operators operate on boolean operands and result
is also boolean. Like relational and equality, they are also
used frequently in if blocks and different loop for decision
making.
Operator Description
& Logical AND : evaluates to true if both operands evaluate to true
Logical OR : evaluates to true if both operands evaluate to true
^ Logical XOR : evaluates to true if odd no of operands are true
Short circuit OR
&& Short circuit AND
! Unary NOT
?: Ternary

Difference between & and &&

& : It evaluates both the operands
&& : It won't evaluate the second operand if the first operand evaluates to false
Example
Case 1
boolean flag = false ;
int count = 5 ;
if (flag & count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 6 here

Case 2
boolean flag = false ;
int count = 5 ;
if (flag && count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 5 here
In the second case, short circuit AND is used.When flag
evaluates to false, it does not go to the second part of
expression. Hence count ++ is not executed
Difference between and
: It evaluates both the operands
: It won't evaluate the second operand if the first operand evaluates to true
You can work it out on the lines of above example

Unary NOT
  • It simply returns toggled value of it's operand.
  • Operand remains unaffected.
    boolean flag = false ;
    if (! flag)
    {
    System.out.println ("flag still false " + flag) ;
    }
    Here, if block would be executed as NOT operator returns true but
    flag still holds false

    Ternary operator
    General syntax is
    exp ? statement 1 : statement 2
    exp: expression evaluating to a boolean
    If exp evaluates to true statement 1 is executed
    otherwise statement 2
    It can be thought of of as a shorthand for if else block

Relational Operators

Relational Operators
  • These operators are used to compare two values for equality or comparison.
  • Result of each comparision is boolean (true or false)


Operator Description
== Equal to Returns true if compared values are equal
!= Not Equal to Returns true if compared values are not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

boolean flag = 10 > 5 ; // flag set to true

  • These are mostly used with if block , different kind of loops (for,while,do while)
    to alter the program flow based on boolean output
    int num1 = 10 ;
    int num2 = 20 ;
    if (num1 == num2)
    {
    // do something
    }
    Remember, == operator is for equality check whereas = operator is assignment operator
  • Only Numeric types (int,float) and character type can be compared with relational operators
  • == and != can be used for any type

Use of == operator with String type and Objects
When you compare primitive types (int,float) using ==
you will get desired result but with Strings and other
Objects, you will get surprising results.

Case 1
String str1 = new String ("abc") ;
String str2 = new String ("abc") ;
if (str1 == str2)
{

// statement1
}
else
{
// statement2
}
Which statement would get executed ?
Apparently statement1 but actually statement2 would get executed
== compares the memory address for Objects (Strings are objects in Java)
As str1 and str2 have different memory addresses, comparison evaluates to
false and else block is executed.
Case 2
String str1 = "abc" ;
String str2 = "abc" ;
if (str1 == str2)
{

// statement1
}
else
{
// statement2
}
Now which statement would be executed ?
This time statement1
When Strings are initialized as literals , same value Strings
will have only one copy.Hence str1 and str2 point to same
location in memory

Operators

Java language provides number of operators. Many of these are similar to as in
other languages. All operators can be grouped into 4 categories
1 Arithmetic
2 Bitwise
3 Relational
4 Boolean Logical

Arithmetic operators
  • addition +
  • subtraction -
  • division /
  • Multiplication *
  • Modulus %
Modulus returns the remainder of division
10 % 3 will return 1
Each of the above has shorthand notation also
a = a + b ;
a += b ;
Both are equivalent

Increment and decrement operators

++ Single unit increment operator
-- Single unit decrement operator
Above two have two flavours : Post fix and Pre fix
Lets see what's the diference between two by working on a simple example
int a = 5 ;
int b ;
Post fix
b = a ++ ; // b will be set to 5
System.out.println ("b = " + b + " a = " + a ) // b will be 5 and a will be 6
Here, the value of a is used first (assigned to b) and then it is incremented
Pre fix
b = ++a ; // b will be set to 6
System.out.println ("b = " + b + " a = " + a ) // b will be 6 and a will be 6
Here the value of a is first incremented and then used (assigned to b)
In both cases, a will finally be 6 but value of b is different in both cases.
Decrement ( -- ) operators work in the same way, they decrease the value by 1

Thursday, 9 July 2009

Arrays

  • Arrays are a collection of like typed variables referenced by a common name.
  • Each element in an Array is referenced by a index.
  • Index starts from 0 , that is first element is stored at index 0
  • Arrays can be multi dimensional
Declaration
It is declared like other data types but with [] .
int arr1 [] ; // single dimension array
int arr2 [][] // two dimension array
int arr3 [][][] // three dimension array
Here int (could be any valid data type) specifies that this array can hold int values
Initialization
There are different ways to initialize an array
Using new operator
float arr1 [] = new float [5] ;
new operator dynamically allocates memory at runtime
Here 5 is the size of array, number of elements it can hold
Now each element can be accessed by it's index and assigned a value
Note: Compiler provides default value (depending on data type) to each
element.
arr1 [0] = 10 ;
arr1 [3] = 20 ;
and so on
Don't go beyond index 4, because that is the last index.
It will result in ArrayIndexOutOfBoundsException

Curley braces style
float arr1 [] = {5.0 , 3 , 4 } ;
Values are given as comma seperated list enclosed in { }
here, size need not be specified as it is same as the number of
values given in the list

Multi dimensional arrays
Two Dimensional
You can think of it as a row column matrix
double twoDim [] [] = new double [dim1] [dim2] ;
dim1 : rows in the matrix
dim2 : columns in the matrix
int a [] [] = new int [3] [3]
a00 a01 a02
a10 a11 a12
a20 a21 a22
Remember, both the indexes start at 0
int a [] [] same as int [] a [] same as int [] [] a