Wednesday 28 October 2015

Java | Shorthand, Increment and Decrement Operators


There comes a time in Java programming when you want to carry out an operation on a variable and assign that operation to that same variable.

For example:


Look at this chunk of code

//Declaring and initializing a variable
int age = 20;
// What is the age after 5 years?
age = age + 5;

Do you see that? we used age in the computation and assigned the answer to the same age.
There is a shorthand way of doing this things, just as there is shorthand in business.

Here is the shorthand way of doing it.

// Declaring and initializing a variable

int age = 20;
// What is the age after 5 years?
age += 5;

Using += is makes it a shorthand operator.

This can be done with all the numeric operators I showed you in one of my previous posts.

+=  -  Addition Assignment Shorthand - egg = egg + 10 in shorthand is egg += 10
-=  -  Subtraction Assignment Shorthand  -  egg = egg - 10 in shorthand is egg -= 10
*=  -  Multiplication Assignment Shorthand  -  egg = egg * 10 in shorthand is egg *= 10
/=  -  Division Assignment Shorthand  -  egg = egg / 10 in shorthand is egg /= 10
%=  -  Remainder Assignment Shorthand  -  egg = egg % 10 in shorthand is egg %= 10

Example: Shorthand - Multiplication

package nicholas;
public class ShortHand{
public static void main(String [] args){
int number = 5;
System.out.println("The previous number is "+number+".");
number *= 5;
System.out.println("The present number is "+number+".");
}
}

Here is the screenshot of the code:

Here is the output:


Increment and Decrement Operators

Increment is the adding of 1 to a variable.
This can be done before or after the variable

Eg:
Preincrement
int egg = 7;
int count = ++egg;
// The value of count here is 8 and the value of egg is 8

Postincrement
int egg = 7;
int count = egg++;
// The value of count here is 7 and the value of egg is 8

Decrement is the subtraction of 1 from a variable, which can be done before or after the variable as well.

Eg:
Predecrement
int ball = 19;
int goal = --ball;
// The value of goal here is 18 and the value of ball is also 18

Postdecrement
int ball = 19;
int goal = ball--;
// The value of goal here is 19 and the value of ball is 18

That's all for now.

I HOPE YOU GOT THE GIST.

If you have any question please do well to comment.

Assignment:

Write just one program that requires you to make use of a shorthand, increment or decrement operator.
Post your problem topic on the comment section for us all to see.

Peace!!

No comments:

Post a Comment