I want to calculate in NumeicVariable class and show the result in Main class but my code doesn't work correctly.
Main class is:
package com.sajjad.java;
public class Main {
public static void main(String[] args) {
int value = 20;
System.out.println(NumericVariables.drawOne(value)); //
System.out.println(NumericVariables.addOne(value)); //
}
}
and NumericValues is:
package com.sajjad.java;
import com.sun.org.apache.xpath.internal.SourceTree;
public class NumericVariables {
public static int addOne(int number){
return number++;
}
public static int drawOne(int number) {
return number--;
}
}
Notice: result is 20
You use post increment and decrement operator :
return number++;
return number--;
For example here :
public static int addOne(int number) {
return ++number;
}
The value number is incremented but only as soon as the next statement.
So as you return, the same value as the parameter is returned.
It is the same thing here :
public static int drawOne(int number) {
return number--;
}
number
will never be decremented as the number is returned in the same statement that the decrementation.
You have several workarounds :
Make things in 2 times :
public static int addOne(int number) {
number++; // post increment
return number; // value incremented here
}
Use pre increment operator :
public static int addOne(int number) {
return ++number; // incremented right now
}
Or more simply increment with 1 :
public static int addOne(int number) {
return number+1; // incremented right now
}
It is exactly the same logic for the decrement operator.