Skip to main content
ICT
Lesson A3 - Primitive Data Types
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

F. Math Operators page 8 of 14

  1. Java provides 5 math operators as listed below:

    + Addition, as well as unary +
    - Subtraction, as well as unary -
    * Multiplication
    / Floating point and integer division
    % Modulus, remainder of integer or floating point division
  2. The numerical result and data type of the answer depends on the type of operands used in a problem.

  3. For all the operators, if both operands are integers, the result is an integer. Examples:
    2 + 3 -> 5 9 - 3 -> 6
    4 * 8 -> 32 11/2 -> 5

    Notice that 11/2 is 5, and not 5.5. This is because ints work only with whole numbers. The remaining half is lost in integer division.

  4. If either of the operands is a double type, the result is a double type. Examples:

    2 + 3.000 -> 5.000
    25 / 6.75 -> 3.7037
    11.0 / 2.0 -> 5.5

    When an integer and a double are used in a binary math expression, the integer is promoted to a double value, and then the math is executed. In the example 2 + 3.000 -> 5.000, the integer value 2 is promoted to a double (2.000) and then added to the 3.000.

  5. The modulus operator (%) returns the remainder of dividing the first operand by the second. For example:
    10 % 3 -> 1 2 % 4 -> 2
    16 % 2 -> 0 27.475 % 7.22 -> 5.815
  6. Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator. A unary operator works with only one value. Applying the negation operator to an integer returns an integer, while applying it to a double returns a double value. For example:
    -(67) -> -67 -(-2.345) -> 2.345
  7. To obtain the answer of 5.5 to a question like 11/2, we must cast one of the operands.
    (double)11/2 results in 5.5

    The casting operators are unary operators with the following syntax:

    (type) operand

    The same effect can also result from simply

    11.0/2

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.