Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views17 pages

Operators in Java Class 9 Morning Star

The document provides an overview of operators in Java, categorizing them into unary, binary, and ternary operators, along with examples of their usage. It explains how operations are performed using operators and operands, detailing arithmetic, relational, and logical operators. Additionally, it includes sample code demonstrating the implementation of these operators in Java programming.

Uploaded by

bholi83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views17 pages

Operators in Java Class 9 Morning Star

The document provides an overview of operators in Java, categorizing them into unary, binary, and ternary operators, along with examples of their usage. It explains how operations are performed using operators and operands, detailing arithmetic, relational, and logical operators. Additionally, it includes sample code demonstrating the implementation of these operators in Java programming.

Uploaded by

bholi83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Op er at or s in Ja va

.
An oper ation is an actio n perfo rmed · eithe r to• modify the value held
~more valu
one aornew val b
on uce es b' . .
by one or both of the valu es, or to prod
ue y com 1n1ng existing values.
ation s on
Ope rato rs are spec ial symb.ols that perfo rm ~pecific oper
one, two, or more oper ands

0
Oper ands can be cons tant ~ a varia ble. An expr essio n is a comb inati on of oper ands and
oper ator that perfo rm a spec ific oper ation .
ol and at least one value.
Therefore, an oper ation is perfo rmed usin g at least one symb
► The symb ol used in an oper ation is calle d an oper ator .
► A valu e invo lved in an oper ation is calle d an oper and .
. Form s Of Ope rato rs
oper ands each takes . They are:
There are basic ally three form s of oper ators depe ndin g on the
► Unar y Ope rator s (One oper and)
► Bina ry Ope rator s (Two oper ~ds)
► Tern ary Ope rator s (Thr ee oper ands ).

Unar y Ope rato rs


rent kind s of oper ation s such
Unary oper ators requ ire only one oper and to perfo rm diffe
ting a bool ean value. ·
as incre asing / decr easin g, nega ting an expr essio n, or inver

Symbol Ope rato r Nam e


:.. _t_:_ ____ -
Ope ratio n
+ Unar y plus oper ator indic ates positive valu e (however, num bers
are positive with out this)
- Unar y minu s oper ator nega tes an expr essio n
++ Incre men t oper ator incre men ts a valu e by 1
-- Decr emen t oper ator decr emen ts a valu e by 1
-
! Logical com plem ent oper ator inve rts a bool ean valu e (

The following prog ram dem onst rates the diffe rent Unar
y Arith:µietic oper ators in Java .
Progra1n 1
Public class unary _Op1 {
public void main()
{

-
_________:.::::.::::~=~~====:.__:=--------------
Total Computer Applications - IX
int x, a=5, b=10, c=15, d=20;
X = a++;
System.out.println("Postfix ++ ·operator resulted in " + x);
X = ++b·
System'.out.println("Prefix ++ operator resulted in" + x);
X= C--·
' d . "+ x)·
System.out.println("Postfix -- operator resulte in '

;;s;~:.out.println{"Prefix -- operator resulted in " + x);

;;s;:~.out.println("Unary operator resulted in " + x);


}
}

Program 2
class Unary_Op2{
public void main()
{
II result is now 1
int result= +1;
System.out.println(result);
II result is now 0
result--;
System.out.println(result);
result++;
II result is now 1
System.out.println(result);
result = -result; II result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); II false
System.out.println(!success ); II true
}
}

Binary Operators
The Java programmi~g language provides operators that perform adqition, subtractior
multiplication, division and modulus on integer and floating point numbers.
The following table summarises the binary arithmetic operations in Java ..
~
, Symbol ..
Operator Name . -·· Example
-

+ Addition Operator n:::; n + 1;


- Subtraction Operator n-:-n-1;
* Multiplication Operator n n * 1;
I Division Operator n - n / 1;
% Remainder Operator n n % 1;
Op er at or s in Ja va
ow n be lo w th t d .
n ex am pl e pr og ra m is sh Bi na ry Arithmetic
a em str at es th e different
on
, pe ra to rs in Ja va .

me tic _O p{
public cla ss bin ar y_ Ar ith
public vo id ma in( )
{
int X, y = 10, Z = 5;
X = y + z;
er ato r resulted in + x);
Sy ste m. ou t.p rin tln {"+ op
II

X = y- z;
er ato r resulted in " + x);
Sy ste m. ou t.p rin tln ("- op
X:: : y * z;

er ato r resulted in + x);


11

Sy ste m. ou t.p rin tln ("* op


x = y I z;
er ato r resulted in + x);
11

Sy ste m. ou t.p rin tln {"/ op


X = y % z;
er ato r resulted in + x);
11

Sy ste m. ou t.p rin tln ("% op


}
}

Te rn ar y O pe ra to rs on al
er at or wh ic h us es th re e op er an ds . It is a co nd iti
is an op
Th e te rn ar y op er at or "? :" r th e if. .th en .. els e sta te m en t. Th e first op er an d
sh or te r sy nt ax fo
op er at or th at pr ov id es a is tru e th en th e va lu e of th e se co nd op er an d
is
if th e ex pr es sio n
is a bo ol ea n ex pr es sio n;
th e va lu e of th e th ird op er an d is re tu rn ed :
re tu rn ed ot h~ rw ise

Sy nt ax
____;__ _ _ _)
:__e_x_:p_r_e_ss_i_o_n_?_._v_al_u_e_l_:_v_al_u_e_2_ _ _ _ _ _ _
(________b_o:_o:..:.l~ean.
two numbers
pr og ra m wh ich de ter mi ne s the greatest among
Let us co ns ide r on e
class ma xfi nd er {
int b)
sta tic vo id ma xim (in t a,
{
int ma x = a> b ? a : b;
Sy ste m. ou t.p rin tln (m ax );
}
}
- :_ _ _ __ _ _ _ _ _~~
Tot al ~~ ~~
com
~Aput
~~ erltt_
PPc_
'c".'a~ti~o'.':ns~-~IX=----~ ~ -~ ~ ~
Ty pes of Op era tor s
·pu late var iab les . We can div ide all
Jav a pro vid es a rich set of op era tor s to man1 the J%
ope rat ors into the following gro ups - .
► Ari thm etic Op era tors
► Rel atio nal Op era tors
► Logical Op era tors
► Inc rem ent and De cre me nt Op era tor
s
► Sho rth and Op era tors

Ar ith me tic Op era tor s


Ari h
. .
· m ath em atic al exp res sio ns 1n h
· tors are use d lil the sam e wa y t at the y ar1
usetd 1?e tic ope raT h -&'. llowing tab le list s the
m alg ebr a. e 10 ari thm etic ope rat ors : .
-
· ger van·able A hol ds 10 and var iab
Ass um e inte le B hol ds 20, the n -

+ (Addition} Ad ds val ues on eith er sid e of the ope


rat or. A + B wil l give 30
- (Subtraction} Sub trac tsri ght -ha n~o per and fro mle ft-h
and ope ran d. A - B wil l give -10
* (Multiplication) Mu ltip lies val ues on
eith er sid e of the ope rat or. A * B ·wil l aiv
1:r e 200
/ (Division) Divides left -ha nd ope ran d by right-har,id
ope ran d. B / A wil l give 2
% (Modulus) Divides left -ha nd ope ran d by rig ht- han
d ope ran d B % A wil l give 0
and ret urn s rem ain der .
++ (Increment) Inc rea ses the ·val ue of ope ran d by 1.
B++ giv es 21
-- (Decrement) De cre ase s the val ue of ope ran d by 1.
B-- giv es 19
Re lat ion al Op era tor s
Rel atio nal ope rato rs in Jav a are use
d to c~m par e 2 or mo re ope ran ds.
rela tion al ope rato rs gre ate r tha n(> ), Jav a pro vid es s~
les s tha n(< ), gre ate r tha n or equ al(
equ al(< =), equ al(= =), and not equ al(! >= ), les s thano
=).
Bin ary num eri c pro mo tion is app lied
to the ope ran ds of the se .op era tor s.
res ult s in a boo lea n val ue. Rel atio nal Th e evaluatior
ope rat ors hav e pre ced enc e low er tha
ope rato rs, bu t hig her tha n tha t of the n arithmeti(
ass ign me nt ope rat ors . Ge ner al for ma
t is,
C variable relatlon_operato.- value
-- -- -- -- -- -- -- -_ _ _ _ ;; _ _ _ .. .. .)
Ass um e var iab le A hol ds 10 and var
iab le B hol ds 20, the n -

Ch eck s if the val ues of two ope ran


yes the n con diti on bec om es tru e. ds are equ al or not if (A ;:: = B) is
!= (not equ al to) '
Ch eck s if the val ues of two ope ran ds not tru e.
are equ al or not , if
val ues are not equ al the n con dition (A I= B) is
bec om es true.
true.
l /
I
'1· 5t

in J a v a
O p e r a to r s
th e is
th e v a l r a n d is g r e a te r th a n u e (A > B)
(g r e a te r th a n ) Checks if
ig h t o
p e
u e o~ left o e n .c o n d it io n becomes tr . n o t tr u e .
v a lu e o f r yes th
k . . p e r a n d , if . s s th a n th e
v a lu e (A < B) is
Ch ~ is le
(less th a n ) ~ S f f t hrea n d ~ o f left o p e r a n d n b e c o m e s tr u e . tr u e .
o f r ig h t o p
e n d it io
' y e s th e n c o or (A>= B) is
C h k . th e v a l e r a n d is g r e a te r th a n n
= ( g r e a te r t h
an e c s ff v a lu u ; ~ f left o p , if y e s th e n c o
n d it io n o t tr u e .
l to th e p e r a n d
r e q u a l to) equa
e s t r u e o nght o
b e c o m e .
lu is le s s th a n or equal (A < = B) is
a
o r C h e c k s i f th e v f _e o f left o p e r a n d e s th e n c o n d it io n true.
= (less t h a n e
to t h e v a lu Q n g h t o p e r a n d , if
y
l to ) u
b e c o m e s t r e.
qu a

n t r e la ti o n a l o p e r a to r s
if f e r e
r a m is s h o wn b 1
a t d e m o n s tr a te s th e d
prog . , e ow
th
A n e x a m p le .
in J a v a . mo{
e la ti o n a lO p e ra to rs D e
R
public class lO p e ratorsDemo
()
ti o n a
public Rela
' {
= 5;
in t X = 10, y y));
t. p ri n tf n (" x > y : "+(x >
System.ou (" x < y : "+(x <
y)); ,
t. p ri n tl n
System.ou x >= y : "+(x >= y
));
t.pri n tf n ("
System.ou
tl n (" x < = y : ·+ (x <= y));
t.prin
System.ou x = = y : ·+ (x == y));
t. p ri n tl n ("
S y s te m .o u (· x f= y : "+(x f=
y));
t. p ri n tf n
S y s te m .o u
}
} th e
l O R " o p e r a ti o n , i.e.,
erators gica k e e p in m in
d
o g ic a l O p lo g ic a l A N D~ a n d "lo n e th in g to
L rm " s. O g
s a r e u s e d to p e r f o te in d ig it a l e le c tr o n ic ., it h a s s h o r t- c ir c u it in
a to r R ga e , i. e
These oper r to A N D gate and O th e f ir s t o n e is fa ls g a d e c is io n .
s im il a a lu a te d if f o r m a k in
~nction o n d it io n is n o t
ev
e v e r a l c o n d it io
ns
1 s th e s e c o n d c
n s iv e ly to te s t f o r s
B h o ld s fa ls e , th e n -
u s e d e x te e a n d v a r ia
b le
{ ffect. It is sA h o ld s t r u
m e B o o le a n v a r ia b le Example
r ssu
e
t io n · ,
n d s (A & & B) is f a ls
D e s c r ip per a
e r a t o r e r a to r . I f b o th th e o
O p
e d L o g ic a l A N
D o p
it io n b e comes µue.
& (l o g ic a l and) C a ll
- z e r o , t h en the co n d
tw o (A 11 B ) is tr u e
& are no n f th e
O p e r a to r. If any o on
C a ll e d L o g ic
al O R
o , t h e n t he conditi
er
I I (logical or) are non-z
operands A & & B) is
tr u e
tr u e . s e s th e !(
becomes ver
r . U s e to r e

f OogicaI n o
t)
C a ll e d L o g
logical s t a t
t h e n Logica
ic a l N O
eo
l NO
f it

__
s

__
T

__
o

_
O
p
___
p
e
__
e
r
_
a
r a
nd
T o p e r a to r w
to
. I~ a c o n d it io n is tr u e
ill m a k e fa ls e .
_,;;.;,;.;;;,-_,,
_
.,.
~ r.
~exa• amp le prog ram is show n below that dem onst rate s the diffe rent Logical oper 81

Jblic class Logical_Op{


public void main()
{
boolean x = true· I

boolean y = false;
System.out.println("x && y : " + (x && y));
System.out.println("x II y: "+ (x II y));
System.out.println("!x : " + (!x));
}

Ass ignm ent Ope rato rs


'=' Assi gnm ent oper ator is used to assi gn a valu e to
any v~a ble. It ha_s a right to le/
on righ t han d side of oper ator is assi gned to the variable or
asso ciati vity, i.e., valu e given
befo re usin g it or should ~
the left and ther efor e righ t han d side valu e mus t be decl ared
a cons tant .

Des crip tion Exa mpl e


II
Operator
Simp le assig nme nt oper ator. Assigns valu es from C = A + B will assign
=
righ t side oper ands to left side oper and. valu e of A + B into C

Add AND assi gnm ent oper ator . It adds righ t C += A is equivalent to
+=
oper and to the left oper and and assig n the resu lt C=C +A
I
to left oper and. I

Sub trac t AND assi gnm ent oper ator. It subt ract s C -= A is equivalent to
-- C=C -A
I

righ t oper and from the left oper and and assig n )
I
__J
the resu lt to left oper and. I

Multiply AN:O assig nme nt oper ator. It mult iplie s C *= A is equivalent to:
*= I

righ t oper and with the left oper and and assig n C=C *A
I

the resu lt to left oper and.


C / = A is equivalent to
/= Divide AND assig nme nt oper ator. It divides left
oper and with the right oper and and assig n the C= C/A I

resu lt to left oper and.


%= Mod ulus AND assi gnm ent oper ator. It take s C %= A is equivalent to
mod ulus usin g two oper ands and assig n the C=C o/oA
resu lt to left oper and.
<<= Left shift AND assig nme nt operator. C <<= 2 is same as c~
C << 2
>>= Right shift AND assig nme nt oper ator. C >>= 2 is same as c~

_,._ C >> 2
---
....--
&=
Operators in Java
bitwise AND assignme n t operator. C &= 2 is same as C =
C&2
- "= bitwise exclusive OR an d assignment
. operator. C "= 2 is same as C =
- 1= bitwise inclusive OR an .
, d assignment operator.
C" 2
C I= 2 is same as C =
I c12
I
·- •-•

~he Java assignment operator statement has the following syntax:

C <variable> = <expression>
------- st----___,;_--~ ~~
)

f the value already exi s in the variable it is overwritten by the assignment operator(=).

public class Assign_Op_Demo{


public void main()
{
· II Assigning Primitive Values
int j, k;
j = 1O; // j gets the value 10.
j = 5; _// j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : "+ j);
System.out.println("k is : " + k);
// Multiple Assignments
k = j = 10; II (k = 0 = 10))
System.out.println("j is : " + j);
System.out.println("k is : ... + k);
}

Increment and Decrement Operators


The++ and -- are Java's increment and decrement operators.
The increment operator increases its operand by one. The decrement operator decreases
its operand by one. For example this statement
x = x+l ;
Can be rewritten like this by using increment operator
x++;
Similarly this statement
x=x- 1;
Can be rewritten like this by using decrement operator
x-- ;
lication s - IX
comput er APP ~
1
: : - - - -_ _ _ _ _ _ _T<_o_ta_ ~
Prefix and Postfix Operat ors after(postfix) its operan d. It is important
(prefi.X) or I
E. t rs.
ither ++ or -- can appear . before these opera o
note the following when using t operato r follows change -then-u se rule i
t or decrem en . d th ·I
The prefix (++op/-- op) increme n t ) the value of their operan , en use then
decrem en ~
they first change ( increme nt 0
1:
Val . al . the expression. t decrem ent operato rs follow use-the n-chan ge l'll,
ue m ev uating . d h -~
increme n or ,
Th e postfix (op++/ op--) f th . operand in evaluat ing the express ion an t en chan --s
. th value o err .
i:e., they first use e th
e O erand's value.
(increm ent or decreme nt) p
► Pre Increm ent / Pre Decrem ent Operat or
r. ment· First Increm ent Value and then Assign Value.. . .
Pre 1ncre · .
increme nt value inside "Var" variable . New value is assigne d to 1tseu
++Var will ,,, .
Pre Decrement: First Decrem ent Value and then Assign Value.
--Var will decrem ent value inside "Var" variable . New value is assigne d to itself.

► Post Increm ent / Post Decrem ent Operat or


Post Increme nt: Increme nt Value of Variabl e After Assigni ng.
Var++ will increme nt value inside "Var" variable after assigni ng old value to itsell
Post Decrem ent: Decrem ent Value of Variabl e.After Assigni ng.
Var-- will decrem ent value inside "Var" variable after assigni ng old value to itsell

The shortcu t increme nt/ decrem ent operato rs are summa rised in the followin g table.

++ op++ Increme nts op by 1; evaluat es to the value of op before ·it was


increme nted
++ ++op Increm ents op by 1; evaluat es to the value of op after it was
increme nted
op-- Decrem ents op by 1; evaluat es to the value of op before it was
decrem ented •
--op Decrem ents op by 1; evaluat es to the .value of op after it was
decrem ented

Solved Exercis e
Q.1. Consider the following code snippet :
inti= 10· .
'
int n = i++%5·
'
What are the values of i and n after the code is execute d?
. .
Ans. 1 =11
n=O
Op era tor s in Ja
i an d . . va
W ha t are the fin al va lue s of ix .
u us e the pre fix ver s1· n( if_instea of us ing the postf inc rem en t op era tor
d
(i++), yo on ++i))?
. 11;
I=

n = l;

If in t a =5 , wh at wo uld e
b th
· ? e Value of a an d b aft er ex ec uti ng two dif fer en t
ex pr es sio ns
(i) b = a+ + + a; (u"•)·
b =+ +a + a·,
(i) b = 11 (as 5+ 6) (ii} b = 12 (as 6+6)

Exercise Qu es tio n
pla in h h
In the fol low ing pr og ram ' ex W · pn·nt ed twice in a row:
Y e va lue "6" Is
t
class Pr eP os t{
public void ma in( )
{
in ti= 3; .
i++;
11 "4" ·,n1 p·= 10 - - - --·- -- -- -- -- -- -- -
Sy ste m. ou t.p rin tln (i);
f - - ) + ( f + -+ ) J., -t- + p
++i; p 4- .=- (
Sy ste m. ou t.p rin tln (i); II "5" \0 + ( 10 + C) -+ 11 )

\0 +\ 0- +~ 4 1\ ~ L-l O
Sy ste m. ou t.p rin tln (++ i); II "6"
II "6" i \'1 t c°' = 5 } b = 9 , c ;
Sy ste m. ou t.p rin tln (i+ + ); ++ b - + +,. .
C d= CA - - ) - V\

Sy ste m. ou t.p rin tln (i); · // "7"


~=Zl - 10 - % .= _l O '
}
iY'\\: ~ = 18
} 'c\ ,=,( =C~--) ~ +-+ ~

I'&* (,i ~ l~)


Sh or th an d Op er at or s \?/· ~ : ~11&
nm en t
ds th at sim pli fy the co din g of a ce rta in typ eo f a as sig
Jav a offers sp ec ial sh or th an
sta tem en t.

For ex am ple ,
X =X + 20;
Can be wr itte n as
X += 20;
op era to~ wo rks
th e co mp ile r to as sig n to x the va lue of x + 20 . Th is
The op era tor += tel ls nd op era tor 1s :
era tor s in Ja va . Th e ge ne ral for m of Ja va sh or tha
for all the bin ary op
_ _ _ _ _ __ _ _ _ _ _ _)
r=a:.:to=r
=--= e
_:: :.:
xp~ e_
r...: • •
_ _
i n
o_ .::.__
¥.~arla==b=l=e~o~p::e=
~...:.:.::__:
I
ns- IX
uter Appl icati o
Tota l ContP h. h can be used to mak e the c~
. nrne nt oper ator s w ic
nd ass1g
The table show s all cornpou
more read able and efficient.
Mea ning
X = (x + y);
?< += y;
+= X = (X - y);
X -= y;
-- X = (x * y);
X *= y;
*= X = (x / y);
X /= y;
/= X = (X % y) ;
X /o= y;
0
%=
x&= y~
X = (X & y);
&=
x .l= y; X = (X ! y);
1=
X "= y;
X = (X A y);
A=

X <<= y; X = (X << y);


<<=
>~= y; X = (X >> y);
>>= X

>>>= X >>>= y·,, X =: (x >>> y);

An example prog ram is show n below that dem onst rates


the diffe rent Sho rtha nd operators
in Java . -
class Comp_Assign_op{
public void main()
{
int x=S-,
int y=10;
X += y;
System.out.println("The addition is:"+ x);
x-= y;
8 Ystem.out.println("The subtracti_on is:"+ x);
X *:: y;

SySlem.out.println("The multiplication is:"+ x)·


XI= y; '
.. .
System.out.println("The ct·1v1s1o
01
n is"+ x)· 1
X 10= y;

System.out.println("Th .
} . e remainder is:"+x);
}
ERATO RS
CHY OF OP . O
a higher
p e ra tors with efined
c e d e n c e
a s p re well-d
li e d is k n o w n we r p re c e d e n c e . J a va h as lu a te d w h e n
~E8: rs a r e a p p
e ra to a lo eva
in w h ic h o p b e fo re o p e ra to rs With to rs in an ex p re 8 sl o n a re ave a
c e a r e a p p li e d
W h ic h th e o p e ra p U c a u o n a n d division h
Th e o r
e c if y in g th e o r d e r in rs . F o r e x a m p le , m u J ti
le s c a n b e o verridden by
p re c e d e n s p e ra to e n c e ru
r p r
r es s io n h a s s e v e ra l o p a n d s u b tr a c ti o n . P re ce d
ru. lee
h s fo . d d it io n
·tpprea rceendthe necsee sth a n a th e table
bthige .e x
: O p e ra to rs a t th e to p o fth e s a m e
n b e lo w have d
o r d e r o f J a v a is s h o w e ta b le . If two o p e ra to rs
th
p r e c e d e n craeto rs _ lo w e r d o w n in y a p p e a r m a s ta te m e n t.
eXJ)!iCJ o p e r th e
o ~ e fo re e o rd e u lt Prece enc
e.
T h e o p enr:c~
e e , th e y a r e a p p li e d m th rr id e th e d e fa
are eadp p li ove
o m c a n u s e P a re n th e s e s to
That is , fr Yo u
le ft to r ig h t.
prec ti v it y .
•. , l A s s o c ia
e le m e n t
access array ember
tm
a c c e s s o b je c
() p a r e n th e s e s e
crement n o t associativ
++ u n a r y p o s t-in r e m e n t
15 ec
-- u n a r y p o s t- d
crement right to left
++ u n a r y p r e -i n
1 4 .- ecrement
u n a r y p r e -d
u n a r y p lu s
+ s
u n a r y m in u
l NOT
! . u n a r y lo g ic a
NOT
u na r y b it w is e
right to left
cast .
0n
13 0 o b je c t creat1 left to right
new e
m u lt ip li c a ti v left to right
12 *I% ti o n
a d d it iv eo n c a te n a
11 +- s t n.ng c left to right
+
s h if t
ve
10 << >> n o t a ss o c ia ti
>>>
r e la ti o n a l
< <=
9
> >= left to right
in s t a n c e o f
·left to r ig h t
8 ==
!= left to right

& left to right


7
A left to right
6
5 I
4 && :
-~li~c~a~ti~·o~n~s~-~IX~==;=~==:==:=.~==:::
r:;=======::;:;===========~T=ot=·a=l~C=o=m~p=u~t: er Ap~•!_'~===========r~le:;f;t-;to~n:·ghilitt~--
3 logical OR right to left
II
2 ?: ternal"Y ri~t to left It C
assignment
l += -=
*= /= %=
&= "= 1=
<<= >>= >>>=

Example
In an operation such as,
result = 4 + 5 * 3
· dded to 4 a-iving the Final Result value as 19.
. * . aluated and the result 1s a 0-
First (5 3) 1s ev '+' ccording to the chart.
Note that'*' takes higher precedence than a
th r applies to all the operators.
This kind of precedence of one operator over ano e

Precedence and Associativity of Operators


Precedence order
When two operators share an operand the operator with the _higher precedence go:s first
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 2) +3
since multiplication has a higher precedence than addition.

Associativity
Associativity is the order in which an operator gets executed. Prefix and postfix gets the
highest precedence among the operators and the associativity of these is from right to left
The operator gets executed from right to left in an expression.
When an expression has two operators with the same precedence, the expression is
1
evaluated according to its associativity. For example x = y = z = 1 7 is treated as x = (y == 1
= 17)), leaving all three variables with the value 17, since the = operator has right-to-le!
associativity (and an assignment statement evaluates to the value on the right hand side).
On the other hand, 72 / 2 / 3 is treated as (72 / 2) / ~ since the / operator has left-to-
right associativity. Some operators are not associative: for example, the expressions (x <i
y <= z) and x++-- are invalid.

EXPRESSIONS
An expression in Java is any valid combination of operators, constants, variables a.n°
1
•method invocat~ons, which are constructed according to the syntax of the language, th~
evaluates ~o a single value. An expression can be mathematical or lo ·cal de ending upo~
the result 1t produces. gi . P

double result= 1.5 + 2.5; / / result is now 4.0


Operators in Java
)fatbematical Expression
When an expression uses mathe .
. maticaI operat 1.t . kn
It can be of different types: or is own as mathematical expre~sion.
► Pure Expression ·
When similar types of operands ar · ·
. . ,.,
Express1on. · kn own as Pure
e present 1n an expression , 1·t is
e.g int a =10, b = 20 c·
' '
c =a+ b·'
.

► Mixed Expression
When different types of oper d · .
Expression an s are present in an expression it is known as Mixed
e.g. float sal = 10000.ggf;
int da = 2000·
'
float total_sal = sal + da·
► Complex Expression
'
When more than one operat .
according to the rul f or appears in an expression, evaluation is performed
- es O the precedence of operators.
e.g. short result= 100 + 4 * g /3;

► Logical Expression
The expression that results into true or false are called logical or Boolean
expressions.
e.g. if (x > y)
System.out.println( "xis greater than y");

STATEMENTS
Statements are roughly equivalent to sentences in natural languages. A statement forms a
complete unit of execution. The following types of expressions can be made into a statement
by terminating the expression with a semicolon(;).
► Assignment expressions
► Any use .of++ or --
► Method invocations
► Object creation expressions

Such statements are called expression statements. Here are some examples of expression
statements. ·
II assignment statement
price = 5045.99;
II increment statement
price++;
II method invocation statement
.System.out.println("Hello World!");
II object creati~n statement
Car myCar = new Car();
«z; er -
I Tot al com put er App llca tlon s - IX
, n add itio n to exp res sio n sta t~m ent
s the re are two oth er kin ds of sta tem
ent s: dec lara ti,
sta tem ent s and

~~
con tro l flow sta tem '
De cla mti on: A dec lara tion sta tem ent s. i

~
ent dec lare s a var iab le, We hav e see n
ma ny exa mp le,
ion sta tem ent s already:
dou ble ·
pric e= 5045,99; //declaration statement
Co ntr ol Flo w Sta tem ent s: The y reg
ula te the ord er in wh ich sta tem ent s
loo p and the if get exe cut ed. Th,
sta tem ent are bot h i,xa mp les of con tro
l flow sta tem ent . Yo u '11 lea rn abo\lt
con tro l flow sta tem ent s in the nex t cha
pte r.

BL
A OC KS
blo ck is a gro up of zer o or mo re sta tem
ent s bet we en bal anc ed bra ces and can
any wh ere , The following exa mp le, Blo be uso1
ckD em o, illu stra tes the use of blo cks
:

class BlockDemo{
public void main()
{
int a=1 0,b=20;
if(a>b)
{ II begin block 1

System.out.println("a is greater than b.")


;

} II end block one


else
{ II begin block 2

· Sy5tem .out.println("b is greater than a");


.

} II end block 2
}
}

,/,.w OP ER AT OR

!:'~
The 'new ' ope rator in Java.1s res po
d~ :ucal ly allocat es me m: ~·bl
eo e progra m. The adv ant a
:h! :~ t h e cre at ion of n ew obj ect o r
ins tan ce of'
. me ans tha t t h e me mo ry is allo cat
ma ny or as few obj ect s as it needs d ed at tll'
u g~
nngofth
thie sexe
app
c roa
t" ch is tha t a p rog ram can cre ate as
. . -- -~ ~- -- u ion o~ the pro gra m .
....
Ope rato rs in Jav a
n _m
::=-o_f _D_,,y'--a .:: M
_ i:.c_: .
:::.::e:!m~o!3___~ !: .
onea~ti:.::o::.:n U'!!ng 'ne w' 0 per at or
;:.. we dec lare a cla ss i J -
.
W}len n ava , a new dat a typ e is cre ated . A clas s provides the blu epr int
r objects. We can cre ate an ob • t f
H
fo ~ec .rom a cl ass . owever, obt aini ng obj ects of a clas s is
a two -ste p pro ces s :

1. Dec lar atio n ·


of th
. le . ble c1ass typ e. Th·ts van•abl e doe s not define an obj ect ..
Firs t, dec lare a var iab
Ins tead , it is sim ply av
ana e that can refe r to an object.
Syn tax :
m= e~- ~-- ---- -----:--::- - - - - - -- - )
(--- ~c± la;s ;s~ -~n ~am ~~e ~v: ar:: =_: n:a
~ '

Example:
s Box
II declare reference to an object of clas
Box demobox;

· · stra ted as follows


A var iab le in this sta te cur re n tIY refiere nce s no obJect can be illu
fi · .' ):
(the var iab le nam e , dem obox, p 1us a re ere nce pom tmg to null

dem obo x G
·2. Ins tan tiat ion and Ini tiaJ in.t ion
e.
y of the obj ect and ass ign it to tha t var iabl
Sec ond , acq uir e an act ual , phy sica l cop cla ss
rato r. The 'new ' ope rato r ins tan tiat es a
Thi s can be don e by usi ng the new ope and
ng at run time) mem ory for a new obj ect
by dyn am ica lly allo cat ing (i.e., allo cati iab le.
. Thi s refe ren ce is the n sto red in the var
retu rni ng a refe ren ce to tha t mem ory
be dyn ami call y -allo cate d.
Thu s, in Jav a, all cla ss obj ect s mu st
iali zes
new ope rato r is als o foll owe d by a call to a cla ss con stru cto r, wh ich init
The is
obj ect . A con stru cto r def ine s wh at occ urs wh en an obj ect of a cla ss
the new ific ant
nt par t of all clas ses and hav e ma ny sign
cre ated . Co nst ruc tor s are an imp orta era l
def aul t con stru cto r is use d. Bel ow is gen
attr ibu tes . In the exa mp le giv en bel ow
on wit h an exa mp le:
syn tax of ins tan tiat ion and init iali zati

( _______
var -na me = new cla ss-n ame (); ___; ;.:_. : . - - - -
- - - - -)

Example:
II instantiation via new operator and
class Box
II initialization via def ault constructor of
demobox = new Box();
cla ss
ore und ers tan din g, how 'new ' dyn am ica lly allo cate s mem ory , let us see
Bef
Box pro toty pe.
~ - - - - - - - - -~~~~~~~
~l~ute
Total Comp ic~ra~t
APP i~o~n~s~-~IX:__ _ __ _ _ _ _
- __---------
class Box
{
double width;
double height;
double depth;
}
.
d t P cur ren tly ref ers to a cla ss
A variable after se~on ~~~, dem obo obj ect , can be illustra~
as follows (the variable x, plu s a ref ere nce po int ing to Bo x obj ectJ

demobox width=0.0

height=O.0 Box object

depth=0.0

DOT(.)OPERATOR
The "dot" con nec ts cla sse s and obj
ects to me mb ers wh en a use r is
nam e to one of its sta tic fields. An exa con nec tin g a clas
mp le of thi s is the do t bet we en "Sy
~ the sta tem ent s a use r use s to ste m" and "ou,
pri nt ou tpu t to the con sol e win dow
.
Sys tem is the nam e of a cla ss inc lud
ed in every Jav a im ple me nta tio n.
reference variable tha t poi nts to a It ha s an objet
Pri ntS tre am obj ect for the con sol
pri ntl n( "text") invokes the println() e.~So , "System .au
me tho d of the Sy ste m.o ut obj ect .

Inv ok ing a Method


Now tha t we hav e an object tha t con
tai ns pri ntl nWi ndo w() , we can use
it. Th e syn tax to invoke a me tho d, the object to invok
given an obj ect , is: ·
1. the identifier of the variable con
tai nin g a ref ere nce to the obj ect , foll
2. the "dot" ope rat or, followed by owed by
3. the me tho d's identifier, followed
by
.I 4. arg um ent s exp ect ed by the me tho
d, and
5. fin ish ed off wit h a semicolon.

Example: obj.printlnWindow( "Hello Wo


rld!" );
class HelloWindow extends ExtendsSt
uff
{
public static void main (String □ args)
{
HelloWindow obj = new HelloWindow
( );
Opera tors in Java
obj.printlnWindow("Hello World!")
}
} //end class HelloWindow

outpu t: "Hello World !" will be printe d in a . d


pop up win ow.
!SPLA YING DATA

utp~t on the scree n is a~com plish_ ed by the built- in metho d or functi


on println (). This
n ction can be used to displa y stnng , which is passe d to it. It can
be used to displa y
other type of inform ation as well. Loo.k at the examp le below:

Syste m.out .print ln("T his is a samp le progra m");

he above statem ent displa ys "This is a sampl e progra m" on the screen
, followed by a
i ewline chara cter, i.e., the curso r move s to the next line.
he line begin s with Syste m.out . At this point, it would be just enoug h to
know that System
is a prede fined class that provi des acces s to the system and out is the outpu t stream
that
s conne cted to the conso le. Notice that println () statem ent ends with
a semic olon.
ok at the statem ent below :
Syste m.out .print ("Thi s is a sampl e progra m");

The print0 is also used to displa y outpu t on the screen , excep t that
it _d oes not displa y a
newlin e chara cter after each call, unlike the println (). Look at the statem
ents below.
Syste m.out.printl n("Th is is line one");
Syste m.out .print ("Thi s is on line two");
Syste m.out .print ln("T his is also on line two");
Syste m.out .print ln("H ello, world" );

Outpu t of the above snipp et will be:


This is line one
This is on line two This is also on line two
Hello World
·ntln(" This is line one"); prints the string that appea rs
A statem ent such as Syste m.out .pn ·
b hi . O f doubl e quote c h arac t e rs . All of these printi ng statem ents are
etwee n the mate ng parr
calls to the printl n() metho d of th e System.ou t O b~.ect. that is built into.
the Java langua ge.
Syste m.out .print ln("# " + price · + " Rs · ")·'
- · g used to .cons truct a single string param eter from three
The two '+' opera tors are b ein
compo nents:
. . . " " note the space chara cter after the hash).
• the stnng literal . # ( t
. h . e field (note there are no quo es aroun d the field name) .

J/11/Jlllll[~~~~~~~~~~~:~~~~:::~::~~~~~;~~~;J
• the value oft e pnc
~=~~~~~
••

You might also like