Bifalgorithm post · Computer science one · Operators

How do Java’s standard arithmetic operators work?

How do Java’s standard arithmetic operators work? (Computer science one · Operators) — "Java supports the standard arithmetic operators for addition, subtracti…

Ideas in this flowchart

  • Java arithmetic operators and numeric type compatibility
  • Java supports addition (+), subtraction (-), multiplication (*), and division (/).
  • Each arithmetic operator is binary and acts on two operands, which may be literals or variables.
  • Multiplication and division have precedence over addition and subtraction.
  • Integer arithmetic includes addition, subtraction, multiplication, division, and expressions such as a + b * c.
  • Integer division truncates the result.
  • Floating-point arithmetic supports the same operators with double values.
  • Arithmetic can combine integer and double values, such as w = a + x.
  • A double result cannot be assigned directly to an int variable.
  • An explicit cast can assign the result to int: d = (int) (b + y).
  • The explicit cast truncates the value; in the example, d becomes 23.
Feed/

How do Java’s standard arithmetic operators work?

No cover

Channel

Computer science one

1 page

"Java supports the standard arithmetic operators for addition, subtraction, multiplication, and division using +, -, *, and / respectively. Each of these operators is a binary operator that acts on two operands, which can either be literals or other variables, and they follow the usual rules of arithmetic when it comes to order of precedence: multiplication and division are performed before addition and subtraction.\n\nint a = 10, b = 20, c = 30, d;\n\nd = a + 5;\n\nd = a + b;\n\nd = a - b;\n\nd = a + b * c;\n\nd = a * b;\n\nd = a / b; // integer division and truncation\n\ndouble x = 1.5, y = 3.4, z = 10.5, w;\n\nw = x + 5.0;\n\nw = x + y;\n\nw = x - y;\n\nw = x + y * z;\n\nw = x * y;\n\nw = x / y;\n\nYou can do arithmetic with both types:\n\nw = a + x;\n\nHowever, you cannot assign a double to an integer:\n\nd = b + y; // compilation error\n\nYou can do so with an explicit type cast:\n\nd = (int) (b + y); // though truncation occurs, d is 23"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.