How to Java

java
 
Simple java source to use as skeleton

public class echo { public static void main (String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } }

 
Common statements


while (expression) { statement(s) }

do { statement(s) } while (expression);

for (initialization; termination; increment) { statement(s) }

if (expression) { statement(s) } else { statement(s) }
try { statement(s) } catch (exceptiontype name) { statement(s) } finally { statement(s) }
 
Constant declaration

    final <type> <identifier> = <value>;

 
Command-Line Arguments


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


Parsing Numeric Command-Line Arguments

	int firstArg;
	if (args.length > 0)
	    firstArg = Integer.parseInt(args[0]);

 
Type conversions

String -> integer:
Integer.parseInt("1234")

integer -> String
Integer.toString(1234)
String.valueOf(1234)
 
Handling line oriented text files

creating a text file:

	PrintWriter out = new PrintWriter(new FileWriter("filename"));

writing text in the file:
	out.print("bla");
	out.println("blabla");

closing the file:
	out.close();


opening an existing file:

	LineNumberReader in = new LineNumberReader(new FileReader("filename"));

reading text from the file:
	in.readLine()

 
Using temporary files

create a temp file:
	File tempFile = File.createTempFile("prefix", null, new File("."));

at closure of the temp file:
	File target = new File(fileName);
	long savetime = target.lastModified(); 
	target.delete(); 
	tempFile.renameTo(target); 
	target.setLastModified(savetime); 

 
Using Properties to Manage Program Attributes

	import java.util.Properties;
	Properties applicationProps = new Properties();

loading properties from last invocation:

	in = new FileInputStream("appProperties");
	applicationProps.load(in);
	in.close();

saving Properties:

	FileOutputStream out = new FileOutputStream("appProperties");
	applicationProps.store(out, "---No Comment---");
	out.close();

getting a value
	applicationProps.getProperty(String key)

setting a value
	applicationProps.setProperty(Object key, Object value) 

 
Handling associative arrays


declaring an associative array:

	Map myArray = new HashMap();

setting values in associative array:

	myArray.put(key,value);

getting a value from an associative array:

	myArray.get(key)

iterating an associative array:

	for (Iterator i = myArray.values().iterator(); i.hasNext(); ) 
	System.out.print(i.next());

 
Creating an executable jar

We want to create an executable jar named alfa.jar.
1) Create a text file called alfa.mf with the following text:

Main-Class: <classname>

Note: This file has to contain an empty line at the end!

2) Create a batch file with the following commands and launch the batch file, we get alfa.jar

del *.class
javac *.java
dir /b *.class > classes.list
jar cmf alfa.mf alfa.jar @classes.list

3) The alfa.jar can be launched using the following command line:


java -jar alfa.jar

---
Note that a java application can access the embedded files in a jar file:

	java.net.URL helpURL = <classname>.class.getResource("HelpFile.html");

 
Using a Timer

define the timer:
	java.util.Timer timer;

init and start the timer:
    timer = new java.util.Timer();
    timer.schedule(new PeriodicTask(), 0, 100);

perform the periodic task:
    class PeriodicTask extends java.util.TimerTask {
    	public void run() {
	    if (condition to continue the task) {
	    	statements;
	    } else {
	        timer.cancel();
//	        System.exit(0);   //Stops the AWT thread if needed
	    }
        }
    }


 
Naming convention
- constants: all letters uppercase
- classes: nouns, in mixed case with the first letter of each internal word capitalized.
- methods: verbs, in mixed case with the first letter lowercase, 
           with the first letter of each internal word capitalized. 
- variables: in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. 

 
packages

The package statement (package <package name>;) must be the first line in every source file belonging to the package.


 
Http URL Syntax (reference: RFC 1738):

hostport       = host [ ":" port ]
httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]
hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
search         = *[ uchar | ";" | ":" | "@" | "&" | "=" ]


lowalpha       = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
                 "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
                 "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
                 "y" | "z"
hialpha        = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"


alpha          = lowalpha | hialpha
digit          = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
                 "8" | "9"
safe           = "$" | "-" | "_" | "." | "+"
extra          = "!" | "*" | "'" | "(" | ")" | ","
national       = "{" | "}" | "|" | "\" | "ˆ" | "~" | "[" | "]" | "`"
punctuation    = "<" | ">" | "#" | "%" | <">


reserved       = ";" | "/" | "?" | ":" | "@" | "&" | "="
hex            = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                 "a" | "b" | "c" | "d" | "e" | "f"
escape         = "%" hex hex

unreserved     = alpha | digit | safe | extra
uchar          = unreserved | escape
xchar          = unreserved | reserved | escape
digits         = 1*digit


 
Filename syntax
Microsoft Windows: Allows any character except 0x0-0x1F, '<', '>', '*', '?', ':', '"', '/', '\', and '|'.
Furthermore, names must not end with a trailing space or period.

 
Using Javadoc

The following comment shall be added for class declaration:

/** 
 * A class representing a text window on the screen.
 * 
 */

The following comment shall be added for method declaration:
/**
* Creates a new instance.
* 
* @param aManager a manager
* @param aFeature the feature that will receive events
*/
 
Some new features in Java 1.5

Generics, no more need for casting!

how to define a generic class:

	public class Box<T> {

	    private T t; // T stands for "Type"          

	    public void set(T t) {
		this.t = t;
	    }

	    public T get() {
		return t;
	    }
	}


now we create an instance with type Integer

	Box<Integer> integerBox = new Box<Integer>();

it is possible to use the wildcard ? for generic classes

	void printCollection(Collection<?> c) { 
		for (Object e : c)
			System.out.println(e);
	}
---
for-each loop: no more need for the iterator!

	void cancelAll(Collection<TimerTask> c) {
	    for (TimerTask t : c)
		t.cancel();
	}
---
type enum (warning: it extends implicitly java.lang.Enum)

	enum Season { WINTER, SPRING, SUMMER, FALL }
	Season now = Season.WINTER;
---
The Concurrency Utilities packages provide a powerful of high-performance threading utilities
such as thread pools and blocking queues. 

safe sequence number generator:

	import java.util.concurrent.atomic.AtomicLong;
	class Sequencer {
	  private AtomicLong sequenceNumber = new AtomicLong(0);
	  public long next() { return sequenceNumber.getAndIncrement(); }
	}

 


javalc6