The modulus Operators
By: aathishankaran Printer Friendly Format
The modulus Operators
The modulus operator, % returns the remainder of a division operation. It can be applied to floating-point types as well as integer types. (This differs from C/C++, in which the % can only be applied to integer types.) The following example program demonstrates the %:
//Demonstrate
the % operator.
class
Modulus {
public static void main ( String args[]) {
int x = 42;
double y = 42.25;
System.out.println(“x mod 10 = “ + x % 10);
System.out.println(“y
mod 10 = “ + y % 10);
}
}
When you run this program you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Assignment Operators
Java provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite common in programming
a = a+4;
in java, you can rewrite this statement as shown here.
a +=4;
This version uses the += assignment operator. Both statements perform the same action: they increase the value of a by 4.
Here is another example,
a = a % 2;
Which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a/2 and puts that result back into a.
There are assignment operators provide two benefits. First, they save you a bit of typing, because they are “shorthand†for their equivalent long forms. Second, they are implement more efficiently by the java run-time system than are their equivalent long forms.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java