[Java] Basic Arithmetic Example Explained

Some Basic JAVA Coding Explained.. Read more.

Welcome.  Let’s touch up on these four arithmetic operators that you’ll use in basic mathematical situations.

+ : Addition operator
-  : Subtract operator
/  : Divide operator
*  : Multiply operator

However, to use them is perhaps a different story.  Take a look at this simple snippet on adding two variables together.

private int javaToday = 3, cracks = 4, result;

if (javaToday == 3)
       result = javaToday+cracks;

We’ve declared three variables all of type int and of access type private.  Simple, we’ve already learned this.  We’ve created an if statement; however, you’ll notice the statement inside.  We’ve basically written, “result equals what ever the variable javaToday plus cracks equals to”.  Well, as you can see in the decelerations the variable javaToday is equal to three while cracks is equal to four.  Keeping it simple, three plus four equals seven thus the variable result now equals seven!  We should ALL know that hopefully; however if you don’t, please close down your computer and never come back.

Now, we’ll take the same decelerations and their values and instead of adding, we’ll subtract.

result = javaToday-cracks;

Once this statement is executed, the variable result will in turn have a value of one.  It’s very much the same while dealing with the multiply operator and division operator however be careful with those as we must not make an int contain a decimal point.  So, be careful while multiplying or dividing expressions because they are not always even.  And, since an int doesn’t hold decimal points, an arithmetic expression such as 24/11 (twenty-four divided by eleven) would result in an error thrown by the compiler since the initial result of that would contain a decimal.  However, if you change the variable result to of type long, then that would work.  So, the variable that gets the results basically back from that mathematical calculation must essentially deal correctly with what expression that can come back. 

So, let’s go back to a Helloworld class and add a arithmetic statement.

public class HelloWorld {

       private int javaWorld = 3, necro = 5, tooShai;

       public static void main(String args[]) {
               for (int i = 0; i < 4; i++) {
                       System.out.println(”Hello World!”); // Prints out a simple message
               }
               if (javaWorld > 2) {
                       tooShai = necro – javaWorld;
                       System.out.println(”tooShai is now equal to “+tooShai+”.”);
               }
       }
}

Hope you’ve learned something.

Thanks for Reading

Leave Your Response