Java: Difference between revisions

From miki
Jump to navigation Jump to search
Line 9: Line 9:
}
}
</source>
</source>

== Syntax ==

=== For loops ===
Foreach loops (available since 1.5) [http://leepoint.net/notes-java/flow/loops/foreach.html]:
* More readable
* Series of values
* Arrays and Collections
* Applies to <tt>Iterable&lt;E&gt;</tt>.
But
* Only access.
* Only single structure.
* Only single element.
* Only forward.
* At least Java 5.

{| class="wikitable"
|-
!FOR EACH loop!!Equivalent FOR loop
|-
|
<source lang="java">
for (type var : arr) {
body-of-loop
}
</source>
|
<source lang="java">
for (int i = 0; i < arr.length; i++) {
type var = arr[i];
body-of-loop
}
</source>
|-
|
<source lang="java">
for (type var : coll) {
body-of-loop
}
</source>
|
<source lang="java">
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
type var = iter.next();
body-of-loop
}
</source>
|}


== Miscellaneous ==
== Miscellaneous ==

Revision as of 14:31, 29 September 2010

Sample Program

Class Test {
  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++)
      System.out.print(i = 0 ? args[i] : " " + args[i]);
    System.out.println();
  }
}

Syntax

For loops

Foreach loops (available since 1.5) [1]:

  • More readable
  • Series of values
  • Arrays and Collections
  • Applies to Iterable<E>.

But

  • Only access.
  • Only single structure.
  • Only single element.
  • Only forward.
  • At least Java 5.
FOR EACH loop Equivalent FOR loop
for (type var : arr) {
    body-of-loop
}
for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
for (type var : coll) {
    body-of-loop
}
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}

Miscellaneous

Class Literal
A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
Eg:
public class MyClass //...
//...
printf ("Class name is %s\n",MyClass.class.getName());