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).
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.
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.
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.
In Java, a variable declaration Thread t = ...
is technically not a statement, whereas a block { ... }
is. What follows for ( ... )
must be a statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With