Of course it's nested. Nesting has nothing to do with the way you format the code.

if (...)
{
    // some code
}
else if (...)
{
    // some code
}
else
{
    // some code
}

is exactly equivalent to

if (...)
{
    // some code
}
else
{
    if (...)
    {
        // some code
    }
    else
    {
        // some code
    }
}

There's no 'else if' keyword in Java, the effect is achieved purely by a formatting convention which stops long chains of nested elses from drifting right across the screen.

In case anybody needs persuading, here is the specification for an if statement: Java Language Specification section 14.9

Answer from JeremyP on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_conditions_nested.asp
Java Nested If Statements
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... You can also place an if statement inside another if. This is called a nested if statement.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ nested_if_statements_in_java.htm
Java - nested if statement
In this example, we're showing use of nested if statement within an if statement. We've initialized two variables x and y to 30 and 20 respectively. Then we're checking value of x with 30 using if statement.
Discussions

In Java, is this considered an example of a "nested IF statement"? - Stack Overflow
Here we have a long-standing assumption that needs to be cleared up in my head. Is the following an example of nesting 'if' statements: if (...) ...; else if (...) ...; I was under the impress... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Avoiding nested if statements - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I currently have the following code. I am using nested if statements to return different errors based on different cases More on stackoverflow.com
๐ŸŒ stackoverflow.com
What's the difference between nested if statements & else if statements?
A nested if only runs if the first if is true, an else if runs if the first if is false. More on reddit.com
๐ŸŒ r/learnprogramming
15
1
July 14, 2025
Can someone please explain to me why the nested-if statement is not printing the statements correctly?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
9
5
July 4, 2021
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ nested-if-in-java
Java Nested if - GeeksforGeeks
July 23, 2025 - Nested if condition comes under decision-making statement in Java, enabling multiple branches of execution. ... Normal if condition checks condition independently which means each condition works on its own. Whereas nested if checks conditions that depend on each other, which means one condition is only checked if another condition is true. Example 1: The below Java program demonstrates the use of nested if statements to check multiple conditions and execute a block of code when both conditions are true.
๐ŸŒ
Coders Campus
coderscampus.com โ€บ home โ€บ nested if statements
Nested IF statements - Coders Campus
April 27, 2021 - So, as predictable as the sun will rise and set, Java will follow the same set of rules for this new if..else block. We will now evaluate if age is less than 65. And as luck would have it, our variable is set to 29. So, yes, 29 is less than 65, so we'll execute the code inside of this block and the console will output โ€œYou are an adult.โ€ ยท You have to consider the fact that you are now inside of nested if statements and make note of where the beginning and end of all of those curly braces {} are.
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ java
Nested if-else statement in Java (with examples)
October 18, 2022 - public class codedamn { public static void main(String[] args) { int a=10; if(a%5==0) { //Divisible by 5 System.out.println("Divisibe by 5"); } else { //Not divisible by 5 System.out.println("Not dividible by 5"); } } } Code language: Java (java) ... In the above example, if the if-condition is satisfied, the statement inside it is executed otherwise it moves to the else part...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ what is nested if statement in java?
What is Nested if Statement in Java? - Scaler Topics
September 16, 2022 - Therefore, we use the nested if ... condition. An example of a nested if statement could be a person should be qualified as well as an adult to be hired in a company....
Find elsewhere
๐ŸŒ
Vaia
vaia.com โ€บ java nested if
Java Nested If: Statements, Syntax & Examples | Vaia
The nested if statement in Java is when an 'if' statement is placed inside another 'if' statement, allowing conditions to be checked in sequence. Here is a simple example to illustrate how a nested if statement works in Java:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ decision-making-javaif-else-switch-break-continue-jump
Decision Making in Java - Conditional Statements - GeeksforGeeks
The below diagram demonstrates the flow chart of an "nested-if Statement execution flow" in programming. ... The if-else-if ladder allows multiple independent conditions to be checked in order. As soon as one condition is true, its block executes, and the rest are skipped. ... import java.util.*; class Geeks { public static void main(String args[]) { int i = 20; if (i == 10) System.out.println("i is 10"); else if (i == 15) System.out.println("i is 15"); else if (i == 20) System.out.println("i is 20"); else System.out.println("i is not present"); } }
Published ย  October 6, 2025
๐ŸŒ
PW Skills
pwskills.com โ€บ blog โ€บ java developer โ€บ java nested if statements
Java Nested If Statements
2 weeks ago - Inner If: Now that itโ€™s inside, it checks if score > 70. Since 85 is greater than 70, it prints โ€œAdmission Granted!โ€. Alternative: If the age was 16, the program would have jumped straight to the final else, ignoring the score check entirely. It is common for beginners to confuse java multiple if statements with nested ones.
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ java tutorial โ€บ nested if statements in java
Nested if Statements in Java | Guide to Nested if Statements in Java
March 27, 2023 - Nested if Statement is one of the decisions making statements in Java that flows according to certain conditions. The branching of these conditions is a result of the programโ€™s state change. That is, there will be an if-else condition inside another if-else.
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
Scientech Easy
scientecheasy.com โ€บ home โ€บ blog โ€บ if else in java | nested if else, example
If Else in Java | Nested If Else, Example - Scientech Easy
February 12, 2026 - In the above example, if x is greater than y and y is greater than z, statement1 will execute. If x is greater than y but y is not greater than z then statement1 will not execute. In this case, else part (statement2) will execute. Letโ€™s take an example program based on Java nested if statements.
Top answer
1 of 4
14

You can indeed reduce the level of nesting significantly. However I leave it up to you whether you like it or not.

Your code currently has three levels of nesting, that's relatively okay. Use comments to make your code more readable instead. However you may adapt some of the following tricks.


Is still unassigned

String returnMessage = null;

// Something is empty
if (cipherFileRead.isEmpty() || freqFileRead.isEmpty()) {
    returnMessage = "Both files must be loaded and contain text. Decryption unsuccessful.";
}

// No description type given
if (returnMessage == null && freqChooser.getSelection() == null) {
    returnMessage = "Please select decryption type. Decryption unsuccessful";
}

// Decrypt
if (returnMessage == null) {
    // Select technique
    String decryptedText = null;
    if (nearestFreq.isSelected()) {
        decryptedText = decrypter.nearestFreq(cipherFileRead, freqFileRead);
    } else if (rankingFreq.isSelected()) {
        decryptedText = decrypter.byRanking(cipherFileRead, freqFileRead);
    }

    // Write decrypted text
    file.writeToFile(decryptedText, "output.txt");

    returnMessage = "Successfully decrypted to output.txt";
}

// Show return message
JOptionPane.showMessageDialog(null, returnMessage);

So the trick was to check whether returnMessage is still unassigned.

The disadvantage of this style is that it slows the program a bit because it makes it harder for the processor to guess the conditions correct for pipelining. This is called branch prediction and all processors do that.

But if it enhances readability, for example by reducing a really deep nesting, you may use it.


Return from method

However if this is a method I would definitely give the advice to use such a style, but then by using return like:

public String decryptFile() {
    // Something is empty
    if (cipherFileRead.isEmpty() || freqFileRead.isEmpty()) {
        return "Both files must be loaded and contain text. Decryption unsuccessful.";
    }

    // No description type given
    if (freqChooser.getSelection() == null) {
        return "Please select decryption type. Decryption unsuccessful";
    }

    // Decrypt
    // Select technique to use
    String decryptedText = null;
    if (nearestFreq.isSelected()) {
        decryptedText = decrypter.nearestFreq(cipherFileRead, freqFileRead);
    } else if (rankingFreq.isSelected()) {
        decryptedText = decrypter.byRanking(cipherFileRead, freqFileRead);
    } else {
        // Out of techniques?
        return "No decryption technique can be applied.";
        // Or if this must not happen due to context, use:
        // throw new AssertionError();
    }

    // Write decrypted text
    file.writeToFile(decryptedText, "output.txt");

    return "Successfully decrypted to output.txt";
}

And the caller will then do it like:

// Show return message
JOptionPane.showMessageDialog(null, decryptFile());

In this scenario, next to reducing the nesting, you also reduce the amount of time you spend in the code itself.

You should definitely pack this inside a method. It should not be the decision of the decryption where and how to display the return message. Instead return the message and let the caller decide how to use it.

Note that in practice you probably want to add some arguments to the method and so on. Also you may want to use exceptions instead of plain String messages, like IllegalArgumentException.

2 of 4
6

I'll answer by using the principles of one of my favorite book called "Clean Code":

  1. A function should do only one thing, if you have nested if like this your function is certainly doing more than one thing.

  2. So that means, each if/else if/else block should then be in its own function. This solved the nested if problem.

  3. And the extracted function should be given a descriptive name of what it does. This is even better then commenting it because comment can go out of date, or even irrelevant, and thus become misleading.

So if I were try to refactor your function with the above principles, I may come up with something like this:

public void displayDecryptResult() {
    String decryptResult = decrypt();
    JOptionPane.showMessageDialog(null, decryptResult);
}

private String decrypt() {
    String decryptResult;

    if(!cipherFileRead.isEmpty() && !freqFileRead.isEmpty() ){
        decryptResult = decryptForValidInputFiles();
    } else{
        decryptResult = "Both files must be loaded and contain text. Decryption unsuccesful.";
    }

    return decryptResult;
}

private String decryptForValidInputFiles() {
    if (freqChooser.getSelection() != null){
        message = decryptForValidInputFilesAndDecryptionType();
    } else {
        message = "Please select decryption type. Decryption unsuccesful";}
    }

    return message;
}

private String decryptForValidInputFilesAndDecryptionType() {
    if(nearestFreq.isSelected()){
        file.writeToFile(decrypter.nearestFreq(cipherFileRead, freqFileRead), "output.txt");;
    }
    else if (rankingFreq.isSelected()){
        file.writeToFile(decrypter.byRanking(cipherFileRead, freqFileRead), "output.txt");;
    }

    return "Succesfully decrypted to output.txt";
}

Some may find the function name is too descriptive that it becomes laughable. But after a long time you've written the code, and you have to debug it, you would thank you had given those descriptive name, so you can easily skim through the pseudocode like names to get idea of what it's trying to do.

๐ŸŒ
DEV Community
dev.to โ€บ paulike โ€บ nested-if-and-multi-way-if-else-statements-3neh
Nested if and Multi-Way if-else Statements - DEV Community
May 2, 2024 - The statement in an if or if-else ... legal Java statement, including another if or if-else statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following ...
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ nested-if-in-java-programming
Nested If in Java Programming
March 26, 2025 - We can use Nested IF statements in these situations, but please be careful while using them. For example, every person is qualified to work if he is 18 years old or above; otherwise, he is not qualified.
๐ŸŒ
CodeWithHarry
codewithharry.com โ€บ tutorial โ€บ java-nested-if-statements
Nested if Statements | Java Tutorial | CodeWithHarry
public class Nested { public static void main(String[] args) { String name = "Mohan"; int Roll = 25; int marks = 85; if (name.equals("Mohan") && Roll == 25) { if (marks > 35) { System.out.println("Mohan has been promoted to next class."); } else { System.out.println("Mohan needs to give re-exam."); ...
๐ŸŒ
Refreshjava
refreshjava.com โ€บ java โ€บ else-if-and-nested-if-else
Java if...else if condition - Java nested if else - RefreshJava
Yes, we can use if statement inside else if statement, the program will run successfully. Java allows programmer to place if else block inside another if or else block. This is called as nested if else statement. Programmer can do any level of nesting in program which means you can place if else block inside another if or else block up to any number of times.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ nested-if-example-in-java
Mastering Nested `if` Statements in Java โ€” javaspring.net
For example, when a user is asked to enter a password, you might want to check if the password meets certain criteria such as length and complexity. import java.util.Scanner; public class PasswordValidation { public static void main(String[] ...
๐ŸŒ
Studytonight
studytonight.com โ€บ java-programs โ€บ java-nested-if-program
Java Nested If Program - Studytonight
April 1, 2021 - In this program, we will see the implementation of the nested if-else statements in a java program. ... Create an instance of the Scanner class. Declare a variable to store the department name. Ask the user to initialize the year. Use the first if statement to check the department of the student. Use the inner if statement to check in which year the student is. Display the result. ... Below is the Java code example for nested if-else.