Subtraction in Java: Method, Code & Examples

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Multiplying in Java: Method & Examples

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Subtraction in Java
  • 1:44 Different Data Types
  • 3:18 BigDecimal
  • 4:17 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

Arithmetic operations are a core function of any programming language. This lesson will describe methods for subtraction in Java, providing working code examples.

Subtraction in Java

Java allows for a wide range of arithmetic operations, from the simplest calculation to the most complex algorithm. Before we can begin writing programs that calculate lens settings for space telescopes, we need to start at the beginning. This lesson will cover subtraction in Java, but it also helps to be aware of the other arithmetic operators available.

In Java, the operators used to perform math are laid out on the table shown below:

Operator Function
- Subtract
+ Add
* Multiply
/ Divide
% Modulo/Remainder

As you can see, the symbols are rather self-explanatory, except for the percent symbol (%) which, as you can see, refers to a modulo or a remainder. Let's take a look at a straightforward subtraction operation. We're going to subtract 1 from an integer value (a counter), and display the output, which you can see below:

int counter = 15;
counter = counter - 1;
System.out.println("Subtraction = " + counter);

When this code runs, the next output is displayed which, as you can see, has the subtraction value placed at 14:


Java subtraction basic output


Java fully supports more complex statements with multiple arithmetic operations. Just as you learned in math, the order of operations is important. Make sure the parenthesis around your statements are placed properly; after all, Java will only do what you tell it to do! For example, the code shown below first subtracts 1 from the counter, then subtracts the enrolled variable from this result:

int counter = 15;
int enrolled = 3;
counter = (counter - 1) - enrolled;

A good habit is to desk-check your equations by plugging in some sample numbers, then making sure you get the result you expect. In this example, the result should be 11: (15-1) - 3.


Java subtraction complex output


As you can see, the counter value is placed at 11.

So far, we've been working with integers. What if you have a mix of data types?

Different Data Types

So what happens if you try to subtract numbers of a different data type? It depends on the data types involved. For example, it's totally okay to subtract an int from a double or float, since those data types will maintain the precision. Therefore, the code shown below will compile and run just fine, returning a value of 37.34 (52.34 - 15).

int counter = 15;
double price = 52.34;
price = price - counter;

But remember: you can't create an integer value and subtract doubles from it. In other words, this will cause compiler errors, like the one you can see below:

counter = counter - price;

In fact, most developer tools will stop you right away. The image below is what the code looks like in the tool:


Java subtract double from int error


If you have mixed variable types, it would be a good idea to convert them up to the data type with the most precision, or try to perform subtraction on variables that are all the same type. In this case, we'd convert our integer values to double and then perform the subtraction. This helps eliminate some nasty surprises in the code.

While a little more complex, we can change our primitive integer value into an instance of the Integer class. This will let us access the doubleValue() method and thus convert the integer to a double. You can see this playing out in the code shown below:

int counter = 15;
double price = 52.34;
//create instance of Integer
Integer counter2 = new Integer(counter);
double counterD = counter2.doubleValue();
price = price - counterD;
System.out.println("Double minus int: " + price);

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support