+ 1

novice Java question (increment and decrement basics)

I would like to make my own example of using increment and decrement operators. However, my code will not work. I get an error on line six. I would appreciate any help in this code. public class IncrementDecrementExample { public static void main(String[] args) { final double PI = 3.14; int i = 2++; double j = i + PI; System.out.println( "The a solution is " + j ); } }

25th May 2019, 5:44 PM
Markie Alicia
Markie Alicia - avatar
5 Answers
+ 5
What do you intend to do with the variable i? int i = 2++ is a wrong syntax. To set i to 2, use int i = 2; To set i to 1 then increment i by one Use int i=1; i++;
25th May 2019, 5:50 PM
Calviղ - avatar
+ 21
The increment and decrement operators (++, --) increment and decrement numeric types by 1. The operator can either precede or follow the variable, depending on whether you want the variable to be updated 'before' or 'after' the expression is evaluated. • The prefix: increments the value of x, and then assigns it to y.     int x = 5;     int y = ++x;  // x is 6, y is 6 • The postfix: assigns the value of x to y, and then increments x.     int x = 5;      int y = x++;  // x is 6, y is 5 • https://code.sololearn.com/chPAcDs7YZgV/?ref=apphttps://code.sololearn.com/cm4wSfJZ8h28/?ref=app ➝ Remember to use  🔍SEARCH. . .  bar to avoid from posting duplicate threads! • https://code.sololearn.com/W26q4WtwSP8W/?ref=apphttps://code.sololearn.com/WvG0MJq2dQ6y/
25th May 2019, 7:46 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 18
The difference between x++ and ++x  • The prefix increment returns the value of a variable after it has been incremented. • On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.    prefix:   ++x;    postfix: x++; To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first 'then' return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first 'then' increment (++) it after, thus x++. ⇨ Things to Remember: The prefix and postfix increment both increase the value of a number by 1. The only difference between the two is their return value. The former increments (++) first, then returns the value of x, thus ++x. The latter returns the value of x first, then increments (++), thus x++. • https://www.sololearn.com/learn/Java/2141/
25th May 2019, 8:21 PM
Danijel Ivanović
Danijel Ivanović - avatar
25th May 2019, 10:05 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 5
2 is not a variable so you cannot do: 2++
25th May 2019, 7:10 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar