SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Object-oriented Design
Exercise:
Exercises
Question:17 | ISBN:9781118771334 | Edition: 6

Question

Most modern Java compilers have optimizers that can detect simple cases when it is logically impossible for certain statements in a program to ever be executed. In such cases, the compiler warns the programmer about the useless code. Write a short Java method that contains code for which it is provably impossible for that code to ever be executed, yet the Java compiler does not detect this fact

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package Data_Structures.Chapter2;

public class DeadCode {
	
	// this method has unreachable code and gives compilation error if we uncomment the println statement
	public void thisMethodHasUnreachableCode() {
		System.out.println("Reachable code");
		return;
		// below line cause compilation problem as it is unreachable code
		// System.out.println("Unreachable code");
	}

	// below method has deadcode it wont cause compilation error, but gives waring
	public void thisMethodHasDeadCode() {
		System.out.println("Reachable code");
		if (2 < 3) {
			return;
		}
		System.out.println("Dead Code");
	}
	// this method too has unreachable code and gives compilation error if we uncomment the println statement
	public void thisOneHasUnreachableCode() {
		System.out.println("Reachable code");
		while (1 < 2) {
			return;
		}
		
	//	System.out.println("Again unreachable code");
	}

	public static void main(String args[]) {

		DeadCode deadcode = new DeadCode();
		deadcode.thisMethodHasUnreachableCode();
		deadcode.thisMethodHasDeadCode();
		deadcode.thisOneHasUnreachableCode();

	}

}

 

Output:

Reachable code
Reachable code
Reachable code

 

0 0

Discussions

Post the discussion to improve the above solution.