In: Computer Science
Consider this code: "int v = 20; --v; System.out.println(v++);".
What value is printed, what value is v left with?
20 is printed, v ends up with 19
19 is printed, v ends up with 20
20 is printed, v ends up with 20
19 is printed, v ends up with 19
cannot determine what is printed, v ends up with 20
*************Summary***************
The answer for above question is given below and also the explanation.....
I have also provided a program with output for reference...showing the correct answer as output..
I hope it works for you :) !!!!!!!!!!!!!!!!!!!
**************Answer****************
The answer for above question is 19 is printed, v ends up with 20 ....
************Explanation**************
1. int v=20;
v is intialized to 20 so value of v=20
2. --v;
as the - - signs are before v...so it pre decrement operation...that means the value is decremented first and then rest of the statement is executed...so the value of v will be 19...v=19
3. System.out.println(v++);
as the ++ signs are after variable v..so it is post increment operation......that means first the statement is executed with current value of v ....and then the it increments the value of v....
1. so when executing system.out.println(v++) ..it uses the current value of v i.e v=19..so it prints 19 ........
2. And when statement has done executing ..then it increments the value of v ...so the latest value of v becomes 20.....
So from 1 and 2
19 is printed because it executes statement first with current value of v
and v ends up with 20 because it increments value of v after execution of that statement
*****************Program*******************
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int v=20; //inutializing v to 20
--v; //pre decrementing value of v...v will be 19
System.out.println(v++);
//as there is post increment operator (++ operator after variable v).
//..so it will print current value of v i.e. 19 using the system.out.println
//and then after the printing of value of v
//it will increment value of v ..so value of will be 20 after execution
//to check the value with which v ends up
System.out.println("V ends up to with "+v);
}
}
*****************Output*********************