Operators
Java provides a rich operator environment. An operator is a symbol that tells the compiler to perform a specific mathematical or logical manipulation. Java has four general classes of operators: arithmetic, bit wise,relational, and logical . Java also defines some additional operators that handle certain special situations. This module will examine the arithmetic, relational,and logical operators. We will also examine the assignment operator. The bit wise and other special operators are examined later.
Arithmetic Operators
Java defines the following arithmetic operators:
Operator Meaning
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
– – Decrements
1. A scope defines the visibility and lifetime of an object. A block defines a scope.
2. A variable can be defined at any point within a block.
3. Inside a block, a variable is created when its declaration is encountered. It is destroyed when the block exits.
The operators+,–,*, and/ all work the same way in Java as they do in any other computer language (or algebra, for that matter). These can be applied to any built-in numeric data type. They can also be used on objects of type char. Although the actions of arithmetic operators are well known to all readers, a few special situations warrant some explanation. First, remember that when/is applied to an integer, any remainder will be truncated; for example, 10/3 will equal 3 in integer division. You can obtain the remainder of this division by using the modulus operator %. It works in Java the way it does in other languages: it yields the remainder of an integer division. For example, 10 % 3 is 1. In Java, the % can be applied to both integer and floating-point types. Thus, 10.0 % 3.0 is also 1. The following program demonstrates the modulus operator.
// Demonstrate the % operator.
class ModDemo
{ public static void main(String args[])
{
int iresult, irem;
double dresult, drem;
iresult = 10 / 3;
irem = 10 % 3;
dresult = 10.0 / 3.0;
drem = 10.0 % 3.0;
System.out.println("Result and remainder of 10 / 3: " + iresult + " " + irem); System.out.println("Result and remainder of 10.0 / 3.0: " + dresult + " " + drem);
}
}
The output from the program is shown here:
Result and remainder of 10 / 3: 3 1
Result and remainder of 10.0 / 3.0: 3.3333333333333335 1.0
As you can see, the%yields a remainder of 1 for both integer and floating-point operations
0 comments:
Post a Comment