Operators in Java Class 9 Morning Star
Operators in Java Class 9 Morning Star
.
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 ).
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 '
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
-
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;
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
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
boolean y = false;
System.out.println("x && y : " + (x && y));
System.out.println("x II y: "+ (x II y));
System.out.println("!x : " + (!x));
}
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
_,._ 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
·- •-•
C <variable> = <expression>
------- st----___,;_--~ ~~
)
f the value already exi s in the variable it is overwritten by the assignment operator(=).
The shortcu t increme nt/ decrem ent operato rs are summa rised in the followin g table.
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\
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=
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
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
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
► 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
} 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 :
Example:
s Box
II declare reference to an object of clas
Box demobox;
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
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 .
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" );
J/11/Jlllll[~~~~~~~~~~~:~~~~:::~::~~~~~;~~~;J
• the value oft e pnc
~=~~~~~
••