HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / Dead code and unreachable code in Java

Dead code and unreachable code in Java

Learn to identify dead code and unreachable code in Java. It may be asked in your Java interview coding problems as a puzzle.

1. Dead code and unreachable code errors

To make concept of dead code, in this puzzle, I have given a piece of code below. Try to identify the problems in code, if it is compiled in eclipse IDE.

public class IdentifyProblemsInCode {

    public void howToDoInJava_method1() {
        System.out.println("how to do");
        return;
        System.out.println("in java");
    }

    public void howToDoInJava_method2() {
        System.out.println("how to do");
        if (true) {
            return;
        }
        System.out.println("in java");
    }

    public void howToDoInJava_method3() {
        System.out.println("how to do");
        while (true) {
            return;
        }
        System.out.println("in java");
    }
}

I am giving the answer of above puzzle in next section, but I would recommend you to try first yourself. Its for fun only.

2. Solution – It has dead code

We all must have been faced compilation errors related to “Unreachable code” and some may have noticed “dead code warning“. Above puzzle is related to them only.

In first method howToDoInJava_method1(), second print statement is unreachable, so compiler will complain for oblivious reasons.

In second method howToDoInJava_method2(), second print statement is also unreachable, but strange compiler only warns you. We will later try to get the logic here.

In third method howToDoInJava_method3() also, second print statement is unreachable, so compiler will complain again.

Why !!

3. What is dead Code

The unreachable code in method 2 is called “Dead code“. This is purely Eclipse compiler reported error, and if you will compile above class with “javac“, Java inbuilt compiler will only complain for other two methods. [First and Third].

Quote from Java language specification –

“The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements.

Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of other expressions are not taken into account in the flow analysis”.

What that means, is that 'if' block is not taken into account while determining unreachable code. Since if you go through one of the paths of the 'if' statement, you could reach second print statement. It all depends on compiler which determines this during compile time.

In other two statement, compiler has determined the un-reachability so it complains with error.

If we re-write second method again like this.

public void howToDoInJava_method2() 
{
	System.out.println("how to do");

	if (true) 
	{
		return;
	}
	else
	{
		return;
	}

	System.out.println("in java");
}

Now, compiler determine that in no way it can reach to last print statement, so 'javac' again reports unreachable code for this second method as well.

If you still have some doubts related to dead code in Java, please write down in comment section. I will try to resolve your queries.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Brindha D

    July 13, 2020

    Difference b/w dead code & unreachable code?
    still, I have confusion not clear with your examples.

    • Lokesh Gupta

      July 13, 2020

      Please share the specific question, what is not clear?

  2. Santosh

    January 10, 2020

    Still I have doubt could pls explain with some other example..

  3. Gaurav Kumar

    January 23, 2014

    As per the java specification quote(i.e specified by you), ‘IF condition expression’ aren’t taken into account during compilation but when i was compiling the below code then it was giving me an warning ‘Dead code’ for line number 2.
    if(1==2)
    System.out.println(“Dead code”);

    As per the quote, it should not give the warning.Please let me know that why this above code is giving an warning.
    it might be happen that i could not understand this quote correctly.

    • Lokesh Gupta

      January 23, 2014

      As I told above “The unreachable code in method 2 is called “Dead code”. This is purely Eclipse compiler reported error”.

    • Hemant

      May 30, 2019

      Try doing the same with javac, you won’t get error

Comments are closed on this article!

Search Tutorials

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces