Java: Difference between revisions
Jump to navigation
Jump to search
Line 11: | Line 11: | ||
== Sample Program == |
== Sample Program == |
||
* Create a file <tt>HelloWorld.java</tt>, with content: |
|||
<source lang="java"> |
<source lang="java"> |
||
public class HelloWorld { |
|||
Class Test { |
|||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
System.out.println("Hello, World!"); |
|||
for (int i = 0; i < args.length; i++) |
for (int i = 0; i < args.length; i++) |
||
System.out.print( |
System.out.print(0 == i ? args[i] : " " + args[i]); |
||
System.out.println(); |
System.out.println(); |
||
} |
} |
||
} |
} |
||
</source> |
|||
* Compile (<tt>javac</tt> must be in the path): |
|||
<source lang=bash> |
|||
javac HelloWorld.java |
|||
</source> |
|||
* Run: |
|||
<source lang=bash> |
|||
java HelloWorld |
|||
</source> |
</source> |
||
Revision as of 14:19, 19 July 2011
java.exe Command-Line
-Djava.library.path=<dllpath>
- Set path to find DLL Libraries
-jar <jarfile>
- Set jar file to load (should contain main())
java -Djava.library.path=.\var -jar "$(MYROOT)\var\main.jar"
Sample Program
- Create a file HelloWorld.java, with content:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
for (int i = 0; i < args.length; i++)
System.out.print(0 == i ? args[i] : " " + args[i]);
System.out.println();
}
}
- Compile (javac must be in the path):
javac HelloWorld.java
- Run:
java HelloWorld
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 tokenclass
. The type of a class literal isClass
. 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());
References
String Integer.toHexString(byte); // Convert an integer to string in hexadecimal
"00" + Integer.toHexString( i ) // Pad with leading zeros (then take rightmost characters)
String.format("%04x",0x2a);
//Prepend 0 if needed
String hex = Integer.toHexString((byte));
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);