In one of the forum I found below code as a question:
public class Test{
public static void main(String[] args){
System.out.println("Hello");
Test:
System.out.println("World");
}
}
And asked what would be the result ?
I thought it would be a compile time error, since I have not seen Test:
code in java.
I was wrong, surprisingly both line is printed after compiling and running above code.
Can any one tell me what is the use of this Test:
kind of code ? And why it is not throwing error ?
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
Conditional Expression Almost every operator has either one or two operands. This is the only operator in Java with three operands. This is called the conditional expression or the question mark-colon operator.
It is simple to label a loop, place the label before the loop with a colon at the end as shown below in the example: public class ColonJava3 { public static void main(String args[]) { int i, j=0; //outer label outerloop: for(i=0; i < 3; i++) { System.
The question mark and colon operators are collectively called ternary operators in Java because they work on three operands. It is the short-hand solution of the if ... else statement in Java and can be used as a single line statement for decision making.
Text followed by a colon (:
) is called a label. It can be used in the context of control structures (such as loops) to break
to or continue
at. In this context, although perfectly legal, it's pointless.
The Test:
text is a label, and is described in the language specification, and are used to break
or continue
from inner loops as shown in the following example:
Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break or continue statements (§14.15, §14.16) appearing anywhere within the labeled statement.
public static void main(String[] args) {
outerLoop:
while (true) {
int i = 0;
while (true) {
System.out.println(i++);
if (i > 5) {
break outerLoop;
}
if (i > 10) {
break;
}
}
System.out.println("Broken inner loop");
}
System.out.println("Broken outer loop");
}
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