Java syntax: Difference between revisions

Content deleted Content added
 
(5 intermediate revisions by 2 users not shown)
Line 476:
/* The following line is equivalent to
if (foo == ColorName.RED) foo = ColorName.BLUE; */
if (foo == RED) {
foo = BLUE;
}
}
}
Line 722 ⟶ 724:
 
===Iteration statements===
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. Since [[J2SE 5.0]], Java has four forms of such statements. The condition must have type <code>boolean</code> or <code>java.lang.Boolean,</code>. meaningJava C's<syntaxhighlightdoes lang="c">not implicitly convert integers or class types to Boolean values.
 
For example, the following code is valid in C but results in a compilation error in Java.
<syntaxhighlight lang="c">
while (1) {
doSomething();
}
</syntaxhighlight>results in a compilation error.
 
====<code>while</code> loop====
Line 763 ⟶ 768:
</syntaxhighlight>
 
Like C, all three expressions are optional. The following loop isnever infiniteterminates:
<syntaxhighlight lang="java">
for (;;) {
Line 770 ⟶ 775:
</syntaxhighlight>
 
====Enhanced <code>for</code>Foreach loop====
{{Main|Enhanced forForeach loop}}
[[enhanced for loop|Enhanced <code>for</code>Foreach loop]]s have been available since [[J2SE 5.0]]. This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. This for loop from Java was later added to [[C++11]]. Unlike [[C Sharp (programming language)|C#]], this kind of loop does not involve a special keyword, but instead uses a different notation style.
 
<syntaxhighlight lang="java">
Line 783 ⟶ 788:
 
====Labels====
Labels are given points in code used by <code>break</code> and <code>continue</code> statements. The JavaWhile <code>goto</code> is a reserved keyword in Java, it cannot be used to jump to specific points in code (in fact it has no use at all).
 
<syntaxhighlight lang="java">