0% found this document useful (0 votes)
8 views18 pages

DocScanner 30-Jan-2025 2-13 PM

The document provides an overview of various operators in Java, including arithmetic, relational, logical, assignment, increment/decrement, conditional, and bitwise operators. It explains how these operators are used to manipulate data and perform calculations, with examples illustrating their application in programming. Additionally, it discusses the precedence of operators and the evaluation of expressions in Java.

Uploaded by

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

DocScanner 30-Jan-2025 2-13 PM

The document provides an overview of various operators in Java, including arithmetic, relational, logical, assignment, increment/decrement, conditional, and bitwise operators. It explains how these operators are used to manipulate data and perform calculations, with examples illustrating their application in programming. Additionally, it discusses the precedence of operators and the evaluation of expressions in Java.

Uploaded by

mayankggn4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
Operator: Expressions gee rors. We have already used several of them, such ats =. yet certain machematicaLorlogiey igs. They usual rich set of oper symbol chat tells the computer to pe in programs t@ manipulate date and ical expr (fo a number of related categories as below: form a part of mathematical ¢ Java operators ean be el ators, S Relational operators Logical operate Assignment ope ors Increment and decrement operators: Conditional operators, > ditional operator: The apenateys shad ave weed yo penton oa ori areca Cabcusatm, 52 ARITHMETIC operators’** Cotten — Halremahed Sjoen ater 1 provides all the h hmetic operators. They are listed in Table 5.1. The operators + and 7 work the same way as they do in other kinguages. These ean operate on any builtin numeric data type of Java. We cannot use these operate: The unary minus operator, in eficet, 1 gle operand by =1, Therefore, number preceded by a minus sign changes its sign. : Bitwise operator 8. Speeial operators on boolean ¢ Itiplies its s Table 5.1 Arithmetic Operators Q Meaning, Addition or unary plu -* Multiplication “ Division ae Modulo division hown below: jnthmetic operators are used 4 Ab: ath mac a/b awd -a°b ere a and b- may be variables or constants and are known as operands. Integer Arithmetic ‘oth the operands in a single alled an integer expression, ani s yields an integer value. In the above examples, 4 we have the following results: arithmetic expression such as a+b are integers. the d the operation is called integer arithmetic. Integer When bi if'a and bare integers, then for expression is ea arithmetic alv a=l4andb A-b = 10 atb 18 acb 56 a/b = 3 (decimal part truncated) a%b 2. (remainder of integer division) a/b, when a and b are integer types, gives the result of division of a by b after truncating the divisor. This operation is called the integer division. For modulo division, the sign of the result is alw: dividend), That i -14% 3= =14%-% 14%-3 = ays the sign of the first operand (the (Note that module d Real Arithmetic An Arithmetic operation involving only real operands is called may assume values cither in decimal or exponential notation. Since flo: rot Beat aa see Z ed to the number of significant digits permissible, the final value is ¢ Correct result. real arithmetic. A real operand ating, point values are an approximation of. = 68 Programming wih Jeva: A Primer Unlike C and C++, modulus operator ean be applied to the floating point data as welt, Roating point modulus operator returns the floating point equivalent of an integer divy What this means is that the division is carried out with both floating point operands but resulting divisor is treated as an integer, resulting in a floating point remainder Programs shows how arithmetic operators work on floating point values Program $.1__Floating point arithmetic atPoint ic void main(String args[]) 6 a = 20.5F, b System.out.printin(™ System.out.printin(* System.out.printin(" System.out.printin(" System.out.printin(™ System.out.printin(™ System.out.println(" 4 The output of Program 5.1 is follows: a 20.5 b= 6.4 a+b 26.9 a-b = 14.1 a*b 3h 2 a/b 3.20313 atb 1.3 Mixed-mode Arithmetic When one of the operands is real and the other is integer, the expression is called a mixed-mn arithmetic expression. If either operand is of the real type, then the other operand is convert to real and the real arithmetic is performed. The result will be a real. Thus 15/10.0 produces the result 1.5 whereas 15/10 produces the result 1 More about mixed operations will be discussed later when we deal with the evaluation expressions. | i ae Tha OPMatey ted ane ue, 4 , ed te Grentoone B valurco ans Cotte ad Operators and Expressions 60 Motionat openaioy , ae RELATIONAL OPERATORS 4... of = Q oury “ y 5 reroter 1 adie on compare fvo quantities, and depending on their relation, take wertain decisions. For y compare the age of Wo persons, OF the price uf two ten ale. we 8 exam san be di hthe soon These Jasons ean be done with the help of relational operators, We So ean fess than’, An expression such nye nt We have alrandy ued the mymty 7 uh Try ¥ falye < bor 20 oataning a relational operator is termed as a relational expression, The value of relational Spyresion is either (rue or false, For example, y= 10, then x < 20 is true while false. shown in ional ope! all. These operators Table 5 Table 5.2 Relational Operators Operator \ < than than or equal wo fa gronter than is greater than or equs isequalto Ss not equal to of the following, ‘Asimple relational expression contains only one relational operator and i form: ae-l relational operator ai ae-1 and ae-2 are arithmetic expressions, which may be simple con! combination of them. Table 5.3 shows some examples of simple relational es values. or sions and their Table 5.3 Relational Expressions Expression Value 4.5 <= 10 TRUE ‘ 4.5 < -10 FALSE -35 >= 0 PALSE 10 < 7+5 TRUE atb == etd TRUE ues of c and d. Only if the sum of values of a and b is equal to the sum of vi 70 Programming with Java’ A Primer ons are used on either side of a relational opera, sults compared. That is, ariehy, When arithmetic expr expressions will be evaluated first and then the r ! have a higher priority over relational operators. Prog relational operators. Program 5.2 _ Implementation of relational operators class RelationalOperators public static void main(String args[]) float a = 15.0F, b = 20.75F, c = 15.0F; System.out.printin(* een System.out.printin(™ "+ bd); System.out.printin(™ pee) ie bis ” + (acb)); bis ” + (a>b)); cis cis bis !=c is atc is System.out.printin(* System.out.printin(™ System.out.print1n(* System.out.printin(™ System. out.printin(™ System.out.printin(* System.out.printin(™ va Too ea BOD The output of Program 5.2 would be: = 15 = 20.75 =15 b is false ¢ is true c is true b is false != c is true atc is false coo eae Hao oD ‘onal expressions are used in decision statements such course of action of a running program. Decision statements ae disc and 7 if and while to decide | sed in detail in Chapter re aperater et ane U 4 te perky enh : ” vu colled Loa, ve + Table 5.4 Logical Operators Operator oe wae ee oe ¥ me ae ia 2 6. — |! logical OR | 2 te Rais logical NOT The logical operators && and || are used when we want to form com smbining two or more relations. An example i eee a >b & 10 ‘An expression of this kind which combines two or more relational expressions is termed as a ical expression or a compound relational expression. Like the simple relational expressions. a eee earession also yields a value of true or false, according to the auth table shown in sble 5.5. The logical expression given above is true only if both a>b and 10 are true. If ther (or both) of them are false, the expression is false. Table 5.5 Truth Table Value of the expression op-1 op-2 op-1 && op-2— op || op-2 true true true true true false false crue false true . false true false false false false Note: © op-l && op-2 is true if both op-1 and op-2 are true and false otherwise. ¢ op-1 | | op-2 is false if both op-1 and op-2 are false and true others’ Some examples of the usage of logical expressions are: 1. if (age>55 && salary<1000) 2. af (number100) he oberoter that fs ured fe o Some Nolut toa Joni ote ox 72 Programn th Java’ A Primer Cotte d a Vy === 5.5 ASSIGNMENT OPERATORS © P®)\0.) eee: & RoW ne= tol Assignment operators are used to assign the value of an expression 10 a variable. \ the usual assignment operator, * =‘. In addition, Java has a set of ‘shorthand operators which are used in the form where v i: va able, exp is an expression and op is a Java binary operator. The oper: known as the shorthand assignment operator. - The ator y signment statement Vv op= exp; is equivalent to v op(exp); with v aeéessed only once, Consider an example x += ytl; This is same as the statement x = xt(ytl); The shorthand operator += means ‘add y+1 to 3 above statement becomes x 3: and when this statement is executed, 3 is added to x. if the old value of value of x is 8. Some of the commonly used shorthand as: Table 5.6. or ‘inerement x by y+1’. For y is. say 5, then th ignment operators are illustra Table 5.6 Shorthand Assignment Operators Statement with simple Statement with assignment operator shorthand operator a= atl a= 1 a a-l a 1 a a*(nt1) a ntl a a/(n+1) a n+l a a%b a b ‘The use of shorthand assignment operators has three advantages: 1. What appears on the left-hand side need not be repeated and therefore to write, it becom atement is more coneise and easier to read. 2. Thes more efficient code. 3. Use of shorthand operator result The opmrater wot ig uned bo tow SOSA. atam operomd byl 68 cabled Inerermunt opera (44) - The apenatery Yad is use 4 Peon nd Expressions 73 ee whet ot ann opernamd bu _ fe d OC tre 6 INOREMENT AND DECREMENT OPERATORS | Cotto on BOCA Rat « java has (v0 VOY useful operators not generally found in many other languages. These are th ave ment and decrentent operators: she operator ++ adds 1 to the operand while ~~ subtracts 1, Both are unary operators and are ef in the following form: 7 - or m-~F Oe . is equivalent to m= m+ 1; (or m += 1;) ay 7% is equivalent to m= m~- 1; (or m -= 1;) Ore 4 Veuse the inerement and deerement operators exte i) While + +m and m++ mean the same thing when th schave differently when they are used in expr qatement. Consider the following: ively in for and while loops. (See Chapter xy form statements independently, they ons on the right-hand side of an assignment m=5 y = ttm; n this case. the value of y and m would be 6. Suppose, if we rewrite the above statement as m= 53 y = mit; hen, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand ind then the result is assigned to the variable on left. On the other hand, a postfix operator first signs the value to the variable on left and then increments the operand. Program 5.3 llustrates this. Program 5.3. Increment operator illustrated ss IncrementOperator public static void main(String args[]) int m= 10, n = 203 System.out.printin(" -out.printin(* out.printin(" System.out.printin(™ System.out.printin(™ System.out.print1n(" 24 Programming wih Jove A Prmer follows: Output of Program § 2 7 is, the statemen, Similar is the case, when we use ++ (or~-) in subscripted variables. That is. the * alit+] = 10 is equivalent to i = ist Tre aprnoater Hor art aon 7 a 377 CONDITIONAL OPERATOR “7S SYD Cor POD aan vou . The character pair ?: is a ternary operator available in Java. This operator is used to constr conditional expressions of the form: expl ? exp2 : exp3 where exp], exp2, and exp3 are expressions. The operator ?: works as follows: exp! is evaluated first. If it is nonzero (true). then expression exp2 is evaluated and becomes the value of the conditional expression. If exp: false, exp3 is evaluated and its value becomes the value of the conditional expression. Note ¢ only one of the expressions (either exp2 or exp3) is evaluated. For example, consider following statements: a = 10; b= 15; x= (azb)? aot be In this example, x will be assigned the value of b. This can be achieved using the if... statement as follows: if(a > b) x= a else be 5.8 BITWISE OPERATORS Java has a distinction of supporting special operators known as bitwise operators manipulation of data at values of bit level. These operators are used for testing the bits AH, or double, Table Table 5.7 Bitwise Operators Operator M ng ES 7 Ee a bitwise AND ) a bitwise OR eae bitwise exclusive OR Cane one’s complement en shift left oe shift right 2 oe shift right with zero fill 59 2 SPECIAL OPERATORS xa supports some special operators of interest such as Jection operator (.). stanceof operator and member stanceof Operator he i eof is an object reference operator and returns true if the object on the left-hand de is an instance of the class given on the right-hand side. This operator allows us to determine hether the object belongs to a particular class or not. ae ‘Example: é person instanceof student true if the object person belongs to the class student ; otherwise it is false. Operator he dot operator (.) is uséd to access the instance variables and methods of class objects xamples: personl.age / / Reference to the variable age personl.salary( ) / / Reference to the method salary( ) It is also used to access classes and sub-packages from a package. ARITHMETIC EXPRESSIONS ors arranged as per mpl mples arithmetic expression is a combination of variables, constants, and ope syntax of the language. We have used a number of simple expressions in the exa dso -omplex mathematical expres me of the a can handle an il programming with Java: A Primer ‘i 76 Programming an OpEraty ot have 4 Java expressions are shown in Table 5.8. Remember that Java does noth of Java expressic exponentiation Table 5.8 Expressions Algebraic expression Java expression cnc a She a ren) (ty) (nenyinty) (mee) : 42x41 Bextxt2°x+1 2s 7 x/yte = 5. EVALUATION OF EXPRESSIONS oom Expressions are evaluated using an assignment statement of the form variable = expression variable is any valid Java variable name. When the statement is encountered, the expression cvaluated first and the result then replaces the previous value of the variable on the lef has side. All variables used in the expression must be assigned values before evaluation is attempte: Examples of evaluation statements are a*b-c; b/cta; 2 = a-b/ctd; The blank space around an operator is optional and is added only to improve readabilit When these statements are used in program, the variables a,b,c and d must be defined befor they are used in the expres oom eoH2e PRECEDENCE OF ARITHMETIC OPERATORS An arithmetic expression without any parentheses will be evaluated from left to right using the rules of pre ‘dence of operators. There are two distinet priority levels of arithmetic operatorsit High priorit Low priority ee The basic evaly During the first ps ation. proc ‘ure includes two left-to-right pi the high priority operators ( s through the expre y) are applied as they are encountered Qporators and Expressions 77 they are encountered any) are applicd ¢ cond pass, the low priority operators (if na the see following evaluation statement sri he insider 12, and ¢ = 3, the statement becomes hen a x = 9512/343*2-1 dis evaluated as follows: rst pass = 9-44+3*2-1 (12/3 evaluated) = 9-44+6-1 (3*2 evaluated) = 546-1 (9-4 evaluated) = 11-1 (5+6 evaluated) = 10 (11-1 evaluated) into an introducing parentheses However, the order of evaluation can be changed by pression. Consider the same expression with parentheses as shown below: 9-12/ (3+3) * (2-1) are used, the expressions within parentheses assume highest appear one after another as shown above, the ‘and the right-most in the last. Given Whenever the parenthe: ses Ii two or more sets of parenthes: ntained in the left-most set is eve iority. :pression ©O} nw are the new steps. st pass stepl: 9-12/6* (2-1) Step2: 9-12/6*1 econd pas Step3: 9-2*1 Step4: 9-2 hird pass: step5: 7 s of three left-to-right Pp However, the number of equal to the number of arichmetic operators) Ses, evaluation of the expression will proceed ‘Just make sure that every opening parentheses This time, the procedure cons Juation steps remain the same as 5 (.¢: Parentheses may be nested, and in such ¢ utward irom the innermost set of parentheses: sa matching closing one. For example 9-(12/(3+3)*2)-1 = 4 vhereas 9-((12/3) +3*2) = " 78 ng with Java: A Primer them to Imy ir just C0 nite the order of priority, we may also Use 1 always add an extra P? While parentheses allow us to che understandability of the program, When in doubt, we e; sure that the priority assumed is the one we require = ae 13 TYPE CONVERSIONS IN EXPRESSIONS Automatic Type Conversion rent types in an expression, but dy canhintion it adheres to very striet rules of type conversion. We know that the comp ata time, involving two operands. If the operands are of different ty illy converted to the 4Shigher’ type before the operation Proce Java permits mixing of considers one operate’ type is automati the ‘lower The result is of the higher type lebyte, short and int variabl flow. Ifa single long is used in the expression, the whole express II integer values are considered to be int unless they have the I ion contains a float operand, the entire expression is promo 5.9 provides a reference chart for p the result is always promoted to xpression, 1 ion is promote are used in an to avoid ove long. Remember th appended to them, Han expr to float. I any operand is double, result is double, Table conversion. Table 5.9 Automatic Type Conversion Chart char short int long float double. char int int int int long float double byte int int int int long float double short int ine int int long float double int int int int int long float double long Jong long long long long float double fl float fl float float float float double double double. — double. — double double. double double Double of the variable on the left of th are introduce The final result of an expression is converted to the type nt sign befor igning the value to it. However, the following changes ssignment. assignm during the final a 1. float to int causes truncation of the fractional part. uses rounding of digits. double to float Jong to int causes dropping of the exc higher order bits. ng a Value ready discussed how J castit ve al ve have A Ten we want C0 foree noes Consider, for e wa Performs type conversion autor 4 type conversion in ay mple, the ealoula ically, However, there are it is different from the automatic fon of ratio of females to males in a town ay t emale_number/male_number female_number and male_number are declared nce es . Si abe ae phe result of the division would be lost and ne sta problem can be solved by converting | us : won below integers in the program, the decimal tio would not represent a correct figure locally one of the variables to the floating point as ratio = (leat) female_number/male number et at) converts 2 e # .e operator (io a converts the female_number to floating point for the purpose of evaluation the expression. Then using the rule of automatic conversion, the division is performed in sting point mode, thus retaining’ the fractional part of result, Note that in no wa v dows the operator (float) affect the value of the variable female_number J also, the type of female_number remains as int in the other parts of the program. The process of such a local conversion is known as casting a value. The general form of ac: (type-name) expression ere type-name is one of the standard data types. The expression may be a constant, variable or expression. Some examples of casts and their actions are shown in Table 5.10. Table 5.10 Use of Casts Examples Action x = (int)7.5 7.5 is converted to integer * by truncation a = (int)21.3/(int)4.5 Evaluated as 21/4 and the result would be 5 b = (double) sum/n Division is done in floating point mode. y = (int) (a+b) The result of a + b is converted to integer. z = (int)atb a is converted to integer and then added to b. P = cost ( (double) x) Converts x to double before using it as parameter. Casting can be used to round-off a_given value _to_an_integer, Consider the following tement; = — (ytd. 8)2 x = (int) 28.1 and of Os nig, the result becomes 28, the value that 1 ayy si coast is not changed ' types of variables in an expression, never Assume good practice to explicitly force the CoNVEEsig, re double and m is int, the following two fate Hyis Ty + OS bs Of course, the expression beitt When combining awe different automatic conversion, It is alwys # safer, For example, when y and p are equivalent. = per = pt (double); However, the second statement is preferable. trates the use of casting in evaluating the equation Program 5.4 ic void main(String args[]) float sum; i++) sum = sum + 1/(float)a; System.out.print(" i= "4 a); System.out.printin(" sum =” + sum); } } } Program 5.3 produces the following output: i =1 sum=1 2 sum = 1.5 3) sum = 1.83333 4 sum = 2.08333 TS sum = 2.20333 : a sum = 2.45 sum = 2.59286 8 sum = 2.71786 = 9 sum = 2.82897 10 sum = 2.92897 titel ee 1 Operators and Expressions 81 OPERATOR PRECEDENCE AND ASSOCIATIVITY precedence is used to determine sociated with it. Thi 2 ated. There are distinct levels of Java has a precedence aan expression involving more than one operator is evalu how a eM ne an operator may’ belong to one of the levels. The operators at the higher level of reoedene® gre evaluated first. The operators of the same precedenee are evaluated either from Pato right or from right to left, depending on the level. This is known as the associativity le Merty of an operator. Table 5.11 provides a complete list of operators, their precedenc prope cir rules of association. The groups are listed in the order of decreasing precedence levels ame Fates the highest precedence level and 14 the lowest). The list also includes those (rank Lit : efators which we have not yet discussed. Table 5.11 Summary of Java Operators Operator Description Associativity Rank : Member selection Left to right 1 0 Function call u Array element reference : Unary minus Right to left 2 Increment Decrement ! Logical negation ~ Ones complement (type) Casting . Multiplication Left to right 3 / Division : Modulus + Addition Left to right 4 z Subtraction << Left shift Left to right 5 > Right shift >> Right shift with zero fill <, Less than Left to right 6 SS Less than or equal to 2] Greater than aa Greater than or equal to instanceof © Type comparison om Equality Left to right 7 : Inequality (Continued) Associativity Left to right Right to left Right to left Ir is very important to note carefully, the order of precedence and associativity Of operates Consider the following condi tement: if (x 10+15 && y<10) The precedence rules say that the addition operator has a higher priority operator (&&) and the relational operators (= executed first. This is equivalent to: than the logy ind <). Therefore, the addition of 10 and 15) if (x 25 && y<10) step is to determine ‘and 5 for y, then The ne: of 20 for whether x is equal to 25 and y less than 10. Ifwe assume vale x 25 is FALSE Y< 10 is TRUE Note that since the opera and then 25 Finally we get: tor < enjoys ahigher priority compared to s tested. Y < 10 is tested firs af(PALSE g& TRUE) FALSE, the Because one of the conditions compound condition is FALSE. oom 5.15 MATHEMATICAL FUNCTIONS ome Mathematical functions such as cos, s problems. Java supports these ba: package. Table 5.12 li be used as follows: ‘art, log, ete, ic math fune the math funetions d are frequently used in tions through Math ch Jefined in the Math cl, analysis of realli ass defined in the java-tat lass. These functior Math. function_name( ) ferators and Expressions 83 Table 5.12 Math Functions Funetions Action sini) Returns the sine of the angle x in radians c08(x) Returns the cosine of the angle x in radians tan(x) Returns the cosine of the angle x in radians asin(y) Returns the angle whose sine is acos(y) Returns the angle whose cosine is y atan(y) Returns the angle whose tangent atan2(xy) Returns the angle whose tangent is x/y pow(x.y) Returns x raised to y () exp(s) Returns ¢ raised to x (c*) log(x) Returns che natural logarithm of x sqrt(x) Returns the square root of ceil(x) Returns the smallest whole number greater than or equal to x, (Rounding up) floor(x) Returns the largest whole number less than or equal to x (Rounded down) rint(x) Returns the truncated value of s. abs(a) Returns the absolute value of max(a.b) Returns the maximum of a and b min(a.b) Returns the minimum of a and b floats and doubles. Note: x and y are double type parameters. « and b may be ints, lon 5.16 SUMMARY oom We have discussed all the basic data types and operators available in Java and also seen their use in expressions. Type conversions and order of precedence of operators during the evaluation of expressions have been highlighted, Program 5.5 winds up our discussions by demonst use of different types of expressi Finally, it is important to note that all Java types have fixed sizes. There is no ani Ml Java types are machine. independent. ity and

You might also like