Java में Increment और Decrement
In this page:
variable++; // or ++variable
variable--; // or --variable
Post-Increment Operator
int y = x++; में, y को increment से पहले x की value मिलती है, और सिर्फ बाद में x की अपनी stored value एक से बढ़ती है -- post-increment में post यह refer करता है कि increase कब effect में आता है read के सापेक्ष।
उदाहरण: Post-Increment Operator
public class Main {
public static void main(String[] args) {
int x = 5;
int y = x++; // y gets 5 (old value), x becomes 6 afterward
System.out.println(y + " " + x);
}
}
Login to try C/C++/Java/PHP code in the editor
Pre-Increment Operator
int y = ++x; में, x पहले increment होता है, और वह पहले से updated value ही y को assign होती है -- इसलिए pre-increment और post-increment x के लिए वही end state produce करते हैं, लेकिन y के लिए अलग values।
उदाहरण: Pre-Increment Operator
public class Main {
public static void main(String[] args) {
int x = 5;
int y = ++x; // x becomes 6 first, y gets the already-updated 6
System.out.println(y + " " + x);
}
}
Login to try C/C++/Java/PHP code in the editor
Post-Decrement Operator
Post-decrement (x--) post-increment को mirror करता है: expression x की current value तक evaluate होता है, और वह value उपयोग होने के तुरंत बाद असली decrease by one होता है।
उदाहरण: Post-Decrement Operator
public class Main {
public static void main(String[] args) {
int x = 5;
int y = x--; // y gets 5, then x decreases to 4 afterward
System.out.println(y + " " + x);
}
}
Login to try C/C++/Java/PHP code in the editor
Pre-Decrement Operator
Pre-decrement (--x) पहले x से एक subtract करता है, फिर surrounding expression वह पहले से कम हुई value देखता और उपयोग करता है।
उदाहरण: Pre-Decrement Operator
public class Main {
public static void main(String[] args) {
int x = 5;
int y = --x; // x drops to 4 first, y gets that already-lowered value
System.out.println(y + " " + x);
}
}
Login to try C/C++/Java/PHP code in the editor
Mixed Expressions
एक complex expression के अंदर कई ++ और -- operators mix करना (जैसे a[i++] = b[--j]) काम करता है, लेकिन यह evaluation order को एक नज़र में trace करना कहीं ज़्यादा मुश्किल भी बनाता है -- ज़्यादातर style guides इन्हें अलग lines में split करने की सिफारिश करते हैं।
उदाहरण: Mixed Expressions
public class Main {
public static void main(String[] args) {
int[] a = {10, 20, 30};
int i = 0, j = 2;
a[i++] = a[--j]; // hard to trace at a glance - most style guides avoid this
System.out.println(a[0] + " " + i + " " + j);
}
}
Login to try C/C++/Java/PHP code in the editor
i = i++लिखना, जोiको unchanged छोड़ता है क्योंकि पुरानी value वापस assign होती है।i++(use then add) को++i(add then use) के साथ एक expression के अंदर confuse करना।- उसी variable पर एक single expression में दोनों increments उपयोग करना, जो पढ़ना और predict करना मुश्किल है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: