You are on page 1of 16

Increment & Decrements Operator

- Increment Operator :

1: Pre-Increment

2: Post-Increment

- Decrements Operator

1: Pre Decrement

2: Post Decrement

Expression Initial value of x Value of y Final value of x

Y=++x 10 11 11

Y=x++ 10 10 11

Y= - - x 10 9 9

Y=x-- 10 10 9

- It can apply increment & decrements operator only for variables. The platform constant value if
you are try to apply for constant value we will get compile time error.

- In string at increment and decrements operator are not allowed.

Fox example :

int x =10

int y = ++(++x)

System.out.println (y); : // Output : compile time error.

- For final variable we cant apply increment and decrements operators.

For example:

final int x =10;

x =20

System.out.println(x) //Output : Cannot assign a value to final variable x

Output :CE: cannot assign a value to final variable.

Ex: final int x=10;

x++;

System.out.println (x)
Output : CompileTimeErrot: illegal start of expression.

- We can apply increment /decrements operator for every primitive type except Boolean

Ex: int x =10

x++;

System.out.println(x)

int ch='a'

ch++

System.out.println (ch);

double d =10.5;

d++

System.out.println(d)

No Error in above example.

boolean b= true;

b++;

System.out.println(b);

Output CompileTimeError : bad operand type Boolean for un-array operator '++'

- Differenc between b++ & b=b+1

- If apply any arithmetic operator between two variable a & b, the result type is always max(int,
type of a, type of b).

max (int, type of a , type of b)

byte a =10;

byte b =20;

byte c= a+b;

System.out.println (c);

Result: Possible loss of precision found int; required byte;

Ex: 1

byte c = (byte) (a+b);


System.out.println (c);

Result: 30

Ex : 2

byte b=10;

b=b+1;

System.out.println(b);

Output : Compile time error

b = (byte)(b+1);

Output : valid.

Ex: 3

- But in case of increment/decrements operator internal type casting will be performed


automatically.

b++ = (type of b)(b+1)

Ex :

byte b=10

b++

System.out.println(b)

Arthmetic Operator:

If you apply any arithmetic operator between tow variable a & b the result type is always max(int,
type of a, type of b).

byte + byte = int

byte + short = int

short + short = int

byte + long = long

long + double = double;

float + long = float

char + char = int System.out.println ('a'+'b') = 195

char + double = double System.out.println ('a'+ 0.89) = 97.89

For check
- In integral arithmetic (byte, short,int,long) there is no way to represent infinity.Hence if infinity
is result we will get arithmetic exception in integral arithmetic.

System.out.println (10/0) = Run time exception

- But in floating point arithmetic (float & double) there is way to represent infinity.

-For this float and double classes contains the following the two Constance POSITVE_INFINITY &
NEGATIVE_INFINITY. Hence even though result is infinity we want get any arithmetic exception in
floating point arithmetic.

System.out.println (10/0.0) = Infinity

System.out.println (-10.0/0) = - Infinity

javap java.lang.Double

javap java.lang.Integer

- NaN (Not a Number) : In integer arithmetic (byte, short, int , long) there is no way to represent
undefined result. Hence the result is undefined will be get run time exception saying arithmetic
exception.

System.out.println (0/0)

- But any floating point arithmetic (Float & Double) there is a way to represent undefined result.
For this float and double classes contains NaN constant.Hence it result is undefined we would not
get any arithmetic exception in floating point arithmetic.

System.out.println (0.0/0) " NaN

System.out.println (-0.0/0) " NaN

- For any x value including NaN the following expression return are false.

System.out.println (10 <Float.NaN) false

System.out.println (10 <= Float.NaN) false

System.out.println (10 > Float.NaN) false

System.out.println (10 >= Float.NaN) false

System.out.println (10 == Float.NaN) false

System.out.println (Float.NaN == Float.NaN) false

- For any x value including Nan the following expression return true.

x != NaN;
System.out.println (10 != Float.NaN) true

System.out.println (Float.NaN != Float.NaN) true

- Arithmetic Exception:

a: It is run time exception but not compile time error.

b: it is possible only in integer arithmetic but not in floating point arithmetic.

c: The only operator which cause arithmetic are (/ or %).

- String Concatenation Operator:

- The only overloaded operator in java is + operator.Sometimes it's arithmetic position operator
and some time it's string concatenation operator.

String a ="durga";

int a=10, b=20, c=30;

Case 1: If at least one arguments is String type then + operator as a concatenation operator and
if both arguments are number type then + operator as a arithmetic position operator.

System.out.println (a+b+c+d); Result: Durga10+20+30 = Durga1020+30 = Durga102030

Case 2:

System.out.println (b+c+d+a); Result : 60Durga

Case 3:

System.out.println (b+c+d+a); Result : 30Durga10

System.out.println:

System.out.println (b+a+c+d); Result : 10Durga2030

- Consider the following declaration

String a ="durga";

int b=10, c=20, d=30;

- Which are the following expression are valid

Case 1 : a = b+c+d; Result : Compile Time Error

a = a+b+c; Result : Valid

b = a+c+d; Result : Compile Time Error

b = b+c+d; Result : Valid


- Relation Operator: (<, <=, >, >=)

- We can apply relational operator for every primitive type except boolean.

System.out.println (10 <20) ; Result = true

System.out.println ('a' <10); Result = false

System.out.println ('a' <97.6); Result = true

System.out.println ('a' > 'A'); Result = true

System.out.println (True > False) Result = Compile time error

- In cant apply relation operator for object types.

System.out.println("durga123" > "durga"); Result =Compile type error

- String of retalionl operator is not allowed otherwise to get compile time error.

System.out.println(10<20); Result : true

System.out.println (10<20<3); Result : Compile time error

- Equality Operator (== , !=)

- We can apply equlity operator for every primitive type including boolean type also.

System.out.println(10==20) Result : false

System.out.println('a' == 'b'); Result= false

System.out.println ('a' ==97.0); Result = true

System.out.println (false == false); Result = true

- We can apply equality operator for object type also.

- For object reference r1 , r2

- r1 == r2 return true; if one only if both reference operate to same object. Reference
compression are address compression.

Example 1:

Thread t1= new Thread();

Thread t2 = new Thread();

Thread t3 = t1;

System.out.println (t1 ==t2); Result =false

System.out.println (t1 ==t3); Result = true;


Example 2:

Thread t = new Thread();

Object o =new Object();

String s = new String ("durga");

System.out.println (t ==o); Result = false;

System.out.println (o == s); Result = false;

System.out.println (s == t); Result = Compile time error

- If you apply equality operator for object type then compulsorily there should be some relation
between argument types.(whether child to parent, parent to child or same type), other while we
will get compile time error saying incomparable type.

- Difference between (==) operator & equals() method :

- In general we can use == operator for reference compression (address compression) and equals
method for content compression.

For ex:

String s1 = new String("durga");

String s2 = new String ("durga");

System.out.println (s1 == s2); Result : false;

System.out.println (s1 equals s2); Result : true;

- For any object reference are r==null is always false. But null==null always true.

String s = new String ("durga");

System.out.println (s == null); Result : false

String s = null;

System.out.println (s == null); Result : true

System.out.println (null == null) Result : true

- instanseOf Operator:

- We can use instanseof operator two check whether to check object to particular or not.

Object o = l.get();

if (o.instanceof Student)

{ Student s = (Student)o } // Perform Student of Specific functionality


elseif (o instanseof Customer) {

Customer c = (customer)o

//Perform Customer specific functionlaty

Syntax : r instanceof x

Where r is object reference

x class| interface name

Ex : Thread t =new Thread();

System.out.println (t instanceOf Thread); Result : True;

System.out.println (t instanceOf Object); Result : True;

System.out.println (t instanceOf Runnable); Result : True;

Ex : Thread t = new Thread();

System.out.println (t instanceof String);

Result : Compile Time error : Incontrovertible type

- Use instanceof operator compulsory there should be some relation between argument types
(Child to parent, parent to child). Other wise compile time error saying incontrovertible types.

- null instanceOf false always:

Note : for any class of interface x "null instanceOf x" is always false.

Ex: (null instanceOf Thread) Result : false

(null instanceOf Runnable) Result : false

Bitwise Operator ( &, !, ^)

& (AND) - Return true if both arguments are true.

1 (OR) - Return true if atlease one arguments are true.

^ (XOR) - Return true if and only both arguments are different (true - false, false-true)

Ex : System.out.println (true & false); Result : false

System.out.println (true | false); Result : true

System.out.println (true ^ false); Result : true

Ex: System.out.println (4 & 5); Result : true :4 100 & 101 = 100

System.out.println( 4| 5); Result : true :5 100 or 101 = 101


System.out.println(4 ^5); Result : false :1 100 ^ 101= 1

- We can apply these operator for integer type also.

- Bitwise complement Operator (~):

- We can apply this operator only for integral type, but not for boolean type. if u are trying to
apply boolean type , then we will get compile time error.

- The most significant bit x as sign bit.

- 0 means positve number 1 means -ve number .

- positive number will be represented directly in memory where as -ve number will be
represented in directly in memory in twos complement form.

Boolean complement operator (!):

- We can apply this operator only for boolean types, but not for integer types.

System.out.println(! 4) Result : Compile time error (! cannot be applied to int)

System.out.println (!false) ; Result :true;

System.out.println(~ true);

Result : Compile time error (operator ~ can not be apply to boolean)

System.out.println (~ 4) Result : -5 100 - 011

Short curit operator ( &&, ||):

Difference between (& ,I) & (&&, ||)

- These are exactly same as bitwise operator (& ,|) except the following differences

&,I && , II

Both argument should be evaluated always Second argument is evalutaion is optional

Retaviely performance is low Relatively performance is high

Applicable for both boolean & integer types Applicable only for boolean but not for integer
types

Ex: int x=10, y =15;

if( ++x < 10 && ++y >15) {x++}

else { y++; }

System.out.println (x, y);

Output
Operator X y

& 11 17

&& 11 16

I 12 16

II 12 16

- If we replace && with & then we will be get run time exception showing arthemitice exception
by zero.

- Typecasting operator

There are two type of type casting.

Implicit type casting

Explicit type casting

- Implicit type casting:

1: Compiler is responsible to perform implicit type casting.

2: Whenever we are assigning smaller type of value to bigger data type variable implicit data type
casting will be performer.

3: It is also know as widening or up casting.

4: There is no loss of information in this type casting.

- The following are various possible conversion where implicit type casting will be performer.

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

char -> int -> long -> float -> double

- Explicit type casting :

1: Programmer is responsible to perform explicit type casting.

2: Whenever we are assigning bigger data type value to smaller data type variable then explicit
type casting is required.

3: It is also know as narrowing or down casting.

4: Where may be chance of loss of information in this typecasting.

- The following are various possibilities where explicit type casting is required.

double -> float -> long -> int -> short -> byte
int -> char

- When ever we are assigning bigger data type value to smaller data type variable by explicit type
casting. The most significant bits will be last we how to consider only least significant bits.

If you assign floating point values to the integer type, by explicit type casting the digit after
decimal point will be loss.

int x =130;

byte b =x;

Result : Compile type error :Possible loss of precision

int x ='a'

System.out.println (x);

Result : Compiler convert char to be automatically by implicit type casting.

int d =10;

System.out.println (d);

Result : Compile convert it to double automatically by implicit type casting.

- Assignment Operator:

There are three type of assignment operators.

Simple Assignment : int x =10;

Chained Assignment: int a=b=c=d=10;

Compound Assignment: a + =20;

Ex:

int a,b,c,d;

a=b=c=d =20

System.out.println (a+""+b+""+c+""+d);

Ex: We can not perform changed assignment directly at the time of declaration.

int a=b=c=d =20 : Result : Compile time error (Cannot find symbol : symbol :b lactation :
Class Test)

int b,c,d;

int a =b=c=d =20;

It is valid.
- Compound Assignment Operator:

- Sometimes assignment operator mixed with some other operator such type of assignment
operator are called compound assignment operators.

Ex:

int a=10;

a + =20;

System.out.println (a); Result : 30

- The following are all possible compound assignment operator in java

+=, -+, *=, /=, %=, &= |=, ^=, >>=, >>>=, <<=,<<<=

- In the case of compound assignment operator internal type casting will be performed
automatically.

Byte b=10 Byte b =10 Byte b=10

B=b+1 B++ B+=1

System.out.println(b) System.out.println(b) System.out.println(b)

Result Result Result

Compile time error B=(byte)(b+1) B=(byte)(b+1)

11 11

- Mix Compound assignment operator

int a,b,c, d;

a=b=c=d=20;

a+= b-= c*= d/=2;

sopln(a+ ""+b+""+c+""+d);

Result : -160,-180,200 10

- Conditional Operator (? :)

a++; = Unary operator

a+b; = Binary operator

(c)?b:d = Termenary operator

- The only possible ternary operator in java is conditional operator.

Syntax : int x=(10<20)?30:40


Ex: int x=(10<20)?30:40 Result : 30;

- We can perform mixing nesting of conditional operator also.

Ex:

int x =(10>30)?30: ((40>50)?60:70)

System.out.println (x) Result : 70

- New operator:

- We can use new operator to create object.

Ex Test t= new Test();

Note: So after create in an object constructor will be executed to perform initialization of an


object. Hence constructor is not for creation of object and it is for initialization of object.

- In java we have only new keyword but not delete keyword because destruction of useless object
is the responsibility of garbage collector.

- [] operator:

- We can use this operator to declare and create arrays.

int [] x = new int[10];

- Operator Precedence :

- Evaluation order of Java Operands:

- In java we have only operator precedence but not operand precedence.Before applying any
operator all operand will be evaluated from left to right.

class Test {

public static void main (String[] args){

System.out.println(m1(1)+m1(2)*m1(3)/m1(4)+m1(5)*m1(6));

public static int m1(int i){

System.out.println(i);

return i;

- new vs newInstance :

-We can use new operator to create an object if known classes as beginning.
Test t = new Test();

Student s= new Student();

Customer c = new Customer();

-newInstance is a method present in class Class. We can use new instance method to create
object if you don’t class name of beginning and if will available dynamically at run time.

java Test Student

Object Created for student.

java Test Customer

Object created for customer

java Test java.language.String

Object created for java.language.String

Ex:

clast Student{}

class Customer {}

class Test{

Public static void main(String[] args) throws Exception{

Object o =Class.forName(args[0]).newInstance();

System.out.println(("Object Created for:"+ o.getClass().getName());

In the case of new operator based on other requirement we can invoke any constructor.

Ex : Test t = new Test();

Test t1= new Test(10);

Test t2 = new Test("Durga");

- But new instance Method internally called no argument constructor. Hence to use new instance
method compulsory corresponding should contain no argument constructor. Other wise we will
get run time exception, saying Instantion Exception.

- Using new operator at run time is corresponding that class file is not available, then we will be
get run time exception saying NoClassGetFound error:Test.

Test t = new Test();


At run time if Test.class file is not available then we will get run time exception saying know class
Not found error :test

- While using newInstance method at run time is corresponding is not available then we will get
run time exception saying, ClassNotFoundException.

Object o = Class.forName(args [0]).newInstance();

Java Test Test123

At run time if Test123.class file is not available then we will get run time exception saying,
ClassNotFoundException : Test123

- Difference between new & newInstance:

New newInstance

It is operator in Java It is a method provide in java.lang.Class

We can use new operator to create object if we We can use this method to create object if we
know class name at beginning don't know class name at the beginning and it
is available dynamically at runtime.

To use new operator class not required to To use newInstance() compulsoury class should
contain no-args constructor contain no-args constructor other wise we get
Run time Initantiation Exception

At runtime if can file not available not available Runtime error


then we get compile time error :
NoClassDefExcepionError

- ClassNotFoundException vs NoClassDefFoundError

- For hard coded class name , at run time it corresponding that class file is not available then we
will be get run time exception saying NoClassgetFoundError,which is unchecked.

Ex: Test t = new Test();

- Get run time if Test.class is not available then we will get run time exception saying
NoClassGetFoundError:Test

- For dynamically provided class name get run time it corresponding that class file is not available
then we will get run time exception saying ClassNotFoundException, which is checked.

Ex: Object o= Class.forName(args[0]).newInstance();

java Test Student;

Get run time if Student.class file is not available then we will get run time exception saying
ClassNotFoundException:Student.

- instanceof vs isInstance() :

- instanceof is operator in Java, we can use instanceOf to check whether the given object is of
particular type or not and we know the type of beginning .

Thread t = new Thread();

System.out.println (t instanceof Runnable);

System.out.println (t instanceof Object);

- Each instance is method present in java.lang.class We can use is instance method to check
whether object is a particular type or not and we don’t about are beginning and is available
dynamically at run time.

Ex :

class Test {

Public static void main(String[] args) throws Exception {

Thread t = new Thread();

System.out.println(Class.forName(args[0]).isInstance(t);

java Test Runnable : Result : True

java Test String : Result : false

- isInstance() method is method equivalent are instanceOf operator.

You might also like