Wednesday, February 15, 2012

chapter 2 Continuation

2.9 Instance operator:

                 a instance of B
                        |               \
                        |                 \
                        |                  \
       Object Reference      Class Name or Interface Name 

 EX1: String s = “surya”
System.out.println(s intanceof String); ------------gives output as true.
Ex2: Thread t = new Thread();
System.out.println(t instanceof Thread);------------gives true
System.out.println(t instanceof Object);------------gives true
System.out.println(t instanceof Runnable);------------gives true
Ex3: Object o = new Object();
System.out.println(o instanceof String);-----------gives false
Note: The type of a and B must be related, otherwise compile time exception like
incompatible types.
The null instance of any thing, the result is always false.


2.10. Type cast operator:

Type casting: Implicit type casting and Explicit type casting


Implicit type casting                                 |          Explicit type casting
This is responsibility of compiler             |            This is responsibility of programmer
No loss of information                              |            This result gives loss of information
Implicit type casting we can called          |             Explicit type casting we can called as Narrowing

as widening 

byte------short----}------>
                                          int----long-----float----double.


char----------------}------->


From left to right is implicit type casting.
From right to left is explicit type casting.
int a = 10;
byte b = a; gives compile time exception like required: byte, found: int.
int a = 10;
byte b = (byte)a;
This is explicit type casting. i.e. we are converting int type to byte type.


2.11. Conditional operator:
int a = (Boolean condition)?value if true: value if false;
int a = (b>40)?30:20;

2.12. New operator:
This operator is used for creation of objects.
[ ] is used for declaring and creating arrays.
class Demo
{
public static void main(String args[])
{
System.out.println(m(1)+m(3)*m(4)/m(5)+m(6));
}
public static int m(int i)
{
return i;
}
}





Output is: 9
1 + 3 * 4 / 5 + 6 = 1 + 12 / 5 + 6 = 1 + 2 + 6 = 9.
Before applying any operator all the operands must be evaluated from left to right and
then operators have to be applied based on the precedence.

2.13. Precedence of java operators:


Operator Precedence
OperatorsPrecedence
postfixexpr++ 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= += -= *= /= %= &= ^= |= <<= >>= >>>=













No comments: