Java Stuff

From TechWiki



Java API Specifications

Terminal Execution

To launch a Java program packaged as ../ch/j-node/project/main/ manually, given the binary files are in a directory .../bin/:

cd /home/jbg/project/bin
java -Djava.library.path=/usr/local/... -classpath .:/usr/local/linux/swt-linux.jar:/usr/local/...:/home/jbg/project/bin/:... 

Or, alternatively, you can use the JAR file from any directory

java -Djava.library.path=/usr/local/... -classpath .:/usr/local/linux/swt-linux.jar:/usr/local/...:/home/my/path/to/jar/myJar.jar 

To create a JAR file using Eclipse, see EclipseStuff.

If you just have a jar file:

java -jar /path/to/jar/myJar.jar

Making Life a Little Simpler...

Using bash you can set your .bashrc file to set the correct classpath variables.

In your home directory, edit the file, e.g.,

vim .bashrc

and add

export CLASSPATH=.${CLASSPATH}$( /home/me/myJava)$( /home/me/MyJars/)

The script gets every Java binary from /home/me/myJava and gets the name of every jar file in /home/me/MyJars/. Thanks Markus.

Put the scripts into /usr/local/bin/ or wherever and

source .bashrc

to load changes. To check, type


and you should get a list of all your Java related stuff.

Now go to any Java directory

cd /home/me/myJava/someEclipseProject/

Here you should have the foldesr bin/ and, e.g., src/ch/myUrl/Main/ containing your Java classes in the package called ch.myUrl.Main. Next execute

java ch.myUrl.Main.MyMainJavaClass perhapsSomeCongigStuff.xml

where the file perhapsSomeCongigStuff.xml is in the /home/me/myJava/someEclipseProject/ directory.

Code Examples

Arrays of Arrays

An ArrayList of Arrays:

private ArrayList<Double>[] myList;
int lgth = 7;
myList = new ArrayList[lgth];
for (int i = 0; i < lgth; i++)
    myList[i] = new ArrayList<Double>();

So myList is an Array of ArrayLists (myList[i]):


To loop through the values of one Arraylist:

for (double val: myList[ind])

There is a problem with generics (unchecked conversion) however, so you need to add the annotation


in front of the method instantiating the Array, if you want to get rid of the warning.


Given an array of data and the value for the granularity (bin size):

double min = min(data);
double max = max(data);
bin = (max - min) / granularity;
Double[] hist = new Double[granularity + 1];
for (int i = 0; i < hist.length; i++) {
    hist[i] = 0.0;
int offset = -(int) Math.floor(min / bin);
for (int i = 0; i < data.size(); i++) {
    int ind = (int) Math.floor(data.get(i) / bin);
    if ((ind + offset) <= granularity)
        hist[ind + offset] += 1.0;


To get the cumulative distribution from the histogram, use

                                int size = hist.length;
				Double[] cdf = new Double[size];
				double sum = 0.0;
				int size = hist.length;
				double[] sum_i = new double[size];
				for (int i = 0; i < size; i++) {
					sum += hist[i];
					sum_i[i] = sum;
				for (int i = 0; i < size; i++)
					cdf[i] = sum_i[i] / sum * 100;


Note that

obj a = new Obj();
obj b = a;

results in b beeing (pointing to) the same object as a. Use:

obj b = (obj)a.clone();

if you want a copy of a.

Dates and Times

If you have bizarre problems with using dates, calendars and stuff, try using a different jdk...

Read Milliseconds

Calendar debugCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.println("time: " + debugCal.getTime());


  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

is 24 h format and

  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

is 12 h am/pm format.


  Date Time = new Date();
  Calendar c = Calendar.getInstance();


  Date t = new Date();
  DateFormat df = DateFormat.getInstance();
  ObcDateFormat f = new ObcDateFormat("dd.MM.yyy hh:mm:ss");
  Date tt = f.parse("12.02.2003 23:55:40");


  if ( t.before(tt)) {


Set date to now:

  Date t = new Date(System.currentTimeMillis());

Get day:

  Date t = new Date();
  Calendar cal = Calendar.getInstance();
  int day = cal.get(Calendar.DAY_OF_WEEK) - 1;

Note that t.getDay() is depricated.


Get time zone info:

   TimeZone here = TimeZone.getDefault();

Set time zone:

   ObcDateFormat f = new ObcDateFormat("dd.MM.yyy HH:mm:ss");

Disable DST

Get Calendar from DateFormat

cal = formatter.getCalendar();

and set


Simple I/O

Output to File


Text output to file:

   FileOutputStream out; // declare a file output object
   PrintStream p; // declare a print stream object
       // Create a new file output stream
       // connected to "myfile.txt"
       out = new FileOutputStream("myfile.txt");
       // Connect print stream to the output stream
       p = new PrintStream( out );
       p.println ("This is written to a file");
   catch (Exception e)
       System.err.println ("Error writing to file");
try {
   FileWriter fw = new FileWriter("/mydir/");
} catch (IOException e) {

Format Output

double value;
DecimalFormat myFormatter = new DecimalFormat("#.0000");
fw.write(myFormatter.format(value) + " ");

Read File

Read a file line by line and check for delimiters. This only works since Java 5.0 as it uses the Scanner class.

                       try {
				Scanner s = new Scanner(new File("/myDir/myFile.txt"));
				while ( s.hasNextLine() ) {
					String str = s.nextLine();
					int posDelimiter = str.indexOf(" "); //Delimiter is white space
					System.out.println(str.substring(0, posDelimiter));
			} catch (FileNotFoundException e) {

You can do more fancy delimiting with

new Scanner(...).useDelimiter("...");

A Specific Example

An example using generics, interfaces and inner classes...

Before reading on, have a look at the code in the next section below.

Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();

here the class Inner, contained in the outer class Wrapper, is instantiated. The syntax is

Wrapper.Inner inner = Inner();

where w is an instance of Wrapper.

The object

Generics<Wrapper> obj;

is an instance of the class Generics:

public class Generics<E extends Interface> {...}

which in this case expects a datatype which extends Interface,i.e., the Wrapper class.


will retrieve an object of type Interface from obj. If one wants to extract the implementing class from it, use:


which returns an instance of Wrapper.

So that is why

Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();



 public class Main {
   public static void main(String args[]) {
     new Main();

   public Main() {
     Generics<Wrapper> obj = new Generics<Wrapper>(new Wrapper());
     Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();

 public class Wrapper implements Interface {

   // Inner class
   public class Inner {
     public final void hi() {

public class Generics<E extends Interface> {
 private E obj;
 public Generics(E obj) {
   this.obj = obj;
 public final E getObject() {
   return obj;

public interface Interface {


Out Of Memory

Free up space:

sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches


watch -n 3 free -mh

Java VM:

java -Xmx4G -Xverify:none -Xms4G -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -jar ... > log.txt 2>&1 &