if-else (Decision Making)
if block तभी चलता है जब condition true हो। अगर false हो, तो else block चलता है।
तुम कई conditions भी लगा सकते हो else if से — जैसे एक के बाद एक gate check करना।
int marks = 85;
if (marks >= 90) {
System.out.println("A grade");
} else if (marks >= 60) {
System.out.println("B grade");
} else {
System.out.println("Keep trying!");
}- if चलता है जब condition true हो
- else चलता है जब false हो
- else if से multiple checks
if-else के अंदर और if-else लिखना "nesting" कहलाता है — जब दो या ज़्यादा independent conditions check करनी हों, एक दूसरे के अंदर। हर nested level अपनी ख़ुद की true/false decision लेता है, जो outer condition पर depend कर सकती है।
बहुत ज़्यादा nesting (3-4 level से ज़्यादा) code को पढ़ना मुश्किल बनाती है — इसे "arrow code" या "pyramid of doom" भी कहते हैं (indentation एक pyramid जैसी बनती है)। इससे बचने के लिए "early return" pattern use करो — जल्दी return/continue कर दो जब condition match ना करे, ताकि main logic flat रहे।
if (age >= 18) {
if (hasID) {
System.out.println("Entry allowed");
} else {
System.out.println("ID chahiye");
}
} else {
System.out.println("Underage");
}Simple if-else जो सिर्फ़ एक value assign कर रहा है, उसे ternary operator से एक line में लिखा जा सकता है — code छोटा और कभी-कभी ज़्यादा readable हो जाता है। लेकिन ternary को chain (nested ternary) करना — जैसे a ? b : c ? d : e — बहुत confusing हो जाता है और normally avoid करना चाहिए, चाहे short लगता हो।
Rule of thumb: ternary तब use करो जब तुम सिर्फ़ "ये value या वो value" decide कर रहे हो। अगर action (print, method call, multiple statements) करना है, normal if-else better है।
String result = (marks >= 40) ? "Pass" : "Fail";
// Avoid: nested ternary jaise ye padhna mushkil hai:
// String grade = (m>=90) ? "A" : (m>=75) ? "B" : (m>=60) ? "C" : "F";सबसे common ग़लती: == की जगह = लिख देना (assignment vs comparison)। अच्छी बात ये है कि Java में if(x = 5) जैसा code compile ही नहीं होगा (क्योंकि = एक int return करता है, boolean नहीं) — ये C/C++ के silent bug से बहुत better है जहाँ ऐसा code चुप-चाप चल जाता है।
दूसरी ग़लती: "dangling else" confusion — else हमेशा सबसे नज़दीकी (most recent) if से जुड़ा होता है, चाहे indentation कुछ भी दिखाए। इसलिए braces {} use करना हमेशा safe है चाहे एक ही statement हो — indentation compiler के लिए कुछ मतलब नहीं रखती, सिर्फ़ इंसान के पढ़ने के लिए है।
तीसरी ग़लती: String को == से compare करना (if (name == "Aarav")) — ये reference compare करता है, content नहीं। Strings के लिए हमेशा .equals() use करो।