A great benefit of using the Java programming language is the huge class library available. Not only does Sun provide a large class library in their Java SDK (Software Development Kit), but there are extensive, freely available, libraries available from organizations like the Apache Project. If you can find the right class and use it in the correct way, you can avoid writing a great deal of code. But this begs the question... How do you find the right class and how do you understand how to use it, given that the Javadoc documentation is frequently less that complete?
A great reference to answer those "how do I do X in Java" questions is Java Cookbook by Ian F. Darwin. However, as extensive and useful as this book is, there are still algorithms that I have not found in it. Frequently these are just a few lines of code, but many hours can be spent pouring through the documentation and trying out code to find the right solution. Since I hate to do this twice, I've provided a few of these algorithms here.
You may use any software lined to by this page (or shown on this page) under the BSD license:
Copyright (c) 2012, Ian Kaplan
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Java: life in a pass-by-value world
This web page publishes an example of a binary tree class that supports both insert and delete. The classic binary tree delete algorithms in C or C++ make use of reference arguments and pointers to pointers. Java only supports pass by value. This code was written as a demonstration of how this language design choice affects this algorithm.
An HTTP Client built with Apache Commons classes
This is a simple HTTP client that sends POST messages to a defined URL. The HTTP client makes use of the Apache Commons HttpClient classes. In addition to handling the basic POST operation, this client handles HTTP timeout.
A Support Class for Creating an Oracle JDBC Connections
The error messages in this class refer to the Oracle database. However, this class is written using the standard Java sql package objects.
A JDBC hack to obtain the table description for a relational database table.
The table description is returned in a format that allows it to be used in SQL commands which create new tables or perform similar operations. This code has been tested under Oracle, using the default Oracle driver. Since it is standard JDBC, it should work on other databases as well.
Basic matrix multiply in Java, and related support code (jar format)
If you have Java installed you should also have the jar program which is used to create Java archives. To unpack the file matrix.jar copy it to a directory where you want the files. Then execute the command
jar xf matrix.jar
When the jar archive is unpacked there will be four files:
For the sake of simplicity these Java classes are in the default package, not within their own package.
A Sparse Array Object (jar format)
A sparse array is an array where elements are allocated in proportion to their use. So if only a few elements are used, the array will only be fractionally allocated. As the array fills, more and more of it is allocated.
This Java sparse array object is based on a similar C++ object that I have been using for some time. I have published the C++ version as part of the source base for some data structures for a VHDL compiler.
A Type-safe Enumeration Class in Java (and C++)
The third edition of The Java Language Specification describes a version of Java that is supported in the Java JDK 1.5 and later releases that includes enumerations. A class like the "type safe enumeration" class largely becomes unnecessary with this new version of Java.
This web page discusses a type safe enumeration object in Java which replaces final values. Unlike enumerations defined via final, these objects are type safe. A general purpose type safe enumeration base class is presented and its use is demonstrated.
C++ has some features that Java lacks. For example operator overloading and generic types (via templates). Although Java lacks some features, in some cases it has advantages over C++. Type safe enumeration are one example. A failed attempt to implement type safe enumerations in C++ is discussed as well.
Return the current time and date:
/**
Return the current date and time. If includeMS is true, include milliseconds. The format is:
mm/dd/yyyy hh24:mm:ss or mm/dd/yyyy hh24:mm:mss
where
hh24 is the 24-hour hour-of-the-day. mss is the millisecond value 0..999
For example
4/20/2004 16:31:23 (includeMS = false) or 4/20/2004 16:41:54:514 (includeMS = true)
Oddly, months range from 0..11, rather than 1..12, assuming the western calendar (which is a pretty safe assumption). So we add 1 to the value returned by cal.get(Calendar.MONTH).
*/
public static String getTimeAndDate( boolean includeMS ) { StringBuffer buf = new StringBuffer(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); int hour24 = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND ); int msec = cal.get(Calendar.MILLISECOND ); buf.append( month ); buf.append('/'); buf.append( day ); buf.append('/'); buf.append( year ); buf.append(' '); buf.append( hour24 ); buf.append(':'); buf.append( min ); buf.append(':'); buf.append( sec ); if (includeMS) { buf.append(':'); buf.append( msec ); } return buf.toString(); } // getTimeAndDate
An easier way to return the current time:
/** Unix epoch time (milliseconds since Jan 1, 1970) to US East Coast date and time. The exception handling below exists to work around a problem that seems to exist in some, but not all of Sun's Java JDKs. When the code is run in the debugger, it hits a FileNotFound exception. As noted below, Sun knows about the problem, but has stated that they're not going to fix it. From http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4981314 Closing as will not fix. In actuality, this cannot be fixed. We have to decide at the point the exception is thrown if it will be caught or not. If there is a native method on the stack, we can't tell if it is going to catch the exception or not. @param epoch @return */ public static String epochToDate( final long epoch ) { final String dateFormat = "yyyy-MM-dd HH:mm:ss SSS"; SimpleDateFormat formatter = null; try { formatter = new SimpleDateFormat( dateFormat ); } catch (Exception e) {} TimeZone tz = TimeZone.getTimeZone("America/New_York"); formatter.setTimeZone(tz); Date dateObj = new Date( epoch ); String dateStr = formatter.format( dateObj ); return dateStr; } // epochToDate
To get the current date and time:
Date date = new Date(); long epoch = date.getTime(); String time = epochToDate( epoch ); System.out.println( time );
Read a string from standard input in Java. Not a very demanding task and not much code. But you still have to know what classes to use. So here it is:
// Create a BufferedReader for standard input BufferedReader is = null; try { is = new BufferedReader( new InputStreamReader( System.in ) ); } catch (IOException e) { System.out.println("Error opening the input stream: " + e.getMessage()); } .... // Read a line from the input stream String line = null; if (is != null) { try { line = is.readLine(); } catch (IOException e) { System.out.println("Error reading form the input stream: " + e.getMessage()); } }
Temporarily reassign System.out to another OutputStream and then get the result in a String object.
import java.io.ByteArrayOutputStream; import java.io.PrintStream; class StdoutTest { private static class Foo { public Foo() { System.out.println("This is a String from Foo"); } } private void test() { ByteArrayOutputStream outstream = new ByteArrayOutputStream(); PrintStream ps = new PrintStream( outstream ); PrintStream keep = System.out; System.setOut( ps ); Foo f = new Foo(); System.setOut( keep ); String s = outstream.toString(); System.out.println("Output stream: " + s ); } public static void main( String argv[] ) { StdoutTest t = new StdoutTest(); t.test(); System.out.println("Standard out still works! See!"); } }
When compiled and executed, the code above will print:
Output stream: This is a String from Foo Standard out still works! See!
Find a resource (e.g., a file) in the class path
A "resource" is a file that is needed during the execution of a Java application. Examples include properties files (which can be used to initialize java.util.Properties objects), XML files or other application input. This little piece of code will take the root file name (myProperties.properties) for example, and search for it in the Java application class path.
/** Given a file name, attempt to find the file name in the class path. If the file name is found, return the absolute path on the local file system. If the file is not found in the class path, return null. @param filename the file name for the resource */ private String getPathForResource( String filename ) { ClassLoader loader = this.getClass().getClassLoader(); URL url = loader.getResource( filename ); String path = null; if (url != null) { path = url.getFile(); } return path; } // getPathForResource
Read a resource file into a String
This came up in an application that sends emails from the Java code. The application needs to read an HTML template, which is used to construct the email.
The resource file can be included a jar by adding it to the class path when the jar is built. However, a normal file path cannot be used. Instead the getResourceAsStream() is used to read it from the jar.
/** * Read a resource file that is either in the class directory or in a resources directory. * Because this uses getResourcesAsStream() it can be used to read a file that is included * in a .jar file. * * @param fileName * @return the contents of the file as a String * @throws IOException */ public String resourceFileToString(final String fileName) throws IOException { ClassLoader loader = this.getClass().getClassLoader(); URL url = loader.getResource( fileName ); InputStream istream = null; if (url != null) { istream = loader.getResourceAsStream( fileName ); } else { String filePath = "resources/" + fileName; url = loader.getResource( filePath ); if (url != null) { istream = loader.getResourceAsStream( filePath ); } } String fileData = null; if (istream != null) { fileData = inputStreamToString( istream ); } return fileData; }
Ian Kaplan, February 12, 2000
Updated: January 2015