Thursday 30 January 2014

Packaging multiple Java files from the command line

Sometimes it's good to leave your IDE of choice behind and go old school. A text editor and the command line. One thing that can catch people out is packaging.
If you have , for example, 3 files with the same package declaration of:

package com.modemnoise.code;

To compile this from the command line you would navigate to the directory in your terminal and execute the following line:
javac -d . *.java
You can then execute your file (yourFile.class) like so:
java com.modemnoise.code.yourFile
The folder structure will be as expected for packaged code i.e. .\com\modemnoise\code\yourFile.class The -d switch tells the compiler the code is to be compiled in an existing directory and the period(.) tells the compiler to start in the current directory. After this the compiler recognises the package declaration and creates the structure for you.

Oracle javac tech note

Monday 27 January 2014

Convert an Array to an ArrayList in Java

To convert an Array into a Java ArrayList we can use the java.util.Arrays class's asList() method. The following code example demonstrates converting an Array of Strings to an ArrayList of Strings.



Source Code (Pastebin)
This will print out the following to the console:

Mary
had
a
little
lamb

You can now add(), remove() etc. using the assorted methods available on ArrayLists.

 Simples!