Home >Java >javaTutorial >The difference between / and % in java

The difference between / and % in java

下次还敢
下次还敢Original
2024-04-29 01:33:15548browse

/ is used for integer division operations and returns the quotient, while % is used for remainder operations and returns the remainder. For example: 10 / 3 = 3, 10 % 3 = 1, because the quotient of 10 divided by 3 is 3 and the remainder is 1.

The difference between / and % in java

The difference between / and % in Java

Short answer:

/ is used for integer division operations, and % is used for remainder operations.

Detailed explanation:

Integer division operation (/)

  • / Operator Performs an integer division operation in which the remainder of the dividend is discarded.
  • It divides the dividend by the divisor and returns the quotient as the result.
  • For example: 10 / 3 = 3, because the quotient of 10 divided by 3 is 3.

Remainder operation (%)

  • % operator performs the remainder operation, which returns the dividend divided by the divisor The remaining remainder.
  • It does not consider the quotient part.
  • For example: 10 % 3 = 1, because the remainder of 10 divided by 3 is 1.

Example:

<code class="java">int dividend = 10;
int divisor = 3;

System.out.println("整除运算结果:" + (dividend / divisor)); // 输出 3
System.out.println("求余运算结果:" + (dividend % divisor)); // 输出 1</code>

Other notes:

  • For integer division operations, if the dividend or If the divisor is a floating point number, the result will be converted to an integer.
  • For the remainder operation, if the divisor is 0, an ArithmeticException exception will be thrown.

By understanding the difference between the / and % operators, you can correctly perform division and remainder operations in your code.

The above is the detailed content of The difference between / and % in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn