What is the Difference Between Prefix and Postfix Operators in Java

When I was learning Java at my school.I was taught about flowchart and pseudocode before I entered the syntax of java language itself.I knew Java at my school when my teacher taught me about algorithm.If you don't understand java,which is programming language,you can learn more here.I'm really exiceted to learn it because it is cross platform and high level programming.

Today I want to share about syntax java that sometimes makes people confused.First you have to understand what is increment(++) and decrement(--).Usually you see increment in operator looping for.like this example
for(int i = 0; 10 > i; i++) {}

i++ is a postfix increment that will add +1 if the condition is true (10 > i).So first check the condition then increment +1.If the condition is false then the looping will be stopped.This is the basic to understand postfix and prefix.Otherwise if you use decrement then the value will be decreased.It's totally easy to be figured it out.

First I will explain postfix then prefix.Don't be confused now because it is so easy to be understood.I will make it as easy as possible with a simple example code.
Look this program :
public class Postfix
    public static void main(String[] args)
        int i = 0; // initialize variable integer i to zero
        if(i++ == 0)
           System.out.println("It's correct + " + i );

if you run this program that condition of if syntax(i++ == 0) it will be true why ? because you use postfix increment in the condition.So we conclude that postfix will add +1 after condition check.

otherwise prefix will add +1 before condition check.try to code this simple example code
public class Prefix
    public static void main(String[] args)
        int i = 0;
        if(++i == 0) {}
           System.out.println("It's correct + " + i );
You can see clearly that prefix increment in the above code.The condition will be false then printing "it's correct 1".

Try this one as a practice :
what is difference between them ?
System.out.println("it's correct + " + ++i );


System.out.println("it's correct + " + i++ );

You can see now the difference both of them.If you have any question just asking here in this blog.
Learning programming is fun.

Popular posts from this blog

How to get thumbnail from video URL in Swift 5

Missing system image Android Studio solution

How to customize your date according to Timezone in Swift 5