Java if Statement: if else, correct indentation, ternary operator, nested if

What are Instructions and flow control:

Java if Statement: if-else, correct indentation, ternary operator, nested if:- As the last basic elements of the language Java we learn in the following sections know commands that influence the flow of our program, i.e. determine whether and in what order certain instructions of our program. In this context, the concept of a block in Java explained. The following sections explain the basic instructions and commands for sequence control, ordered according to their mode of operation.

Attention: In addition to the commands for the sequence control presented here, another group of such commands is used in connection with exceptions in Java. This group contains the try-catch-finally and throw.

What are the instructions?

We already learned some simple instructions:

  • the declarative statement, with the help of which we agree on variables;
  • assignments that we use to assign variables values;
  • Method calls, which we use, for example, to send input or output statements

The last two statements belong to the group of expression statements. The name is based on the fact that in an expression statement an expression (an assignment expression, a prefix, or postfix operation with ++ or — or a method call) by attaching a semicolon to a statement.

In addition, there is the so-called empty statement, which is simply extracted from a semicolon and in fact also in some places (where syntactically an instruction is required, but we do not want to execute any instruction) can be used.

Blocks and their structure

In the Java programming language, a block designates a sequence of statements. which are enclosed by { and }. Such a block can where a single statement is allowed because a block is basically a statement, which is a compound statement. This also makes it possible to box blinds.

The following program section contains, for example, a large (“outer”) Block in which two (inner) blocks are nested.

It should be noted that the variables we declare in our program are only valid until the end of the block in which they were defined. In this context, the scope of the variables is also referred to. For example, we can reference the variable y in the above example program, no longer accessible in the outer block and in the second inner block because these with the closing curly bracket after the empty statement hers Has lost its validity. One could also say that the variable y is only within of the first inner block are valid.

Java if statement:

Probably the most fundamental decision-making statement in many programming languages represents the so-called java if statement. The syntax of this instruction generally looks like this in Java.

Example: how to check whether age is greater or not using simple java if statement :


If else statement:

First evaluates the expression whose result type must be boolean (it is a logical expression, such as a comparison). Is the result true, the immediately following statement is executed if it is false, the statement after else is executed. After that, at the next statement. However, one of the executes both statements – the java if statement and the statement after else, i.e. never both in one pass of the if-else statement come out.

You do not want to execute any instructions when the expression returns the result false, you can omit the else part completely. It should be noted that the two instructions naturally also replaced by the block are possible if one executes several instructions from the result of the logical expression. Syntactically, this could be quite general So look like this.

Here too, the following applies: You do not want to execute any instructions when the expression returns false, so you can omit the else part completely.

Attention: Which instructions belong to which block is exclusively is defined by the curly brackets. If the instructions in the if or not clamped in the else part, then naturally only the first statement in this part, no matter how the following instructions are copied. In the program section

if the instructions in lines 6 and 7 no longer belong to the else part and are is therefore definitely executed, no matter which value f ¨ is read in for x. It is therefore advisable to always put if and else parts in parentheses, also if they consist of a single statement. That’s the only way you can see immediately. which instructions belong to these parts and which do not. You do not know also use an editor that is self-sufficient for the correct insertion No. Tools with this function, called the Code Formatter or Beautifier, are nowadays built directly into many programs and partially on the Internet even as freeware or open-source.

In the simplest case, a java if statement looks like this:

You can also use Boolean operators to do much more complex Formulate conditions. If more when the condition is true should be executed as a command, the commands in curly brackets are placed. else directs a second block of code one that is executed if the condition was not met.

In contrast to some other programming languages, Java knows none’s own elseif keyword. Rather, there are multi-level branches formed by a combination of else and if (i.e., the second if forms the first else block).

All Java control structures, i.e. if, switch, for, do etc., can be nested will. Refers to several nested if-constructions else always to the last, innermost if!

If you want a different logic you have to go through the if structure Define curved brackets exactly:

It is common to use the following if(condition) to place code in curved brackets, but it is not mandatory. If you do not use the { and } brackets, it has a very simple Consequence: Only the immediately the following statement, as specified by if(…) and ending with the next semicolon is from the if condition. The additional code is always executed, regardless of whether the if-condition was met or not. Often, initially, only a single statement from if is dependent, and therefore the brackets are really dispensed with. In the following example, b should be assigned the value 5 if a contains the value 3:

So far, so simple. But then a second instruction comes in. the danger is great, now to overlook the brackets. The code in the following Example is intentionally incorrectly indented to correct the mental error illustrate:

What happens when the above code is executed? No matter if a 3 or not – b is definitely set to 5! From the if condition depends only on the next statement, here the println Call. Indented correctly, the code looks like this:

The intention was to use this code, now with the correctly placed curved brackets:

Nevertheless, you will see in this article many listings in which if or for constructions with only one statement without curved brackets. The reason: The code is then simple better readable.

Example: how to find odd and even number using java if-else statement :


Example: how to find whether the year is a leap or not using java if statement:

Imagine developing a program that determines whether a year is a leap year or not.

Years divisible by four without remainder usually leap years.

Years divisible by 100 without a remainder are not leaped years.

400 years that can be divided without remainder are leap years.

In our Java program, the year is in the variable year. Now it’s about making the above sentences for Java understandable if statements. There are many solutions to this problem, but the easiest is to order the rules easily and start with the most effective rule. The resulting solution then looks like this:


java if statement

So first two variables are defined in the code, one int variable for the year and a boolean variable for the result. The test of whether a year is divisible without a remainder is done with the remainder operator%. The eight curly brackets in the if-else construction are all optional, d. that is, the code would work without them. When evaluating the results, I used the curly brackets waived. Instead of if (leapyear == true), and even simpler if (leap year) works. if then simply evaluates the content of the leap year variable out.

Clear logic through correct indentation java:

Java understands your Code even if you don’t indent anything – the only question is whether you can do it yourself understand. To put it brutally: As long as you don’t indent the code correctly you don’t understand him (completely) either. As long as you are consistently curving for each Java language construct Using parentheses (which I highly recommend!) Is the indentation logic actually very simple: with every open {bracket you move one level further. Of course, the first instruction should also be indented after if, for, etc., which is formulated without curly brackets. Moreover, because if, for can be nested as desired and Java statements may well be allowed to extend over several lines, there is a certain amount of Complexity.

the ternary operator in java:

Often, if constructions are only required to be Condition to calculate the one and the other expression. For such cases, Java provides a shorthand with the so-called ternary operator. Its syntax is condition ? expression1 : expression2. If the condition returns true, the first expression, otherwise the second:

The second example shows the evaluation of a variable with the number of the day of the week, where the numbers 1 to 7 are the days Sunday to Saturday, and Println shall indicate whether it is a working day or whether the weekend is:

Example: how to find even and odd number using the ternary operator in java:


nested if statement:

We have already mentioned that the instructions in each part of choosing an instruction could be absolutely any. They can in particular contain their turn to other java if statements. Given the two possible forms of the java if statement (with or without else), there are certain situations where ambiguity arises. This is the case in this example:

Is it interpreted as suggested by this presentation?

The first interpretation would lead to display “unordered” when the condition a <= b is false, while the second would display nothing. The rule adopted by Java to remove such ambiguity is as follows: An else always refers to the last if encountered to which an else has not yet been assigned. In our example, it is the second presentation that best suggests what is happening. Here is an example of using nested ifs. This is a billing program with a discount. It reads in data a simple price excluding tax and calculates the corresponding price including tax (with a constant rate of 18.6%). He then establishes a discount, the rate of which depends on the value thus obtained, namely:

  • 0% for an amount of less than 1000,
  • 1% for an amount greater than or equal to 1000  and less than 2000
  • 3% for an amount greater than or equal to 2,000  and less than 5,000
  • 5% for an amount greater than or equal to 5,000.

This program is accompanied by two examples of execution.

java if statement

Related Article:

Operators in java: Arithmetic, Bit, Assignment, Comparison, Logical And Operators Priority

Input and Output Data in java With Examples


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button