Computer Science

Java Arithmetic Operators

Java Arithmetic Operators are symbols used to perform mathematical operations in Java programming language. These operators include addition, subtraction, multiplication, division, and modulus. They are used to manipulate numeric values and perform calculations in Java programs.

Written by Perlego with AI-assistance

10 Key excerpts on "Java Arithmetic Operators"

  • Book cover image for: OCP Oracle Certified Professional Java SE 17 Developer Study Guide
    • Scott Selikoff, Jeanne Boyarsky(Authors)
    • 2022(Publication Date)
    • Sybex
      (Publisher)
    Working with Binary Arithmetic Operators Next, we move on to operators that take two operands, called binary operators . Binary operators are by far the most common operators in the Java language. They can be used to perform mathematical operations on variables, create logical expressions, and perform basic variable assignments. Binary operators are often combined in complex expressions with other binary operators; therefore, operator precedence is very important in evaluating expressions containing binary operators. In this section, we start with binary arithmetic operators; we expand to other binary operators in later sections. Arithmetic Operators Arithmetic operators are those that operate on numeric values. They are shown in Table 2.4. TABLE 2.4 Binary arithmetic operators Operator Example Description Addition a + b Adds two numeric values Subtraction c - d Subtracts two numeric values Multiplication e * f Multiplies two numeric values Division g / h Divides one numeric value by another Modulus i % j Returns the remainder after division of one numeric value by another Working with Binary Arithmetic Operators 73 You should know all but modulus from early mathematics. If you don’t know what modulus is, though, don’t worry—we’ll cover that shortly. Arithmetic operators also include the unary operators, ++ and -- , which we covered already. As you may have noticed in Table 2.1, the multiplicative operators ( * , / , % ) have a higher order of precedence than the additive operators ( + , - ). Take a look at the following expression: int price = 2 * 5 + 3 * 4 -8; First, you evaluate the 2 * 5 and 3 * 4 , which reduces the expression to this: int price = 10 + 12 -8; Then, you evaluate the remaining terms in left-to-right order, resulting in a value of price of 14 . Make sure you understand why the result is 14 because you will likely see this kind of operator precedence question on the exam.
  • Book cover image for: OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2014(Publication Date)
    • Sybex
      (Publisher)
    We'll spend the first half of this chapter discussing many of the operators in this list as well as how operator precedence determines which operators should be applied first. Note that you won't be tested on some operators, although we recommend that you be aware of their existence.

    Working with Binary Arithmetic Operators

    We'll begin our discussion with
    binary operators
    , by far the most common operators in the Java language. They can be used to perform mathematical operations on variables, create logical expressions, as well as perform basic variable assignments. Binary operators are commonly combined in complex expressions with more than two variables; therefore, operator precedence is very important in evaluating expressions.

    Arithmetic Operators

    Arithmetic operators
    are often encountered in early mathematics and include addition (+ ), subtraction (- ), multiplication (* ), division (/ ), and modulus (% ). They also include the unary operators, ++ and -- , although we cover them later in this chapter. As you may have noticed in Table 2.1 , the multiplicative operators (* , / , % ) have a higher order of precedence than the additive operators (+ , - ). That means when you see an expression such as this:
    int x = 2 * 5 + 3 * 4 - 8;
    you first evaluate the 2 * 5 and 3 * 4 , which reduces the expression to the following:
    int x = 10 + 12 - 8;
    Then, you evaluate the remaining terms in left-to-right order, resulting in a value of x of 14 . Make sure you understand why the result is 14 as you'll likely see this kind of operator precedence question on the exam.
    Notice that we said “Unless overridden with parentheses…” prior to Table 2.1
  • Book cover image for: Code with Java 21
    eBook - ePub

    Code with Java 21

    A practical approach for building robust and efficient applications (English Edition)

    HAPTER 5Arithmetic Operations Mathematics is the language with which God has written the universe.
    Galileo Galilei
    Introduction
    In this chapter, we will understand how to perform arithmetic in Java. This will lead us to discuss some nuances of how computers process math. We will also take a quick look at how to build simple unit tests, as the deterministic nature of arithmetic makes a good backdrop for teaching the basics of unit testing.
    While some may find math daunting, as software developers, we must embrace it. Understanding how computers execute arithmetic operations is central to learning about software development and, as Galileo inferred, the universe as well.
    Structure In this chapter, we will cover the following topics:
    • Integer arithmetic
    • Floating point arithmetic
    Objectives
    The primary aim of this chapter is to build a foundational understanding of how to leverage arithmetic operations in Java code. We will also take the opportunity to introduce unit testing. This leads to the following objectives for this chapter:
    • Learn how to perform integer arithmetic in Java.
    • Learn how to perform floating point arithmetic in Java.
    • Understand how computers process arithmetic under the hood .
    • Learn a little about unit testing and how to use it to ensure consistent method behavior.
    Integer arithmetic
    We will start by showing some simple arithmetic with integers (whole numbers). First, create a new Java class named MathExamples in a new package named chapter5 . Make sure this class has a main() method:
    package chapter5;   public class mathExamples {   public static void main() {   } }
    Inside our main() method, let us define two integer variables:
    int intNumA = 5; int intNumB = 3; Addition Now, let us add them together and print the result: System.out.println(intNumA + " + " + intNumB + " = " + intNumA + intNumB); If we run our code, the output should be as follows: 5 + 3 = 53
    However, this output is not what we expected. After all, 5 plus 3 is equal to 8 , not 53
  • Book cover image for: Java
    eBook - ePub

    Java

    The Comprehensive Guide

    • Christian Ullenboom(Author)
    • 2022(Publication Date)
    • SAP PRESS
      (Publisher)

    2.4     Expressions, Operands, and Operators

    Let’s start with some mathematical expressions and then illustrate how they are written in Java. A mathematical formula, such as the expression -27 * 9 , consists of operands and operators . For example, an operand is a variable, a literal, or the return of a method call. In the case of a variable, the value is read from the variable and the calculation is performed with it.
    The operators link the operands. Depending on the number of operands, the following types of operators are distinguished:
    • An operator defined on exactly one operand is referred to as a unary operator (or monadic operator ). The minus (negative sign ) before an operand is a unary operator since it applies to exactly the following operand.
    • The usual operators (plus, minus, multiply, and divide) by are binary ( dyadic ) operators .
    • A question mark operator is used for conditional expressions, which have 3 characters.
    Operators allow the connection of individual expressions to new expressions. Some operators are familiar from school, such as addition, comparison, assignment, and others. C(++) programmers will recognize many old friends.

    2.4.1    Assignment Operator

    In Java, the equal sign = is used for an assignment . [ 57 ] The assignment operator is a binary operator with the variable to be assigned on the left and an expression on the right.
    [eg]   Example Let’s look at some expressions with assignments:
    int quantity = 12 , total ; total = quantity * 2 ;
    The multiplication calculates the product of 12 and 2 and stores the result in total . From all primitive variables that occur in the expression, the value is read and inserted into the expression. [ 58 ] This process is also called a value operation because the value of the variable is considered (and not its location or even its variable name).
    Only after the expression has been evaluated does the assignment operator copy the result into the variable. If runtime errors occur, for example, due to a division by zero, no write access to the variable is possible.
  • Book cover image for: Brief Java
    eBook - PDF

    Brief Java

    Early Objects

    • Cay S. Horstmann(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    For example, BigDecimal d = new BigDecimal("4.35"); BigDecimal e = new BigDecimal("100"); © FinnBrandt/iStockphoto. We prefer programs that are easy to understand over those that appear to work by magic. 4.2 Arithmetic 107 BigDecimal f = d.multiply(e); System.out.println(f); // Prints 435.00 4.2 Arithmetic In this section, you will learn how to carry out arithmetic calculations in Java. 4.2.1 Arithmetic Operators Java supports the same four basic arithmetic operations as a calculator—addition, subtraction, multiplication, and division—but it uses different symbols for the multi- plication and division operators. You must write a * b to denote multiplication. Unlike in mathematics, you can- not write a b, a · b, or a × b. Similarly, division is always indicated with the / operator, never a ÷ or a fraction bar. For example, a b + 2 becomes (a + b) / 2. The combination of variables, literals, operators, and/or method calls is called an expression. For example, (a + b) / 2 is an expression. Parentheses are used just as in algebra: to indicate in which order the parts of the expression should be computed. For example, in the expression (a + b) / 2, the sum a + b is computed first, and then the sum is divided by 2. In contrast, in the expression a + b / 2 only b is divided by 2, and then the sum of a and b / 2 is formed. As in regular algebraic notation, multiplication and division have a higher precedence than addition and sub- traction. For example, in the expression a + b / 2, the / is carried out first, even though the + operation occurs further to the left (see Appendix B). If you mix integer and floating-point values in an arithmetic expression, the result is a floating-point value. For example, 7 + 4.0 is the floating-point value 11.0. 4.2.2 Increment and Decrement Changing a variable by adding or subtracting 1 is so common that there is a special shorthand for it.
  • Book cover image for: OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2019(Publication Date)
    • Sybex
      (Publisher)
    tiger . The result is then printed:
    lion is 3 tiger is 5

    Working with Binary Arithmetic Operators

    Next, we move on to operators that take two arguments, called
    binary operators
    . Binary operators are by far the most common operators in the Java language. They can be used to perform mathematical operations on variables, create logical expressions, and perform basic variable assignments. Binary operators are often combined in complex expressions with other binary operators; therefore, operator precedence is very important in evaluating expressions containing binary operators.
    In this section, we’ll start with binary arithmetic operators, shown in Table 3.3 . In the following sections, we’ll expand to other binary operators that you need to know for the exam.
    Table 3.3
    Binary arithmetic operators
    Operator Description
    + Adds two numeric values
    - Subtracts two numeric values
    * Multiplies two numeric values
    / Divides one numeric value by another
    % Modulus operator returns the remainder after division of one numeric value by another

    Arithmetic Operators

    Arithmetic operators
    are often encountered in early mathematics and include addition (+ ), subtraction (- ), multiplication (* ), division (/ ), and modulus (% ). If you don’t know what modulus is, don’t worry—we’ll cover that shortly. Arithmetic operators also include the unary operators, ++ and -- , which we covered already. As you may have noticed in Table 3.1 , the multiplicative operators (* , / , % ) have a higher order of precedence than the additive operators (+ , - ). Take a look at the following expression:
    int price = 2 * 5 + 3 * 4 - 8;
    First, you evaluate the 2 * 5 and 3 * 4 , which reduces the expression to this:
    int price = 10 + 12 - 8;
    Then, you evaluate the remaining terms in left-to-right order, resulting in a value of price of 14 . Make sure you understand why the result is 14
  • Book cover image for: Java All-in-One For Dummies
    • Doug Lowe(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    Then the unary minus operator is applied, giving a result of -9. Finally, -9 is multiplied by a, giving a result of -27. Using Increment and Decrement Operators One of the most common operations in computer programming is adding or sub- tracting 1 from a variable. Adding 1 to a variable is called incrementing the variable. Subtracting 1 is called decrementing. The traditional way to increment a variable is this: a = a + 1; Here the expression a + 1 is calculated, and the result is assigned to the variable a. Working with Numbers and Expressions CHAPTER 3 Working with Numbers and Expressions 105 Java provides an easier way to do this type of calculation: the increment (++) and decrement (--) operators. These unary operators apply to a single variable. Thus, to increment the variable a, you can code just this: a++; Note that an expression that uses an increment or decrement operator is a state- ment by itself. That’s because the increment or decrement operator is also a type of assignment operator, as it changes the value of the variable it applies to. You can use the increment and decrement operators only on variables — not on numeric literals or other expressions. Java doesn’t allow the following expres- sions, for example: a = b * 5++; // can't increment the number 5 a = (b * 5)++; // can't increment the expression (b * 5) Note that you can use an increment or decrement operator in an assignment statement. Here’s an example: int a = 5; int b = a--; // b is set to 4, a is set to 5 When the second statement is executed, the assignment is performed first, so b is set to 5. Then, a is decremented to 4. The increment and decrement operators are unusual because they are unary oper- ators that can be placed either before (prefix) or after (postfix) the variable they apply to. Whether you place the operator before or after the variable can have a major effect on how an expression is evaluated.
  • Book cover image for: Java Foundations
    • Todd Greanier(Author)
    • 2006(Publication Date)
    • Sybex
      (Publisher)
    If it returns 0, one number is a power of the other. The modulus operator is a lesser known, but still fairly common operator. This operator divides the first number by the second and returns the remainder. This can be used with integers and floating-point primitives. To see how the modulus operator is used, you can change the existing MathDemo class slightly: public class MathDemo { 76 Chapter 3 public static void main(String[] args) { int x = 6; int y = 3; System.out.println(x + y); // 9 System.out.println(x - y); // 3 System.out.println(x * y); // 18 System.out.println(x/y); // 2 System.out.println(x % y); // 0 x = x + 1; System.out.println(x % y); // 1 } } Because 6/3 is 2 without any remainder, the first of these new statements prints 0. In the next line, the x variable has 1 added to it, and then this new value of 7 is used in the subsequent modulus operation, which prints 1. This is because 3 fits into 7 2 times, with 1 left over. The Unary Arithmetic Operators Some operators in Java do not require two operands, making them unary in nature. Some of them have to do with arithmetic while others have to do with logical operations. Here are the main unary operators: ◆ ++ ◆ --◆ -The Increment Operator: ++ The unary operator is an increment operator and can be used before or after a variable. When used before, it is called a preincrement operator; when used after, it is called a postincrement operator. Here is a code snippet that shows both the preincrement version and postin-crement version of this operator in action: int f = 10; System.out.println(f++ + 2); // 12 System.out.println(++f + 2); // 14 The difference between these two forms of the increment operator is seen in this example. The call to (f++ + 2) uses the postincrement operator. What Keywords and Operators 77 happens here is that 2 is added to the current value of f (which is 10, as specified on the previous line), and that is what is printed.
  • Book cover image for: Microsoft Visual Basic 2017 for Windows, Web, and Database Applications: Comprehensive
    182 Chapter 4 Variables and Arithmetic Operations The arithmetic operators shown in Figure 4-52 are explained in the following paragraphs: Addition The addition arithmetic operator (+) adds the numeric values immediately to the left and right of the operator and replaces the arithmetic expression in the assignment statement. For example, in Figure 4-53, the value in the decPrice variable is added to the value in the decTax variable. In Figure 4-53, the arithmetic expression (decPrice + decTax) is evaluated, and then the assignment statement copies the sum to the decTotal variable in RAM. An arithmetic expression that uses the addition operator can contain more than two numeric values to be added. For example, in Figure 4-54, three variables are used in the arithmetic expression. In Figure 4-54, the value in decRegularPay is added to the value in decOver- timePay. The result then is added to decBonusPay, and that sum is copied to the decTotalPay variable. Visual Basic imposes no limit on the number of variables in an arithmetic expression. In addition to variables, arithmetic expressions can contain literals. The assign- ment statement in Figure 4-55 uses a literal. arithmetic expression 118.25 = 110.00 + 8.25 decTotal decPrice decTax FIGURE 4-53 iStockphoto.com/Tpopova FIGURE 4-54 Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Arithmetic Operations 183 In Figure 4-55, the value 10.25 is added to the value in the decInternetTicket- Cost variable, and that sum is placed in the decTicketCost variable.
  • Book cover image for: Java Programming Fundamentals
    eBook - PDF

    Java Programming Fundamentals

    Problem Solving Through Object Oriented Analysis and Design

    • Premchand S. Nair(Author)
    • 2008(Publication Date)
    • CRC Press
      (Publisher)
    Class and Java Fundamentals ■ 39 Output 12 + 51 = 63 – 12 + 51 = 39 51 – 12 = 39 – 51 – 12 = – 63 3 * 8 = 24 19 / 5 = 3 20 / 5 = 4 19 % 5 = 4 – 19 % 5 = – 4 19 % – 5 = 4 – 19 % – 5 = – 4 5 % 19 = 5 All five operations can be used on two integers or two floating point numbers or one integer and one floating point number. Example 2.14 illustrates four operations on floating point numbers. Modulus operator is rarely used in connection with floating point operands and hence omitted. Example 2.14 The following program computes all the expressions given in Table 2.5: /** Demonstration of numeric operations in floating point mode */ public class FloatingPointOperator { public static void main(String[] args) { System.out.println( (12.0 + 49.2) = + (12.0 + 49.2)); System.out.println( (12.3 + 49.2) = + (12.3 + 49.2)); System.out.println( (12.3 - 49.2) = + (12.3 - 49.2)); System.out.println( (12.3 * 49.2) = + (12.3 * 49.2)); System.out.println( (12.3 / 49.2) = + (12.3 / 49.2)); } } Output (12.0 + 49.2) = 61.2 (12.3 + 49.2) = 61.5 (12.3 - 49.2) = -36.900000000000006 (12.3 * 49.2) = 605.1600000000001 (12.3 / 49.2) = 0.25 40 ■ Java Programming Fundamentals Note that (12.3 – 49.2) is not – 36.9, as you might have expected; rather, the value computed by the above program is –36.900000000000006. Again note that multi-plication also produced a result different from what you might have expected. In other words, floating point arithmetic is not exact. So far, we have used all operators with two operands. If an operator has two operands, it is called a binary operator . Thus addition, subtraction, multiplication, division, and modulo. are binary operations. In other words, + , – , *, and % are binary operators. However, we also use symbols + and – as unary operators or operators with one operand. For example, in the expressions + 12.5 and – 51.5, the operators + and – are unary operators. Note further that in the expression + 12.5, the symbol + does not stand for addition.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.