Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop brackets [duplicate]

Tags:

java

for-loop

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A();
                Task task= new Task();
                for(int i=0; i<10; i++)
                        Thread t= obj.newThread(task);
        }
}

Compilation error: Multiple markers at this line

Syntax error, insert ";" to complete Statement
  t cannot be resolved to a variable
Syntax error, insert "AssignmentOperator Expression" to complete Assignment
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
  Thread cannot be resolved to a variable

whereas

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A();
                Task task= new Task();
                for(int i=0; i<10; i++){
                        Thread t= obj.newThread(task);
                }
        }
}

compiles successfully (note the added curly braces in the for loop).

like image 616
Payal Bansal Avatar asked Apr 20 '15 20:04

Payal Bansal


People also ask

Does a for loop need brackets?

They are optional. That is just how it is. If you don't use braces to group multiple statements into one, then only the first statement following the for or if preamble is considered part of that construct.

Can we write for loop without braces?

Curly braces in for loop is optional without curly braces in for-loop we can take only one statement under for-loop which should not be a declarative statement and if we write declarative statement there then we will get compile-time error.

Do you need curly brackets for loop Java?

Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.


1 Answers

In Java, a variable declaration Thread t = ... is technically not a statement, whereas a block { ... } is. What follows for ( ... ) must be a statement.

like image 116
Paul Boddington Avatar answered Oct 12 '22 13:10

Paul Boddington