I came upon an interesting blog post about Java control flow. The author listed six examples (from LASER 2009 summer school on Software Testing) of pseudo Java code, and you have to determine what the value of the int b is, as well as whether an Exception is thrown or not. You can assume the program will execute with proper syntax, and proper throws Exception on the method signature.

 Here are my answers, and explanations. The actual answers will be posted in the author's next blog entry.

1. What is the value of b at the end of this code:

foo () {
	int b = 1;
	b++;
}

My answer: b is 2

2. What is the value of b at the end of this code:

foo () {
	int b = 1;
	while (true) {
		b++;
		break;
	}
}

My answer: b is 2 because it gets incremented one first iteration of the while loop, then the loop breaks.

3. What is the value of b at the end of this code and tell us if this executes normally or with an exception:

foo () {
	int b = 1;
	try {
		throw new Exception();
	}
	finally {
		b++;
	}
}

My answer: The exception is thrown, and then b is incremented to 2. And since the exception in not caught, it is thrown from the method.

4. What is the value of b at the end of this code and tell us if this executes normally or with an exception:

foo () {
	int b = 1;
	while (true) {
		try {
			b++;
			throw new Exception();
		}
		finally {
			b++;
			break;
		}
	}
	b++;
}

My answer: b is incremented in the try block, then exception is thrown. In the finally block, b is incremented again, then a static return from break brings control flow to the end of the method where b is once again incremented, and no exception is thrown from the method. So, b is 4 at the end, and no exception is thrown... in fact, you don't even need a throws Exception in the method signature because this method cannot throw Exception.

5. The previous sample was too long, what does this return:

int foo () {
	try {
		return 1;
	}
	finally {
		return 2;
	}
}

My answer: the return 2 is the last statement executed in the method, so it returns 2.

6. If you have answered properly to the above questions, then you are definitely quite an expert. To prove it, tell us the value of b at the end of the call as well as the return value:

int b;
int foo () {
	b = 0;
	try {
		b++;
		return b;
	}
	finally {
		b++;
	}
}

My answer: b is incremented in the try block, then returned; return value is 1 from the method. Then the finally block executes and increments b, so it is 2 at the end (but return value is still 1).

Update: Feb 2, 2012

Looks like I was write on all the parts. :)

Read the answers post


blog comments powered by Disqus