Prev Next

Java / Control Statements

Could not find what you were looking for? send us the question and we would be happy to answer your question.

Is there a way to access an iteration-counter in Java's for-each loop?

You'll have to provide your own counter.

The reason is that the for-each loop internally does not have a counter; it is based on the Iterable interface. It uses an Iterator to loop through the "collection" - which is not a collection and does not have index.

Advantages of declaring loop variable as final in enhanced for-loop.
  • Enables using the loop variable in an anonymous inner class within the loop body.
for (final int i : intList) {
	Runnable run = new Runnable() {
		public void run() {
			process(i);
		}
	};
	new Thread(run).start();
}
  • It prevents the loop variable to be accidently changed inside the loop while iterating.
Does returning a value from the loop body break the loop?

Yes. return statement breaks the loop and returns from the entire method immediately. The only code that will be executed is the finally clause and the release of any synchronized statement.

public class ForLoopReturnExample {

public static void main(String[] args) {

	for (int i = 0; i < 10; i++) {
		try {
			if (i == 1)
				return;
			System.out.println(" try block. i = " + i);
		} finally {
			System.out.println(" finally block i=." + i);
		}
	}
}
}

The same applies to the break statement as well, the finally clause will be executed before exiting the loop.

What happens when we forget break in switch case?

The switch statement will continue the execution of all case labels until if finds a break statement, even though those labels doesn’t match the expression value.

What types of loops does Java support?

Java offers three different types of loops: for, while, and do-while.

A for loop provides a way to iterate over a range of values. It’s most useful when we know in advance how many times a task is going to be repeated.

for (int i = 0; i < 50; i++) {
     // do something 
}

A while loop can execute a block of statements while a particular condition is true.

while (iterator.hasNext()) {
    // ...
}

A do-while is a variation of a while statement in which the evaluation of the boolean expression is at the bottom of the loop. This guarantees that the code will execute at least once.

do {
    // ...
} while (i != -1);
How will you exit anticipatedly from a loop?

Using the break statement, we can terminate the execution of a loop immediately.

for (int i = 0; ; i++) {
    if (i > 10) {
        break;
    }
}
Difference between dead code and unreachable code in Java.

Dead code is a compiler warning while unreachable code is a compile time error.

As per Java language specification, 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 expressions are not taken into account in the flow analysis.

As per the JLS, if statement is excluded so we get dead code warning.

What types of loops does Java support?

Java offers three different types of loops: for, while, and do-while.

A for loop iterates over a range of values. It is useful when we know in advance how many times a task is going to be repeated.

for (int i = 0; i < 10; i++) {
     // perform some action
}

Java also supports enhanced for loop to iterate over collection.

for (Employee emp:employeeList){

{

A while loop can execute a block of statements while a particular condition is true.

while (i<10) {
    // ...
}

A do-while is a variation of while statement in which the evaluation of the boolean expression is at the bottom of the loop. This guarantees that the code will execute at least once.

Which is considered as a selection statement?

if block is considered as selection statement; continue and break are jump statements, and for is a looping statement.

Can you create switch statement using enum?

Yes.

public class EnumSwitchCaseExample {

	enum Communication {
		EMAIL, CHAT, PHONECALL, MESSAGE
	}

	public static void main(String[] args) {

		Communication mode = Communication.CHAT;
		switch (mode) {
		case EMAIL:
			System.out.println("Communicated by Email.");
			break;
		case CHAT:
			System.out.println("Communicated by Instant messaging.");
			break;
		case PHONECALL:
			System.out.println("Communicated by Voice call.");
			break;
		case MESSAGE:
			System.out.println("Communicated by Message.");
			break;
		}
	}
}
Can we write switch case using a double variable?

No. We cannot switch on a value of type double. Only int, strings or enum variables are permitted.

What is tautology and contradiction in boolean expressions?

The tautology refers to a logical expression which always evaluates to true, regardless of the logical value of its variables.

For example, consider the below expresion in Java.

boolean isTrue = true;
if (! (! (isTrue) )) {

}

In the above example, applying NOT operation twice (double negation) does not impact the expression value and it always returns true. This is an example of tautology.

On the other hand, contradiction refers to the opposite of tautology, that is, the expression will always return false.

«
»
Access Modifiers

Comments & Discussions