Tutorial

How To Write Conditional Statements in Java

Published on November 29, 2022
How To Write Conditional Statements in Java

The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

Introduction

Conditional statements change the program flow. Conditional statements are also called branching statements because when a condition is matched, the flow goes one way into one branch of the code. If a condition is not met, another condition is evaluated (if there is one). This evaluation continues until either all conditions are evaluated to true or false. For example, you could compare two numbers (x and y) with the following conditional statements: x > y, x = y, and x < y. If x equals 1 and y equals 2, there will be three evaluations until the final x < y conditional statement evaluates to true.

There are two types of conditionals. The first type is if and its extended else if variations. This type is widely used. The second type is switch, which is more specific and limited.

In this tutorial, you will write conditional statements in Java and learn about each type’s use cases, benefits, and drawbacks.

Prerequisites

To follow this tutorial, you will need:

Differentiating Between Statements and Blocks

When a conditional statement is met and the execution flow is directed to a corresponding branch of code, this branch could be either a single statement or a block of code. Statements and blocks of code are processed differently, so it’s important to differentiate between them.

A statement is a single unit of execution, usually on one line, terminated with a semicolon. For example, use the following statement to print example:

  1. System.out.println("example");

Info: To follow along with the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and pressing ENTER. To exit jshell, type /exit.

This statement uses the method println() to print a string, which in this case is example. Unless otherwise instructed, Java will execute this statement unconditionally.

Note: Statements are usually written on one line to make them more readable. However, according to the official convention guidelines, you should avoid lines longer than 80 characters. If your statement exceeds 80 characters, you should spread it over multiple lines.

Furthermore, in some cases, such as with lambdas, it’s more convenient and intuitive to spread the statements over a few lines. In any case, Java doesn’t impose syntax requirements about new lines in a statement, and you can just continue the statement on a new line. As an exercise, try rewriting some of the examples in this tutorial and separate the statements on multiple lines.

When you group statements so that they are executed together, you are using a block. A block is a group of zero or more statements that starts with an opening bracket ({) and ends with a closing one (}). You can rewrite the previous code and place it inside a block like this:

  1. {
  2. System.out.println("example");
  3. }

In the block above, you have used four spaces before System.out.println("example");. These four spaces are called indentation. In contrast to other programming languages such as Python, indentation in Java is not required and does not affect the code. However, for better readability, and by convention, the lines inside a block start with an indentation of four spaces. Most code editors support automatic indentation, but the convention is different across programming languages and even among editors. Thus, if your code editor supports indentation, ensure it is set to four spaces when writing Java code. Jshell, which is recommended and used in this tutorial, automatically sets four spaces as the indentation.

In this case, placing the code inside a block makes no difference because there are no conditions. Thus, example will be printed regardless of whether the statement is inside a block. When you run the two previous examples in jshell, you will receive the same output in both cases:

Output
example

The above output shows that the statement for printing example works the same way from within a block as outside of it.

In this section, you learned about statements, blocks, and how to create them. In the next section, you will add a conditional statement to a block of code. Thus, the statements inside the block will be executed together and conditionally.

Using Single If Conditionals

The most commonly used conditional statement is the if statement. It is universal and fits every need for conditional comparison, as long as the result of the comparison is a boolean (true or false). The if conditional can be a single conditional in its simplest form or have a more complex structure, which you will use in later sections.

The single if statement is used to execute a piece of code under a single condition. You will put the conditionally executed code inside a block and put if (boolean expression) at the beginning. If the expression, and thus the condition, is true, only then will the code block be executed. If the expression evaluates to false, the conditional block code will be skipped.

In this example, you will write a code snippet that compares two numbers. Depending on the result of the comparison, a message might be printed. Add the following lines to jshell:

  1. int x = 1;
  2. int y = 0;
  3. if (x > y) {
  4. System.out.println(x + " is bigger than " + y);
  5. }

You define two variables in the first two lines: x and y. The third line is the conditional if (x > y), which compares whether x is bigger than y. The comparison is always inside parentheses.

The block code starts with the first opening bracket ({) and ends with the closing bracket (}). Inside the block, a statement uses the println() method to print that x is bigger than y. The block code will be executed only if this condition is true.

When you run this code in jshell, you will get the following output:

Output
x ==> 1 y ==> 0 1 is bigger than 0

The first two lines of the output confirm the values of x and y. Line 3 reads 1 is bigger than 0, which means that the conditional statement is true: x is bigger than y. If you change x to be smaller than y, the message will not be printed.

The most important rule in conditional statements is that the evaluated expression must evaluate to a boolean. In any other case, you will get an error that what you are comparing cannot be converted to a boolean.

For additional practice, try to cause an error with a non-boolean expression. To do this, place an int variable, which cannot be converted to a boolean, inside the conditional parentheses like this:

  1. int x = 1;
  2. if (x) {
  3. System.out.println("Will this work?");
  4. }

In line 1, you define an int variable x and assign it a value (1). Line 2 is the condition if (x), which will crash the program because x cannot be converted to a boolean. When you run the above code in jshell, you will get the following error:

Output
x ==> 1 | Error: | incompatible types: int cannot be converted to boolean | if (x) { | ^

The first line confirms that x has received the value 1. The next lines describe the error about incompatible types and explain that an int value such as x cannot be converted to a boolean value. Whenever you get such an error, you will know to double-check your comparison.

A non-boolean conditional statement like this one is probably the most common pitfall with conditionals. Luckily, modern IDEs (Integration Development Environments) catch such errors as you write. Still, even if you don’t use an IDE, the errors are straight-forward.

Writing Conditional If Statements Without a Block

One peculiarity of Java’s if conditionals is that there is a shorter way to write them without using a block of code. While using conditionals without a code block is not recommended, you should know that it is possible to write code like this. On the practical side, if you study for a Java exam or go to a job interview, you may encounter such confusing examples and should be prepared.

For example, instead of using a block of code, you could write a statement like this:

  1. int x = 1;
  2. int y = 0;
  3. if (x > y)
  4. System.out.println(x + " is bigger than " + y);

The difference from the previous example is that there is no block of code after the conditional statement if (x > y). Instead, the target statement System.out.println(x + " is bigger than " + y) comes immediately after the conditional statement if (x > y).

When you run this in jshell, you will get the same output as the previous example:

Output
x ==> 1 y ==> 0 1 is bigger than 0

The values of x and y will be printed on the first two lines. The confirmation message that 1 is bigger than 0 prints on line 3.

When there is no block code following a conditional, only the line immediately after the conditional depends on the conditional. In this case, any statements after line 4 will be executed regardless of the conditional. For example, try changing x to 0, so that it is not bigger than y, and add a fifth line like so:

  1. int x = 0;
  2. int y = 0;
  3. if (x > y)
  4. System.out.println(x + " is bigger than " + y);
  5. System.out.println("This line is always printed.");

When you run the above code in jshell, you will get the following output:

Output
x ==> 0 y ==> 0 This line is always printed.

The values of x and y are printed on lines 1 and 2. Both values are 0, which means they are equal. Because of this, the conditional statement x > y returns false. Thus, the fourth line saying x is bigger than y is not printed. However, line 5 is printed because its execution does not depend on the conditional.

Additionally, the indentation on line 5 is unnecessary. It was included to suggest that the execution of line 5 depends on the conditional, which is not the case. This indent could be omitted, but this would not make the code any clearer.

Using conditionals without a code block is not intuitive or easy to follow, which is why you should use shorthand syntax sparingly. To keep your code clean and understandable, it’s better to use block statements because they are more readable and allow you to have more than one line of conditionally executed code.

Nested if statements are another example of code that is possible to write but not usually recommended. In the next section, you’ll explore nested if statements to better understand their value and drawbacks.

Nesting If Statements

To create a more complex conditional structure, it is possible to combine many if statements. To create nesting if statements, you place another if statement inside a parent if statement instead of in a code block.

This practice is not usually recommended since it makes your code harder to read and understand. However, nested if statements do sometimes have a practical use, so it’s helpful to be familiar with them.

To understand how this is done, you’ll extend the previous example by adding one more if statement. You’ll compare y again to assess whether it is equal to 0. Add the following lines to jshell:

  1. int x = 1;
  2. int y = 0;
  3. if (x > y) {
  4. if (y == 0) {
  5. System.out.println("This is legal but does not look clean.");
  6. }
  7. }

The first three lines remain unchanged from the previous examples: you define two int variables (x and y) and compare them. On line 4, another if statement compares whether y is equal to 0. If true, Java will proceed with line 5, which has a println() statement with the message This is legal but does not look clean..

When you run this in jshell, you will get the following output:

Output
x ==> 1 y ==> 0 This is legal but does not look clean.

The first two lines confirm the values of x and y. Line 3 reads This is legal but does not look clean.. This message confirms that the block code has been executed because both if conditions are fulfilled: x > y and y == 0.

You can nest if statements like this indefinitely. However, with each nested if statement, you increase the complexity of the code and decrease its readability. That’s why nesting if statements is not generally considered good coding practice.

However, nested conditional structures do have some practical use. Sometimes, it may seem worthwhile to sacrifice the readability and increase the complexity in favor of writing shorter code and potentially saving time. As a result, you may encounter nested statements during exams, job interviews, or in real-world productive code.

Using Extended If Conditionals with Else If and Else Statements

if conditionals can be further extended to handle additional matching criteria using else if and else supplementary statements. The else statements can be used only after an initial if statement. With else if, you can add unlimited additional conditional statements, similar to the first if. With a final, optional else, you specify the default path that the program flow should follow in case no previous conditional statement has been matched.

With else if and else, you can branch your program flow in more directions than with the single if. Thus, you can build complex conditional structures that cannot be built in any other way. Branching the code in various directions allows you to handle more complex business cases. However, business requirements in production are numerous and the design flow is not necessarily straight-forward.

Start with the following code example to get the idea of else if and else statements. You will extend the previously used code and add more conditional branches. These new conditions will continue comparing x and y:

  1. int x = 1;
  2. int y = 0;
  3. if (x > y) {
  4. System.out.println(x + " is bigger than " + y);
  5. } else if (x < y) {
  6. System.out.println(y + " is bigger than " + x);
  7. } else if (x == y) {
  8. System.out.println(x + " is equal to " + y);
  9. } else {
  10. System.out.println(x + " cannot be compared to " + y);
  11. }

According to the code above, lines 1 and 2 define two variables (x and y) with the values 1 and 0. On lines 3 and 4, you evaluate whether x is bigger than y with an if statement. If the evaluation is true, the text x is bigger than y will be printed and the conditional structure will be exited. If the evaluation is false, the program will continue to the next conditional. So far, the code is the same as the previous examples.

On line 5, after the closing bracket of the if statement, comes an else if statement. It has a similar syntax to an if: there is a boolean expression inside parentheses and a following block of code. The expression evaluates whether y is bigger than x, which is the opposite of the previous if statement. If the expression is true, the block of code following it will be executed, and again the conditional structure will be exited. In this case, this is the statement on line 6, which will print y is bigger than x.

On line 7 is another else if case. This time, you check whether x is equal to y in the parentheses. If true, the statement on line 8 will be executed and it will print x is equal to y. Such else if statements can be added indefinitely, one after another and evaluating different conditions.

On line 9 comes the final else statement. It is always final and does not have a condition, which means its branch is always entered if no other conditional statement has been matched. In other words, the block of code after else is executed when no if or else if condition has been previously met. If this were true, the code on line 10 would be executed, printing that x cannot be compared to y.

Only the first if statement is required in such complex conditional structures. If you wish to make additional comparisons, you can have zero or more else if statements. In the end, you could place one optional else to match if no other conditionals have matched.

When you run the above code in jshell, you will get the following output:

Output
x ==> 1 y ==> 0 1 is bigger than 0

The first and the second lines from the above output confirm the values of x and y: 1 and 0. The third line prints 1 is bigger than 0, which confirms that the boolean expression (x > y) has returned true and the block code after it has been executed.

Writing if, else if, and else statements is a good way to write complex conditional structures because you can place different conditions in each if and else if statement. In the above example, you first compared x > y, then the opposite x < y and finally x == y. The code is still readable and manageable in cases with only a few comparisons.

However, if you need to make more comparisons, adding more else if statements will make the code hard to follow and even confusing. That’s why you should make your structures small and simple when possible. Furthermore, in some cases, there is an alternative to such complex structures using the switch statement, which you’ll use in the next section.

Using Switch Conditionals

The switch statement is another conditional statement you can use to build decision-making structures. It is similar to an if statement because it can be used to direct the program flow conditionally. However, the switch statement works with a single variable and matches it against different predefined cases. Thus, you cannot evaluate boolean expressions such as x > y. Instead, you can have, for example, an int variable and match its value against other int variables; when there is a match (that is, a case), the program flow will be redirected according to the match.

The switch conditionals have two important rules. The first is that the compared variable can be only of specific data types, such as the primitive types int and char, as well as the reference types String and Integer. (The full list of the supported data types can be found at the official switch documentation.) Thus, you cannot use boolean variables, which is why switch conditionals cannot replace if conditionals.

The other important rule is that the values for the case statements must be literals or constants. Constants resemble variables, but they have the keyword final in front when they are defined. In contrast to variables, you cannot change the value of a constant once it is defined. Constants will be covered in detail in future tutorials from our Java series.

The switch is more limited than the if structure, and it’s not a complete replacement for it. Still, it has the unique advantage of being more readable and better suited for a larger number of comparisons when feasible.

For example, imagine that you want to match the numerical representation of each month (1 through 12) with the month’s name. With an if - else if structure, you would have to make twelve comparisons that are similar. But with switch, you can do this much more neatly without repeating code.

To practice using the syntax of the switch conditional with this example about months, add the following lines to jshell. There is an int variable numerically representing the month of the year and a case for the name of each month:

  1. int monthOfYear = 1;
  2. switch (monthOfYear) {
  3. case 1:
  4. System.out.println("January");
  5. break;
  6. case 2:
  7. System.out.println("February");
  8. break;
  9. default:
  10. System.out.println("Not a month");
  11. }

On line 1, there is a variable monthOfYear with the value 1. This variable will be used for the switch statement. On line 2 comes the switch statement definition. The variable monthOfYear is placed inside the parentheses to show that it will be compared. After that begins the block of code inside which the different case conditionals are described.

On line 3 comes the first case with value 1. The first comparison will be whether monthOfYear equals 1. A colon (:) always follows the compared value. On line 4 comes the println() method to print that in case 1 is matched, it should print January as the month’s name. This line could be zero or more statements on zero or more lines — that is, it could be skipped.

After the first case comes a break statement on line 5, which causes the switch conditional structure to be exited when the condition is met. Thus, once the break is executed, no other case conditionals will be evaluated. Instead, the program flow will continue after the closing bracket of the switch conditional, which is on line 11 in this example. Note that the break is optional, and you may forget to include it. In that case, the switch will continue evaluating the remaining cases instead of breaking out of the conditional structure when there is a match. This may lead to unexpected output and problems that are hard to debug.

The next case conditional is on lines 6, 7, and 8, which will match whether the monthOfYear value is 2. These three lines follow the same syntax as the previous three but with a new string for "February" in line 7. For brevity, the case conditionals for the remaining ten months have been omitted. Otherwise, they would also follow this structure with new strings for each named month.

On line 9 is a default statement. It has no conditions, and thus it is always matched. It is optional and used to define the default path for the program flow when no previously listed case is matched. It is similar to the else statement in the if conditionals.

On line 11 there is the closing bracket to terminate the block of code for the conditional statements.

To execute the above code, paste it in jshell. You will receive the following output:

Output
monthOfYear ==> 1 January

The first line confirms that the value of monthOfYear is 1. The second line prints January, which means that the case conditional for the value 1 has been matched: the monthOfYear is 1, which triggers the statement on the next line to print January.

As an exercise, try changing the value of monthOfYear, adding more case conditionals, and even removing the break statements to understand how the result will change.

Conclusion

In this tutorial, you used conditional statements to direct the execution flow. You learned when it is suitable to use if and switch statements and wrote a few code examples with them. You also learned best practices for clean code and how to avoid common pitfalls related to conditionals.

For more on Java, check out our How To Code in Java series.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: How To Code in Java

Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

About the authors
Default avatar
Toli

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.