what will be the output of the following code
int k=5,j=9
k+=k++-++j+k;
system.out.println("k="+k);
Answers
QUESTION:-
➣
What will be the Output:-
ANSWER:-
➣
Output:- 6
WORKING:-
➣
Given:-
➣ int k = 5 and j = 9
Method:-
➣ 5 = 5 - 10 + 6
➣ 5 + 5 - 10 + 6
➣ 10 - 10 +6
➣ 6
_________________________________________
Explanation:-
➣
Let's understand the Concept of above Output:-
Case 1:
➣ When the sign of increment (++) is present before any variable the default value increases by 1 and the increased value becomes the Default Value then the Value is printed.
➣ This is called Pre-increment
• For eg:-
➣ ++ a [int a = 5]
In this case the default value of a will 1st increase and replace the default value and at last print the Incremented value.
Output:- a = 6
Default value:- a = 6
Case 2:
➣ When the sign of increment (++) is present after any variable the default value is 1st Printed then the increased value increases by 1 and the increased value becomes the Default Value.
➣This is called Post-increment
• For eg:-
➣ a++[int a = 5]
In this case the default value of a will be printed then its value will increase by 1.
Output:- a = 5
Default value:- a = 6
_________________________________________
• We can Simply understand this Concept like this:-
• In Pre-increment(++a) the default value stored in a 1st increases by 1 and then the value is Printed or this changed value is used further in a function if the the variable repeats itself.
Also after Printing the value the Incremented value becomes the Default Value for a.
• In Post-increment(a++) the default value stored in a 1st is printed and then increases by 1 and the increased value is implemented further in expression if a is present one more time.
➣ ++a = Add before
➣ a++ = Add after
Answer:
k = 6
Explanation:
k = 5+(5-10+6)=5+1=6