Java Conditions and If Statements
Java Conditions and If Statements
In Java programming, conditions and if statements are used to control the flow of a program based on certain conditions. These constructs allow you to execute different parts of your code depending on whether a given condition is true or false.
If Statement:
The basic structure of an `if` statement in Java is as follows:
if (condition) {
// Code to be executed if the condition is true
}
Here, `condition` is a boolean expression that is evaluated. If the condition is true, the code block enclosed within the curly braces `{}` is executed; otherwise, it's skipped.
Example:
int num = 10;
if (num > 5) {
System.out.println("The number is greater than 5.");
}
In this example, since the condition `num > 5` is true (`10` is indeed greater than `5`), the code within the `if` block is executed and "The number is greater than 5." is printed.
If-Else Statement:
The `if-else` statement allows you to provide an alternative code block that is executed when the condition is false:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example:
int age = 17;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
In this example, if the `age` is greater than or equal to `18`, the first message is printed. Otherwise, the second message is printed.
If-Else If-Else Statement:
You can also use `else if` clauses to check multiple conditions in sequence:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}
Example:
int score = 75;
if (score >= 90) {
System.out.println("You got an A.");
} else if (score >= 80) {
System.out.println("You got a B.");
} else if (score >= 70) {
System.out.println("You got a C.");
} else {
System.out.println("You need to improve your grade.");
}
Here, the appropriate message is printed based on the `score` value.
Java's conditional statements provide a way to make your programs more dynamic by allowing different paths of execution based on specific conditions.
हिंदी:
जावा प्रोग्रामिंग में, कंडीशन्स और इफ स्टेटमेंट्स का उपयोग किसी विशिष्ट स्थिति पर आधारित प्रोग्राम के नियंत्रण में करने के लिए किया जाता है। ये निर्माण आपको आपके कोड के विभिन्न हिस्सों को नियंत्रित करने की अनुमति देते हैं आपके पास किसी शर्त के सत्य या असत्य होने पर विभिन्न हिस्सों को निष्पादित करने की।
इफ स्टेटमेंट:
जावा में `इफ` स्टेटमेंट का मूल ढांचा निम्नलिखित है:

Post a Comment