Chapter 3: Operators, Expressions and Type Conversion

Size: px
Start display at page:

Download "Chapter 3: Operators, Expressions and Type Conversion"

Transcription

1 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To program with assignment statements and assignment expressions. To use compound assignment operators. To write decision-making statements by using comparison operators. To use short-circuit operators. To apply the precedence of operators in expressions. To use Java operators to write numeric expressions. To cast the value of one type to another type. To become familiar with Java documentation, programming style, and naming conventions.

2 102 Chapter 3 Operators, Expressions and Type Conversion 3.1 Introduction In Chapter 2 you learned how to declare and use identifiers of different data types. In this chapter you will learn how to manipulate different operations on these identifiers. Java provides various operators to operate on identifiers and literals. For example, arithmetic operators are used to perform arithmetic operations on identifiers and relational operators are used to compare the values of identifiers. You will learn also in this chapter how to convert a type of an identifier to another type by using casting operator. Furthermore, you will learn how to document and organize your Java code. 3.2 Operators Operators are symbols used to perform certain operations. Operators in Java work much like they do in mathematics, producing a value from one or more operands. An operand is any quantity on which an operation can be performed. For example, in the addition operation, x+y, the quantities (variables) x and y are called operands and the symbol + is called an arithmetic addition operator. Java has a great many operators. The operators fall into several categories: arithmetic, assignment, comparison, logical, bitwise, and miscellaneous. Within a category the operators can be classified into types: unary, binary, or ternary. The type indicates the number of operands required with the operator. For instance, a unary operator only requires a single operand, whereas a binary type operator requires two operands, and of course ternary type operators require three operands. Fig. 3.1 shows the categories and types of operators in Java. Operators Categories Types Arithmetic Operators Assignment Operators Unary Operators Comparison Operators Bitwise Operators Binary Operators Logical Operators Miscellaneous Operators Ternary Operators Fig. 3.1 Categories and types of operators in Java.

3 103 Chapter 3 Operators, Expressions and Type Conversion The operators have an order of precedence among themselves. This order of precedence dictates in what order the operators are evaluated when several operators are together in a statement or expression. Also, with each operator is an associativity factor that tells in what order the operands associated with the operator are to be evaluated. Operands of many operators are evaluated from left to right such as the operands in addition operator. This means that the associativity of addition operator works in this way: take the value of the operand on the left of addition operator and then add it to the value of the operand on the right of addition operator. However, operands of some operators are evaluated from right to left such as the operands in assignment operator. This means that the associativity of assignment operator works in this way: take the value on the right of assignment operator and assign it to the variable on the left of assignment operator. See Appendix C for precedence and associativity of Java operators. Unary operators are designed specifically to work with only one operand, performing such operations as incrementing and decrementing the value of an operand by one, negating an expression, or inverting a boolean value. For example, ++count increment the variable count by one, -result negates the expression result, and!done invert the Boolean value done. Binary operators are another kind of operator that are designed to work with two operands, performing such operations as Basic arithmetic operators in Java include addition (+), subtraction (-), multiplication (*), division (/) and the assignment operator (=), all of which constitute the, and, with the exception of the assignment operator, are evaluated from left to right. The assignment operator is evaluated from right to left; it is a way of saying take this value on the right and assigns it to the variable on the left. The ternary operator should be used in a modest fashion and only necessary when setting a variable to one of two values; otherwise the standard if-else statement should be the preferred choice as it produces more readable code Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. In Java, arithmetic operators include both basic arithmetic operators and increment/decrement operators. Basic arithmetic operators evaluate from left to right whereas increment/decrement operators evaluate from right to left. When several arithmetic operators, in fact operators of any type, appear within an expression several passes of the expression may be necessary to completely evaluate the expression Basic Arithmetic Operators Basic arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/) and the modulus operator (%) which produces the remainder from an integer division. Basic arithmetic operators are binary type operators that require two operands to be performed. Table 3.1 lists the basic arithmetic operators along with their description and examples assuming integer variable A holds 7 and variable B holds 19.

4 104 Chapter 3 Operators, Expressions and Type Conversion TABLE 3.1: Basic Arithmetic Operators. Operator Name Description Example + Addition Adds values on either side of the operator. A + B will give 26 - Subtraction Subtracts right hand operand from left hand operand. A - B will give -12 * Multiplication Multiplies values on either side of the operator. A * B will give 133 / Division Divides left hand operand by right hand operand. B / A will give 2 % Modulus Divides left hand operand by right hand operand and returns remainder. B % A will give 5 Listing 3.1 demonstrates a simple example program of basic arithmetic operators. 1 // BasicArithmeticOperators.java 2 // This program demonstrates basic arithmetic operators 3 4 public class BasicArithmeticOperators 5 { 6 // main method begins execution of Java application 7 public static void main (String[] args) 8 { 9 int a = 10; 10 int b = 20; 11 int c = 25; System.out.println ("a + b = " + (a + b) ); 14 System.out.println ("a - b = " + (a - b) ); 15 System.out.println ("a * b = " + (a * b) ); 16 System.out.println ("b / a = " + (b / a) ); 17 System.out.println ("b % a = " + (b % a) ); 18 System.out.println ("c % a = " + (c % a) ); 19 } // end method main 20 } // end class BasicArithmeticOperators.java output a + b = 30 a - b = -10 a * b = 200 b / a = 2 b % a = 0 c % a = Increment and Decrement Operators Listing 3.1 A simple example program illustrates basic arithmetic operators.

5 105 Chapter 3 Operators, Expressions and Type Conversion The decrement and increment operators are unary type operators that require only one operand. The increment operator (++) increments a value by 1, while the decrement operator (--) decrements a value by 1. The increment and decrement operators can be applied before (prefix) or after (postfix) the operand. For example, ++x is prefix increment (++ is applied before x) and x++ is postfix increment (++ is applied after x) whereas x is prefix decrement (-- is applied before x) and x-- is postfix decrement (-- is applied after x). When applied before (i.e., ++x or --x) the operation is performed first and then the value is produced, when applied after (i.e., x++ or x--) the value is first produced before the operation is performed. In more specific, the code x++; and ++x; will both end in x being incremented by one. The only difference is that the prefix version (++x) evaluates to the incremented value, whereas the postfix version (x++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. Table 3.2 lists the increment and decrement operators along with their description and examples assuming integer variable A holds 7 and integer variable B holds 19. TABLE 3.2: Increment and Decrement Operators. Operator Name Description Example ++ Increment Increases the value of operand by 1 B++ will give Decrement Decreases the value of operand by 1 B-- will give 18 Listing 3.2 demonstrates a simple example program that illustrates the prefix/postfix unary increment and decrement operators. In line 14 of Listing 3.2, a++ displays the original value of a (i.e. 10) and then the value of a is incremented by 1 (a becomes 11 after display). In line 15, ++a increments the value of a by 1 (a becomes 12) and then display it. In line 16, --b decrements the value of b by 1 (b becomes 19) and then display it. In line 17, b-- displays the original value of b (i.e. 19) and then the value of b is decremented by 1 (b becomes 18 after display). In line 18, k = ++c increments the value of c by 1 to become 26 and then this value (i.e. 26) is assigned to k. In line 19, k = c++ assigns the original value of c (i.e. 26) to k and then increments the value of c by 1 to become 27 (c becomes 27 after assignment).

6 106 Chapter 3 Operators, Expressions and Type Conversion 1 // IncrementDecrementOperators.java 2 // This program illustrates increment and decrement operators 3 4 public class IncrementDecrementOperators 5 { 6 // main method begins execution of Java application 7 public static void main (String[] args) 8 { 9 int a = 10; 10 int b = 20; 11 int c = 25; 12 int k; System.out.println ("a++ = " + (a++) ); 15 System.out.println ("++a = " + (++a) ); 16 System.out.println ("--b = " + (--b) ); 17 System.out.println ("b-- = " + (b--) ); 18 System.out.println ("k = ++c --> k = " + (k = ++c) ); 19 System.out.println ("k = c++ --> k = " + (k = c++) ); 20 } // end method main 21 } // end class IncrementDecrementOperators.java output a++ = 10 ++a = 12 --b = 19 b-- = 19 k = ++c --> k = 26 k = c++ --> k = 26 Listing 3.2 A simple example program illustrates increment and decrement operators Assignment Operators Assignment operators include simple assignment operator and compound assignment operators. All assignment operators take the value on the right and assign it to the variable on the left. It is as copying the value of the right operand to the variable of the left operand. So, they are binary type operators evaluate from right to left. The key point here is that the left operand must be variable whereas the right operand can be variable or literal or an expression Simple Assignment Operator The simple assignment operator (=) is a way of copying a value on the right-hand side (rvalue), to a variable on the left-hand side (lvalue). The rvalue can be any constant, variable, or any expression that produces a value, while the lvalue must be a distinctly named variable that possesses the capacity to hold to a value. For instance, we may assign a value, 20 to a variable x in the following way:

7 107 Chapter 3 Operators, Expressions and Type Conversion x = 20; or an expression to a variable: x = 5 + 2; However we cannot assign a variable to a constant; this is to say a constant cannot be an lvalue, for instance, the following expression would produce a compiler error: 20 = x; //!Error When you assign primitives, you actually copy a value from one place to another. This is because primitives hold actual values as opposed to objects that hold references. See Subsection for the assignment of objects Compound Assignment Operators Compound assignment operators fall into three categories: arithmetic assignment operators (+=, -=, *=, /=, %=), bitwise assignment operators (&=, =, ^=), and bitshift assignment operators (<<=, >>=, >>>=). They are used when you want to modify the current value of a variable and reassign the modified value back to the same variable. It is as saying change whatever is the current value of x to a new value and assigns this new value back to x. All compound assignment operators are binary type operators evaluate from right to left. They are sometimes called shorthand operators because they provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. However, this subsection presents only arithmetic compound assignment operators. Bitwise and bitshift operators are discussed in Subsection The arithmetic compound assignment operators include addition assignment operator (+=), subtraction assignment operator (-=), multiplication assignment operator (*=), division assignment operator (/=) and modulus assignment operator (%=). Arithmetic compound assignment operators combine each of the arithmetic operators (+, -, *, /, %) with the assignment operator (=) together in one shorter syntax. So, we can combine addition and assignment operators together into +=, subtraction and assignment operators together into -=, multiplication and assignment operators together into *= and so on. For example, we can combine the addition (+) operator and assignment (=) operator in the expression x=x+1 and express it as the shorter syntax x+=1. Because of these short notations, they are sometimes called shorthand operators. Recall that the key point here is that you use arithmetic assignment operators when you need to reassign the modified value back to the same variable not to different variable. For example, x +=y (which is equivalent to x=x+y) finds the number stored in the variable x, add value of y to it, and then store the result of the addition in the variable x. Note Using compound assignment operators increase the efficiency of program execution because the compiler will look up just once for the location of the variable used in the expression.

8 108 Chapter 3 Operators, Expressions and Type Conversion Table 3.3 lists the arithmetic assignment operators along with their description and examples assuming integer variable A holds 7 and integer variable B holds 19. TABLE 3.3: Arithmetic Assignment Operators. Operator Name Description Example += -= *= /+ %= Add AND assignment Subtract AND assignment Multiply AND assignment Divide AND assignment Modulus AND assignment Adds right operand to the left operand and assign the result to left operand. Subtracts right operand from the left operand and assign the result to left operand. Multiplies right operand with the left operand and assign the result to left operand. Divides left operand with the right operand and assign the result to left operand. Takes modulus using two operands and assign the result to left operand. A += B is equivalent to A = A + B A = 26 A -= B is equivalent to A = A B A = -12 A *= B is equivalent to A = A * B A = 133 A /= B is equivalent to A = A / B A = 0 A %= B is equivalent to A = A % B A = 7 Listing 3.3 demonstrates a simple example program illustrates arithmetic assignment operators. In Listing 3.3, the line 13 c = will give c=30. Line 15, c += a, evaluates c += 10 which means c = and this will give c=40. Line 17, c -= a, evaluates c -= 10 which means c = and this will give c=30. Line 19, c *= a, evaluates c *= 10 which means c = 30*10 and this will give c=300. In line 23, c /= a, evaluates c /= 10 which means c = 15/10 and this will give c=1. In line 27, c %= a, evaluates c %= 10 which means c = 15%10 and this will give c=5.

9 109 Chapter 3 Operators, Expressions and Type Conversion 1 // ArithmeticAssignmentOperators.java 2 // This program illustrates arithmetic assignment operators 3 4 public class ArithmeticAssignmentOperators 5 { 6 // main method begins execution of Java application 7 public static void main (String[] args) 8 { 9 int a = 10; 10 int b = 20; 11 int c = 0; c = a + b; 14 System.out.println ("c = a + b --> c = " + c ); 15 c += a; 16 System.out.println ("c +=a --> c = " + c ); 17 c -= a; 18 System.out.println ("c -= a --> c = " + c ); 19 c *= a; 20 System.out.println ("c *= a --> c = " + c ); 21 a = 10; 22 c = 15; 23 c /= a; 24 System.out.println ("c /= a --> c = " + c ); 25 a = 10; 26 c = 15; 27 c %= a; 28 System.out.println ("c %= a --> c = " + c ); 29 } // end method main 30 } // end class ArithmeticAssignmentOperators.java output c = a + b --> c = 30 c +=a --> c = 40 c -= a --> c = 30 c *= a --> c = 300 c /= a --> c = 1 c %= a --> c = 5 Listing 3.3 A simple example program illustrates arithmetic assignment operators Comparison Operators: Equality and Relational Operators Comparison operators include equality operators and relational operators. Comparison operators determine if one operand is greater than, less than, equal to, or not equal to another operand. That is, they are used to compare the values of two operands and produce a Boolean value (i.e. true or false). Boolean values are also called truth values. Comparison operators are evaluated from left to right and they are binary type operators because require two operands.

10 110 Chapter 3 Operators, Expressions and Type Conversion Equality operators include equivalence operator (==) and nonequivalence operator (!=). Equality operators work with all primitive data types and so used to test the equality or not equality of the values of two integers, two characters, or two Booleans and produce a Boolean result (i.e. true or false). Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. Relational operators include greater operator (>), greater than or equal to operator (>=), less than operator (<), and less than or equal to operator (<=). Relational operators evaluate the relationship between the values of two operands and produce a Boolean result (i.e. true or false). Relational operators work with all primitive data types except Boolean type. This means that, you can test the relationship between the values of two integers, two characters, but not two Booleans. Table 3.4 lists the comparison operators along with their description and examples assuming integer variable A holds 7 and integer variable B holds 19. TABLE 3.4: Comparison Operators. Operator Name Description Example == Equal to Checks if the values of two operands are equal or not, if values are equal then condition becomes true. (A == B) is not true!= Not equal to > Greater than Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A!= B) is true (A > B) is not true >= Greater than or equal to Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true < Less than Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true <= Less than or equal to Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Listing 3.4 demonstrates a simple example program that illustrates the comparison operators.

11 111 Chapter 3 Operators, Expressions and Type Conversion 1 // ComparisonOperators.java 2 // This program illustrates comparison operators 3 4 public class ComparisonOperators 5 { 6 // main method begins execution of Java application 7 public static void main (String[] args) 8 { 9 int a = 10; 10 int b = 20; System.out.println ("(a == b) is " + (a == b) ); 13 System.out.println ("(a!= b) is " + (a!= b) ); 14 System.out.println ("(a > b) is " + (a > b) ); 15 System.out.println ("(a < b) is " + (a < b) ); 16 System.out.println ("(b >= a) is " + (b >= a) ); 17 System.out.println ("(b <= a) is " + (b <= a) ); 18 } // end method main 19 } // end class ComparisonOperators.java output (a == b) is false (a!= b) is true (a > b) is false (a < b) is true (b >= a) is true (b <= a) is false Listing 3.4 A simple example program illustrates comparison operators Logical Operators Logical operators (sometimes called Boolean operators ) are performed on one or two expressions and return a Boolean result. They include NOT operator (!), AND operator (&), OR operator ( ), XOR operator (^), conditional-and operator (&&), and conditional-or operator ( ). All logical operators are evaluated from left to right. The logical NOT operator (!) is a unary type operator because it is performed only on one expression. The logical NOT operator (!) reverses the Boolean value of any expression. This means that, it inverts true to false and inverts false to true. For example, the relational expression (3>5) is evaluated to true and!(3>5) inverts it to false (i.e.!(5>3) =!(true) = false). The other logical operators (&,, ^, &&, ) are binary type operators require two expressions. The AND operator (&) performs on two expressions and returns true if both expressions are true otherwise returns false. For example, the logical expression (1!=2) & (2<0) returns false. The AND operator (&) must evaluate the Boolean value of both left and right expressions and then performs the operation. The conditional- AND operator (&&) is similar to the AND operator (&). It performs on two expressions and returns true if both expressions are true otherwise returns false. However, the

12 112 Chapter 3 Operators, Expressions and Type Conversion conditional-and operator (&&) differs from AND operator (&) in that it may not need to evaluate the right expression. The left expression determines whether to evaluate the right expression or not. For example, the logical expression (1!=2) && (2<0) stops immediately if 1!=2 is false (i.e., the entire expression is false) and continues if 1!=2 is true (i.e., the entire expression could still be true if the condition 2<0 is true). The OR operator ( ) performs on two expressions and returns false if both expressions are false otherwise returns true. For example, the logical expression (1!=2) (2<0) returns true. The OR operator ( ) must evaluate the Boolean value of both left and right expressions and then performs the operation. The conditional-or operator ( ) is similar to the OR operator ( ). It performs on two expressions and returns false if both expressions are false otherwise returns true. However, the conditional-or operator ( ) differs from OR operator ( ) in that it may not need to evaluate the right expression. The left expression determines whether to evaluate the right expression or not. For example, the logical expression (1!=2) (2<0) stops immediately if 1!=2 is true (i.e., the entire expression is true) and continues if 1!=2 is false (i.e., the entire expression could still be true if the condition 2<0 is true). The && and operators perform Conditional-AND and Conditional-OR operations on two Boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second expression is evaluated only if needed. This feature of conditional AND and conditional OR expressions is called short-circuit evaluation. Note Using conditional AND and conditional OR operators increases the efficiency of program execution because they make use of short-circuit evaluation feature. Table 3.5 lists the logical operators along with their description and examples assuming Boolean variable A holds true and Boolean variable B holds false. TABLE 3.5: Logical Operators. Operator Name Description Example! NOT Reverse the logical value of its operand. Returns true if the operand to the right is false. Returns false if the operand to the right is true.!(a && B) is true & AND Returns true if both of the operands evaluate to true. Both operands are evaluated before the AND operator is applied. (A & B) is false OR Returns true if at least one of the operands evaluates to true. Both operands are evaluated before the OR operator is applied. (A B) is true && Conditional AND Same as &, but if the operand on the left returns false, it returns false without evaluating the operand on the right. (A && B) is false Conditional OR Same as, but if the operand on the left returns true, it returns true without evaluating the operand on the right. (A B) is true

13 113 Chapter 3 Operators, Expressions and Type Conversion Listing 3.5 shows a simple example program that illustrates the logical operators. 1 // LogicalOperators.java 2 // This program illustrates logical operators 3 4 public class LogicalOperators 5 { 6 // main method begins execution of Java application 7 public static void main (String[] args) 8 { 9 boolean a = true; 10 boolean b = false; System.out.println ("(a & b) is " + (a & b) ); 13 System.out.println ("(a b) is " + (a b) ); 14 System.out.println ("(a && b) is " + (a && b) ); 15 System.out.println ("(a b) is " + (a b) ); 16 System.out.println ("!(a && b) is " +!(a && b) ); 17 } // end method main 18 } // end class LogicalOperators.java output (a & b) is false (a b) is true (a && b) is false (a b) is true!(a && b) is true Listing 3.5 A simple example program illustrates logical operators Bitwise and Bit Shift Operators Bitwise (~, &,, ^) and bit shift (<<, >>, >>>) operators are used to manipulate the contents of variables at a bit level according to binary format. These operators perform bitwise and bit shift operations on integral type variables. All bitwise and bit shift operators are binary type operators evaluated from left to right except the bitwise complement operator (~) which is a unary type operator evaluated from right to left. Bitwise operators are used to manipulate values for comparisons and calculations. For example, checking if a number is power of two or swapping two numbers without temporary variable can be easily solved using bitwise operators. Table 3.6 summarizes the bitwise and bit shift operators along with their description and examples assuming byte variable A holds 7 and byte variable B holds 19.

14 114 Chapter 3 Operators, Expressions and Type Conversion TABLE 3.6: Bitwise and Bit Shift Operators. Operator Name Description Example ~ Unary bitwise complement Inverts a bit pattern; making every 0 a 1 and every 1 a 0. (~A) -8 & Bitwise AND The result is 1, if corresponding bits are 1 in both operands. Otherwise, the result is 0. (A & B) 3 Bitwise inclusive OR The result is 0, if corresponding bits are 0 in both operands. Otherwise, the result is 1. (A B) 23 ^ Bitwise exclusive OR The result is 1, if corresponding bits are different in both operands. Otherwise, the result is 0. (A ^ B) 20 << Signed left shift Shifts a bit (or bits) to the left by the distance specified in the right operand and fill right bits with 0,s. (A << 3) 56 >> Signed right sift Shifts a bit (or bits) to the right by the distance specified in the right operand and fills the left most bit by the sign bit. (B >> 2) 4 >>> Unsigned right shift Shifts a bit (or bits) to the right by the distance specified in the right operand and fill left bits with 0,s. (B >>> 2) 4 The unary bitwise complement operator (~) takes a single bit and inverts the level of that bit pattern. Table 3.7 shows the truth table of ~ operator where the value of a bit which is 0 becomes 1 and vice versa. For example the value 7 to a variable "x" is represented in binary as But after applying ~ operator, the operation will be performed on each bit pattern which will return 1000 to the variable and the value -8 in the decimal format. TABLE 3.7: Truth Table of Unary Bitwise Complement Operator (~). Operand A ~A The bitwise AND operator (&) performs the bitwise AND operation on each parallel pair of bits of two operands. In each pair, the result is 1, if corresponding bits are 1 in both operands, otherwise the result is 0. Table 3.8 shows the truth table of & operator.

15 115 Chapter 3 Operators, Expressions and Type Conversion TABLE 3.8: Truth Table of Bitwise AND Operator (&). Operand A Operand B A&B The bitwise inclusive OR operator ( ) performs the bitwise inclusive OR operation on each parallel pair of bits of two operands. In each pair, the result is 1, if either first or second bit is 1 (or both are 1), otherwise the result is 0. Table 3.9 shows the truth table of operator. TABLE 3.9: Truth Table of Bitwise Inclusive OR Operator ( ). Operand A Operand B A B The bitwise exclusive OR operator (^) performs the bitwise exclusive OR operation (XOR) on each parallel pair of bits of two operands. In each pair, the result is 1, if the two corresponding bits are different, and 0 if they are the same. Table 3.10 shows the truth table of ^ operator. TABLE 3.10: Truth Table of Bitwise Exclusive OR Operator (^). Operand A Operand B A^B Registers in the computer processor include a fixed number of available bits for storing numerals. So it is possible to "shift out" some bits of the register at one end, and "shift in" from the other end. The number of bits is shifted within the range mode of 32.

16 116 Chapter 3 Operators, Expressions and Type Conversion The bit shifts operators are used to perform bitwise operations on the binary representation of an integer instead of its numerical value. In this operation, the bit shifts operators don't operate the pairs of corresponding bits rather the digits are moved or shifted in a computer register either to the left or right according to the distance specified by a number. Java has two signed bit shift operators: left and right and only one unsigned bit shift operator which is right. A sign bit is found in the left most position of the number and is known as most significant bit (MSB) which indicates the status of a number i.e. the number is positive or negative. If the value of the sign bit is 0, then the number is positive and if the value of the sign bit is 1, then the number is negative. On the other hand, the right most position of the number is known as least significant bit (LSB). Fig. 3.2 depicts MSB and LSB of a binary number. Fig. 3.2 MSB and LSB of a binary number. The signed left shift operator (<<) shifts a bit (or bits) to the left by the distance specified in the right operand. In this case, the leftmost digit is shifted at the end of the register, and a new 0 is shifted into the rightmost position. No matter, the number is positive or negative; in both cases the leading bit position is always filled with 0. Fig. 3.3 Left shifting operation. Fig. 3.3 shows that, all bits were shifted to the left by the distance of 1; and 0 were shifted to the right most position. Thus the result is returned as Another expression 2<<2; shifts all bits of the number 2 to the left placing 0 to the right for each blank place. Thus the value 0010 becomes 1000 or 8 in decimal.

17 117 Chapter 3 Operators, Expressions and Type Conversion The signed right shift operator (>>) shifts a bit (or bits) to the right by the distance specified in the right operand and fills the left most bit by the sign bit. In this case the rightmost bit (or bits) is shifted out, and a new 0 is filled with the sign bit into the highorder bits to the left position if the left operand is positive; otherwise 1, if the left operand is negative. This technique is known as sign extension. Fig. 3.4 Signed right shifting operation. Fig. 3.4 shows that, all bits were shifted to the right by the distance of 1. Since the sign bit of this number indicates it as a positive number so the 0 is shifted to the left most position. Thus the result is returned as or 3 in decimal. Another expression 2>>2; shifts all bits of the number 2 to the right placing 0 to the left for each blank place. Thus the value 0010 becomes 0000 or 0 in decimal. When signed left or signed right shifting operation is performed, then the sign bit is ignored, i.e. all the bits except the sign bit can be moved but the sign bit stays the same. Thus a signed left or signed right shift (<< and >>) operator never causes a number to change its sign. A positive number will always stay positive and a negative number will always stay negative. But the result for a negative number is different. For example, if we take a negative number as -50 then this value is represented in binary as , then the expression -50>>2; will return the result as or - 13 in decimal. The unsigned right shift operator (>>>) behaves like the signed right shift operator. I.e., it shifts a bit (or bits) to the right. But unlike >> operator, this operator always shifts 0s into the leftmost position by the distance specified in the right operand. So the result of applying the >>> operator is always positive. For example, the expression 14>>>2; shifts all bits of the number 14 to the right placing 0 to the left for each blank place. Thus the value 1110 becomes 0011 or 3 in decimal. An unsigned shift operation of a negative number generally returns the result in a positive number, because any unsigned right shift operation replaces the leading sign bit with 0 which indicates a positive number. Listing 3.6 shows a simple example program that illustrates the bitwise and bit shift operators.

18 118 Chapter 3 Operators, Expressions and Type Conversion 1 // BitwiseBitShiftOperators.java illustrates bitwise & bit shift operators 2 3 public class BitwiseBitShiftOperators 4 { 5 public static void main (String[] args) 6 { 7 byte a=7; // byte b=19; // System.out.println("~a : " + ~a); 11 System.out.println("a & b : " + (a & b)); 12 System.out.println("a b : " + (a b)); 13 System.out.println("a ^ b : " + (a ^ b)); 14 System.out.println("a << 3 : " + (a << 3)); 15 System.out.println("b >> 2 : " + (b >> 2)); 16 System.out.println("b >>> 2 : " + (b >>> 2)); 17 } // end method main 18 } // end class BitwiseBitShiftOperators output ~a : -8 a & b : 3 a b : 23 a ^ b : 20 a << 3 : 56 b >> 2 : 4 b >>> 2 : 4 Listing 3.6 A simple example program illustrates bitwise and bit shift operators Miscellaneous Operators There are few other operators supported by Java language including ternary operator, member access, comma, array index, new, instanceof, and typecast operators. Ternary operator or conditional operator (? :) can be used as an alternative of if else statement. Member access operator or dot operator (.) is used to access data members and member methods of a class by its objects. Comma operator (,) is used to separate method arguments, and to declare more than one variable of same type in one statement. Array index operator ([]) is used to declare and access array elements. new operator is used to create a new object. instanceof operator compares an object to a specific type. Typecast operator (()) is used to convert a variable from one data type to another data type. However, we will discuss these operators throughout this book Precedence of Operators Java operators have two properties those are precedence, and associativity. Precedence is the priority order of an operator, if there are two or more operators in an expression

19 119 Chapter 3 Operators, Expressions and Type Conversion then the operators will be evaluated from the highest priority to the lowest priority. For example, in expression * 5, multiplication operator (*) will be processed first and then addition because multiplication has higher priority or precedence than addition. From above example you would have understood the role of precedence or priority in execution of operators. But, the situation may not be as straightforward every time as it is shown in above example. What if all operators in an expression have same priority? In that case the second property associated with an operator comes into play, which is associativity. Associativity tells the direction of execution of operators that can be either left to right or right to left. Example 3-1 Consider the following Java expressions: 5 + x y a = b = c = 8 The first expression, 5 + x y, includes two addition and one subtraction operators. The addition and subtraction operators have the same priority and since their associativity is from left to right, they are evaluated from left to right. That is, 5 is added to x then 3 is subtracted and then y is added. In the second expression a = b = c = 8, the assignment operator is executed from right to left that means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You can parenthesize this expression as (a = (b = (c = 8))). Note that, you can change the priority of a Java operator by enclosing the lower order priority operator in parentheses but not the associativity. For example, in expression (1+2) * 3, addition will be done first because parentheses has higher priority than multiplication operator. All Java operators from highest to lowest precedence along with their associativity are listed in a table included in Appendix C Problem: Is a Number Divisible by 2 or 3 We now introduce a Java program that reads an integer number and examines whether it is divisible by 2 or 3. In order to solve this problem, we need to know when a number is divisible by another number. In mathematics, a number is divisible by another number if the remainder of the division operation is zero. For example, 10 is divisible by 2 because the remainder of dividing 10 by 2 is 0. But 10 is not divisible by 3 because the remainder of dividing 10 by 3 is 1. For addressing this problem in Java, we need to use both the modulus operator (%) and the equivalence (or equal) operator (==). The modulus operator (%) divides the first number by the second number and returns the remainder. The equivalence operator (==) then comes to examine whether the remainder equals to 0 or not. If the remainder is equal to 0 then the first number is divisible by the second number, otherwise it is not. Furthermore, we need to use the logical OR operator ( ) because the problem asks to test the divisibility of a number on 2 or 3. The program and its output are shown in Listing 3.7.

20 120 Chapter 3 Operators, Expressions and Type Conversion 1 // This program checks whether a number is divisible by 2 or public class DivisibleBy2or3 4 { 5 public static void main (String[] args) 6 { 7 int number; 8 boolean ans; 9 Scanner input = new Scanner(System.in); System.out.print("Enter an integer number: "); 12 number = input.nextint(); ans = (number%2==0) (number%3==0); System.out.println("Is " + number + " divisible by 2 or 3? " + ans); 17 } // end method main 18 } // end class DivisibleBy2or3 output Enter an integer number: 53 Is 53 divisible by 2 or 3? false Listing 3.7 A program to check whether a number is divisible by 2 or 3. Line 7 declares an integer variable number and line 8 declares a Boolean variable ans. Line 12 reads an integer value and assigns it to the variable number. In line 14, the expression (number%2==0) (number%3==0) consists of two smaller expressions. The first smaller expression (number%2==0) evaluates whether the number modulus 2 is equal to 0 (i.e. whether number is divisible by 2). The second smaller expression (number%3==0) evaluates whether the number modulus 3 is equal to 0 (i.e. whether number is divisible by 3). The first and second smaller expressions are then ORed and the result (i.e. true or false) is assigned to variable ans. Line 18 displays the result. 3.3 Expressions Now that you understand variables and operators, it's time to learn about expressions. An expression is a syntactic construction that has a value. Expressions are formed by combining variables, constants, and method returned values using operators. Operators may or may not be used in building expressions. For example, x+y is an expression formed by combination of two variables (x and y) and an addition operator (+), and x (or y) alone without using any operator is also an expression. However, Java has two kinds of expressions; arithmetic and logical expressions which are presented next.

21 121 Chapter 3 Operators, Expressions and Type Conversion Arithmetic Expressions Arithmetic expressions are formed by combing numbers using basic arithmetic operators (+, -, *, /, %) and/or increment and decrement operators (++, --). An arithmetic expression always yields a numeric value. If all operands (that is, numbers) in an arithmetic expression are integers, the expression is called an integral expression and if all operands in an expression are floating-point numbers, the expression is called a floating-point or decimal expression. An integral expression yields an integral result; a floating-point expression yields a floating-point result. Looking at some examples will help clarify these definitions. EXAMPLE 3-2 Consider the following Java integral expressions: * x - y / 6 x + 4 * (y++ - z) + 19 In these expressions, x, y, and z represent variables of the integral type; that is, they can hold integer values. EXAMPLE 3-3 Consider the following Java floating-point expressions: 13.8 * a * 12.5 (b ) Here, x and y represent variables of the floating-point type; that is, they can hold floating-point values. Arithmetic expressions are evaluated according to the precedence and associativity rules given in Appendix C. The increment and decrement operators are evaluated before the multiplication, division, modulus, addition, and subtraction operators. And multiplication, division, and modulus operators are evaluated before the addition and subtraction operators. When arithmetic operators have the same precedence, the expression is evaluated from left to right except for increment and decrement operators, the expression is evaluated from right to left. To avoid confusion, you can always use parentheses to group operands and operators. EXAMPLE 3-4 Evaluate the following arithmetic expression: x + 4 * (y++ - z) + 19 Where x=35, y=14, and z=5

22 122 Chapter 3 Operators, Expressions and Type Conversion Now: x + 4 * (y++ - z) + 19 = x + 4 * (14 - z) + 19 = x + 4 * (9) + 19 = x = = 90 Listing 3.8 shows a Java program that evaluates and outputs the arithmetic expressions given in Examples 3-2 and // This program evaluates and outputs arithmetic expressions. 2 3 public class ArithmeticExpressions 4 { 5 public static void main (String[] args) 6 { 7 int x=35, y=14, z=5; 8 double a=1.0, b=2.0; 9 10 System.out.println ("2 + 3 * 7 = " + (2 + 3 * 7)); 11 System.out.println("3 + x - y / 6 = " + (3 + x - y / 6)); 12 System.out.println("x + 4 * (y++ - z) + 19 = " + (x + 4 * (y++ - z) + 19)); 13 System.out.println("13.8 * = " + (13.8 * )); 14 System.out.println("--a * 12.5 (b ) = " + (--a * (b ))); 15 } // end main 16 } // end class Output * 7 = x - y / 6 = 36 x + 4 * (y++ - z) + 19 = * = a * 12.5 (b ) = Listing 3.8 A program to evaluate some arithmetic expressions.

23 123 Chapter 3 Operators, Expressions and Type Conversion Logical Expressions A simple logical expression is formed by combining numbers using comparison (>, >=, <, <=, ==,!=) or logical (!, &&,, &, ) operators. For example, 3>5 is a simple logical expression formed by combining two numbers, 3 and 5, using comparison operator >. Another example of simple logical expression is!done which is formed by combining the boolean type variable done with the logical NOT operator!. More complicated logical expressions are formed by combining two or more simple logical expressions using logical operators. For example, the above two simple logical expressions can be combined by using logical operator && to form the logical expression (3>5) && (!done). However, all logical expressions are evaluated to true or false. Logical expressions are evaluated according to the precedence and associativity rules shown in Appendix C. In general, comparison and logical operators have lower priority compared to arithmetic operators except for the logical operator! which has higher priority. In logical expressions, postfix increment and postfix decrement operators are evaluated first. Then, prefix increment, prefix decrement, unary plus, unary minus, and logical NOT operators are evaluated. Next, multiplication, division, and modulus operators are evaluated followed by addition and subtraction operators. Next, comparison operators are evaluated and finally logical operators are evaluated. The associativity of comparison and logical operators is from left to right except for the logical NOT operator which is from right to left. Thus, they are evaluated from left to right except for logical NOT operator which is evaluated from right to left. This means that, if an expression has more than one comparison operator, then these operators are evaluated from left to right, and if an expression has more than one logical operator, then these operators are also evaluated from left to right except for the logical NOT operator which is evaluated from right to left. Once again, you can always use parentheses to group operands and operators to avoid confusion. Example 3-5 gives examples of logical expressions. EXAMPLE 3-5 Expression Result Explanation!('A' > 'B') true Because 'A' > 'B' is false,!('a' > 'B') is true.!(6 <= 7) false Because 6 <= 7 is true,!(6 <= 7) is false (24 >= 35) && ('A' < 'B') false Because (24 >= 35) is false, ('A' < 'B') is true, and false && true is false, the expression evaluates to false. (14 >= 5) && ('A' < 'B') true Because (14 >= 5) is true, ('A' < 'B') is true, and true && true is true, the expression evaluates to true.

24 124 Chapter 3 Operators, Expressions and Type Conversion (14 >= 5) ('A' > 'B') true Because (14 >= 5) is true, ('A' > 'B') is false, and true false is true, the expression evaluates to true. ('A' <= 'a') (7!= 7) true Because ('A' <= 'a') is true, (7!= 7) is false, and true false is true, the expression evaluates to true. EXAMPLE 3-6 Evaluate the following logical expression: (24 >= 35) && ('A' < 'B') Now: (24 >= 35) && ('A' < 'B') = (false) && ('A' < 'B') = (false) && (true) = false Listing 3.9 shows a Java program that evaluates and outputs the logical expressions given in Example 3-5.

25 125 Chapter 3 Operators, Expressions and Type Conversion 1 // This program evaluates and outputs logical expressions. 2 3 public class LogicalExpressions 4 { 5 public static void main (String[] args) 6 { 7 int x=35, y=14, z=5; 9 char p='a', q='b'; System.out.println("!(p > q) = " +!(p > q)); 17 System.out.println("!(6 <= 7) = " +!(6 <= 7)); 18 System.out.println("(24 >= x) && (p < q) = " + ((24 >= x) && (p < q))); 19 System.out.println("(y >= z) && (p < q) = " + ((y >= z) && (p < q))); 20 System.out.println("(y >= z) (p > q) = " + ((y >= z) (p > q))); 21 System.out.println("(p <= 'a') (7!= 7)= " + ((p <= 'a') (7!= 7))); 22 } // end main 23 } // end class Output!(p > q) = true!(6 <= 7) = false (24 >= x) && (p < q) = false (y >= z) && (p < q) = true (y >= z) (p > q) = true (p <= 'a') (7!= 7) = true Listing 3.9 A program to evaluate some logical expressions. Mixed Expressions An expression that has operands of different data types is called a mixed expression. A mixed expression may contain both integers and floating-point numbers. The following expressions are examples of mixed expressions: / * / 2 In the first expression, the operator + has one integer operand and one floating-point operand. In the second expression, both operands for the operator / are integers; the first operand of + is the result of 6 / 4, and the second operand of + is a floating-point number. The third example is a more complicated mix of integers and floating-point numbers.

26 126 Chapter 3 Operators, Expressions and Type Conversion A mixed expression may also contain numbers, characters, and Boolean values (true or false). Such a mixed expression is a combination of both arithmetic and logical expressions and always evaluates to a Boolean value. The following expressions are also examples of mixed expressions: ('A' < 4 * 3 + 5) (17 < 4 * 3 + 5) (done) In the first expression, the operator < has one character operand and three integer operands. In the second expression, all operands are integers, except the operand done which is Boolean type variable. The questions arises here is how does Java evaluate such mixed expressions? Two rules apply when evaluating a mixed expression: 1. When evaluating an operator in a mixed expression: a. If the operator has the same types of operands (that is, both are integers or both are floating-point numbers, or both are Booleans, and so on), the operator is evaluated according to the type of the operand. Integer operands yield an integer result; floating-point numbers yield a floatingpoint number result; Boolean operands yield a Boolean result; and so on. b. If the operator has different types of operands (that is, one is an integer and the other is a floating-point number or one is an integer and the other is a character, or one is a Boolean and the other is long, and so on), then Java's conversion rules are performed for promoting one type to another. (See Section 3.4 for type conversion and casting.) In general, characters and integers are converted implicitly to floating-point numbers but vice versa is not true. Boolean type cannot be converted to or from any other type. When converting integers to floating-point numbers, during calculation the integer is treated temporarily as a floating-point number with the decimal part of zero, and then the operator is evaluated. The result is a floating-point number. 2. The entire expression is evaluated according to the precedence rules. The postfix increment and postfix decrement operators are evaluated first. Then, prefix increment, prefix decrement, unary plus, unary minus, and logical NOT operators are evaluated. Next, multiplication, division, and modulus operators are evaluated followed by addition and subtraction operators. Next, comparison operators are evaluated and then followed by logical operators. Basic arithmetic operators having the same level of precedence are evaluated from left to right. Comparison and logical operators having the same level of precedence are evaluated from left to right except for logical Not operator! which is evaluated from right to left. Grouping is allowed for clarity. Following these rules, when you evaluate a mixed expression, you concentrate on one operator at a time, using the rules of precedence. If the operator to be evaluated has operands of the same data type, evaluate the operator using Rule 1(a). That is, an operator with integer operands yields an integer result, and an operator with floatingpoint operands yields a floating-point result and so on. If the operator to be evaluated has operands of the different data types, evaluate the operator using Rule 1(b). For example, if one operand is an integer and the other operand is a floating-point, before

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. http://www.tutorialspoint.com/go/go_operators.htm GO - OPERATORS Copyright tutorialspoint.com An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

Operators in java Operator operands.

Operators in java Operator operands. Operators in java Operator in java is a symbol that is used to perform operations and the objects of operation are referred as operands. There are many types of operators in java such as unary operator,

More information

Prof. Navrati Saxena TA: Rochak Sachan

Prof. Navrati Saxena TA: Rochak Sachan JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

More information

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>= Operators in java Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: Unary Operator, Arithmetic

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Java enum, casts, and others (Select portions of Chapters 4 & 5) Enum or enumerates types Java enum, casts, and others (Select portions of Chapters 4 & 5) Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The

More information

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands Introduction Operators are the symbols which operates on value or a variable. It tells the compiler to perform certain mathematical or logical manipulations. Can be of following categories: Unary requires

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Department of Computer Science

Department of Computer Science Department of Computer Science Definition An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and

More information

A flow chart is a graphical or symbolic representation of a process.

A flow chart is a graphical or symbolic representation of a process. Q1. Define Algorithm with example? Answer:- A sequential solution of any program that written in human language, called algorithm. Algorithm is first step of the solution process, after the analysis of

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

COMP Primitive and Class Types. Yi Hong May 14, 2015

COMP Primitive and Class Types. Yi Hong May 14, 2015 COMP 110-001 Primitive and Class Types Yi Hong May 14, 2015 Review What are the two major parts of an object? What is the relationship between class and object? Design a simple class for Student How to

More information

Operators & Expressions

Operators & Expressions Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

More information

Operators in C. Staff Incharge: S.Sasirekha

Operators in C. Staff Incharge: S.Sasirekha Operators in C Staff Incharge: S.Sasirekha Operators An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups: JAVA BASIC OPERATORS http://www.tuto rialspo int.co m/java/java_basic_o perato rs.htm Copyrig ht tutorialspoint.com Java provides a rich set of operators to manipulate variables. We can divide all the

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands Performing Computations C provides operators that can be applied to calculate expressions: tax is 8.5% of the total sale expression: tax = 0.085 * totalsale Need to specify what operations are legal, how

More information

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE Operators and Type Conversion By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE Introduction An operator is a symbol which represents a particular operation that can be performed on some data.

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g. 1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object

More information

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

More information

Expressions and Precedence. Last updated 12/10/18

Expressions and Precedence. Last updated 12/10/18 Expressions and Precedence Last updated 12/10/18 Expression: Sequence of Operators and Operands that reduce to a single value Simple and Complex Expressions Subject to Precedence and Associativity Six

More information

LECTURE 3 C++ Basics Part 2

LECTURE 3 C++ Basics Part 2 LECTURE 3 C++ Basics Part 2 OVERVIEW Operators Type Conversions OPERATORS Operators are special built-in symbols that have functionality, and work on operands. Operators are actually functions that use

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

Arithmetic Operators. Portability: Printing Numbers

Arithmetic Operators. Portability: Printing Numbers Arithmetic Operators Normal binary arithmetic operators: + - * / Modulus or remainder operator: % x%y is the remainder when x is divided by y well defined only when x > 0 and y > 0 Unary operators: - +

More information

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Operators 2018W (Institute of Pervasive Computing, JKU Linz) OPERATORS Operators are required to form expressions. Depending on the number of operands they take, they are called:

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators. Lecture 3 COP 3014 Spring January 16, 2018 Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-Liang Lu Java Programming 45 / 79 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

More information

CT 229. Java Syntax 26/09/2006 CT229

CT 229. Java Syntax 26/09/2006 CT229 CT 229 Java Syntax 26/09/2006 CT229 Lab Assignments Assignment Due Date: Oct 1 st Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember:

More information

Information Science 1

Information Science 1 Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

More information

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a) Operators Representing and storing primitive data types is, of course, essential for any computer language. But, so, too, is the ability to perform operations on data. Java supports a comprehensive set

More information

Informatics Ingeniería en Electrónica y Automática Industrial

Informatics Ingeniería en Electrónica y Automática Industrial Informatics Ingeniería en Electrónica y Automática Industrial Operators and expressions in C Operators and expressions in C Numerical expressions and operators Arithmetical operators Relational and logical

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Disclaimer The slides are prepared from various sources. The purpose of the slides is for academic use only Operators in C C supports a rich set of operators. Operators

More information

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS OPERATORS Review: Data values can appear as literals or be stored in variables/constants Data values can be returned by method calls Operators: special symbols

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

UNIT 3 OPERATORS. [Marks- 12]

UNIT 3 OPERATORS. [Marks- 12] 1 UNIT 3 OPERATORS [Marks- 12] SYLLABUS 2 INTRODUCTION C supports a rich set of operators such as +, -, *,,

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto CS 170 Java Programming 1 Expressions Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 What is an expression? Expression Vocabulary Any combination of operators and operands which, when

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Unit-2 (Operators) ANAND KR.SRIVASTAVA Unit-2 (Operators) ANAND KR.SRIVASTAVA 1 Operators in C ( use of operators in C ) Operators are the symbol, to perform some operation ( calculation, manipulation). Set of Operations are used in completion

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning 4 Operations On Data 4.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: List the three categories of operations performed on data.

More information

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

JAVA Programming Fundamentals

JAVA Programming Fundamentals Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 4. Operations on Data

Chapter 4. Operations on Data Chapter 4 Operations on Data 1 OBJECTIVES After reading this chapter, the reader should be able to: List the three categories of operations performed on data. Perform unary and binary logic operations

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 Data types, Variables, and Operators 4 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators Expressions 1 Expressions n Variables and constants linked with operators Arithmetic expressions n Uses arithmetic operators n Can evaluate to any value Logical expressions n Uses relational and logical

More information

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values

More information

Operators and Expressions:

Operators and Expressions: Operators and Expressions: Operators and expression using numeric and relational operators, mixed operands, type conversion, logical operators, bit operations, assignment operator, operator precedence

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

UNIT-II. Part-2: CENTRAL PROCESSING UNIT

UNIT-II. Part-2: CENTRAL PROCESSING UNIT Page1 UNIT-II Part-2: CENTRAL PROCESSING UNIT Stack Organization Instruction Formats Addressing Modes Data Transfer And Manipulation Program Control Reduced Instruction Set Computer (RISC) Introduction:

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

LAB A Translating Data to Binary

LAB A Translating Data to Binary LAB A Translating Data to Binary Create a directory for this lab and perform in it the following groups of tasks: LabA1.java 1. Write the Java app LabA1 that takes an int via a command-line argument args[0]

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Types and Expressions. Chapter 3

Types and Expressions. Chapter 3 Types and Expressions Chapter 3 Chapter Contents 3.1 Introductory Example: Einstein's Equation 3.2 Primitive Types and Reference Types 3.3 Numeric Types and Expressions 3.4 Assignment Expressions 3.5 Java's

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Prepared by: Shraddha Modi

Prepared by: Shraddha Modi Prepared by: Shraddha Modi Introduction Operator: An operator is a symbol that tells the Computer to perform certain mathematical or logical manipulations. Expression: An expression is a sequence of operands

More information

ME 461 C review Session Fall 2009 S. Keres

ME 461 C review Session Fall 2009 S. Keres ME 461 C review Session Fall 2009 S. Keres DISCLAIMER: These notes are in no way intended to be a complete reference for the C programming material you will need for the class. They are intended to help

More information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 Data types, Variables, and Operators 4 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44

More information

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87 Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and

More information

4. Inputting data or messages to a function is called passing data to the function.

4. Inputting data or messages to a function is called passing data to the function. Test Bank for A First Book of ANSI C 4th Edition by Bronson Link full download test bank: http://testbankcollection.com/download/test-bank-for-a-first-book-of-ansi-c-4th-edition -by-bronson/ Link full

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Chapter 12 Variables and Operators Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2 Highlights (2) r. height

More information

QUIZ: What value is stored in a after this

QUIZ: What value is stored in a after this QUIZ: What value is stored in a after this statement is executed? Why? a = 23/7; QUIZ evaluates to 16. Lesson 4 Statements, Expressions, Operators Statement = complete instruction that directs the computer

More information

Lecture 3 Operators MIT AITI

Lecture 3 Operators MIT AITI Lecture 3 Operators MIT AITI - 2004 What are Operators? Operators are special symbols used for mathematical functions assignment statements logical comparisons Examples: 3 + 5 // uses + operator 14 + 5

More information

Programming for Engineers: Operators, Expressions, and Statem

Programming for Engineers: Operators, Expressions, and Statem Programming for Engineers: Operators,, and 28 January 2011 31 January 2011 Programming for Engineers: Operators,, and Statem The While Loop A test expression is at top of loop The program repeats loop

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Chapter 4: Basic C Operators

Chapter 4: Basic C Operators Chapter 4: Basic C Operators In this chapter, you will learn about: Arithmetic operators Unary operators Binary operators Assignment operators Equalities and relational operators Logical operators Conditional

More information

Computers Programming Course 6. Iulian Năstac

Computers Programming Course 6. Iulian Năstac Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information