Java Code Snippets & Hints

General Java Syntax Cheat Sheets:

See: (Java Syntax Cheat Sheet)
See: (Constants in Java 1.5)

Synchronization and Threading

Moved to Threading Page.

Bit Shifting:

Operator Use Operation
>> op1 >> op2 shift bits of op1 right by distance op2
<< op1 << op2 shift bits of op1 left by distance op2
>>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)

from: (link no longer valid)

Unsigned Bytes:

to save a byte value in a C++ compatible work around Java's lack of support for unsigned types:

public static byte toUnsignedByte(int intVal) {
	byte byteVal;
	return (byte)(intVal & 0xFF);
Another option:
public static byte toUnsignedByte(int intVal) {
	byte byteVal;
	if (intVal > 127) {
		int temp = intVal - 256;
		byteVal = (byte)temp;
	else {
		byteVal = (byte)intVal;
	return byteVal;

Sliders in Java:

Use a JSlider component.

JSlider(int orientation, int minValue, int maxValue, int initialValue)
where orientation is either JSlider.HORIZONTAL or JSlider.VERTICAL


Save a screen capture of a Java Frame/Panel/Window:

Essentially the trick is to draw the panel/frame/etc. into a BufferedImage and use the ImageIO class to write it to an image file.

    BufferedImage image = ...
    System.out.println("image " + image);
    File f = ...
    String fileType = f.getName().substring(f.getName().lastIndexOf('.') + 1);
    try {
    } catch (IOException ioe) {


Sprintf for Java

"While not a perfect replica of the C language sprintf utility, the PrintfFormat class should be helpful in converting a code from C to Java. Users are encouraged, however, to use the java.text classes for formatting data because those have regular maintenance and are a much better path towards internationalizing your software than PrintfFormat."


Java Classpath

See: Mastering the Java Classpath -

Java Primitive Type Capacities:

Primitive Type Size Minimum Value Maximum Value Wrapper Type
char   16-bit     Unicode 0   Unicode 216-1   Character
byte   8-bit     -128   +127   Byte
short   16-bit   -32,768 32,767   Short
int   32-bit   -2,147,483,648 2,147,483,647   Integer
long   64-bit   -9,223,372,036,854,775,808 9,223,372,036,854,775,807   Long
float   32-bit     32-bit IEEE 754 floating-point numbers   Float
double   64-bit     64-bit IEEE 754 floating-point numbers   Double
boolean   1-bit     true or false   Boolean
void   -----     -----     -----     Void



Reasons we usue packages:

"One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class."

"The fully-qualified class name is the name of the java class that includes its package name "


Zero-padding Integers:

// converts integer to left-zero padded string, len chars long.
public static String toLZ( int i, int len ) {
     String s = Integer.toString(i);
     if ( s.length() > len ) return s.substring(0,len);
     else if ( s.length() < len ) // pad on left with zeros
	     return "000000000000000000000000000".substring(0, len - s.length ()) s;
     else return s;


Closing Dependent Windows:

"Because the main window is a multi-document interface it needs to be the “parent” of all windows created. For this reason a dependent window should not create another window itself but inform the main window and let it do so. Creating a listener is the best solution to this problem"



Java 1.5+ solution:


(Simple) Kludge for 1.4 and before (use int constants):

public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;

Problems with the kludge way: This is not type-safe (its just an int, you can do stupid things with it), provides no namespace to prevention of collision with other constants, printed values are not obvious (numeric not string).

(Advanced) Kludge for 1.4 - "type safe enum pattern":

public class MyEnum {
  private final String name;
  private MyEnum(String name) { = name;
  public static final MyEnum WINTER = new MyEnum("winter");
  public static final MyEnum SPRING = new MyEnum("spring");

  public String toString() {
    return name;


Files & Directories

Select Directory using JFileChooser:

    JFileChooser chooser = new JFileChooser(); 
    chooser.setDialogTitle( "Select Directory" );
    chooser.setAcceptAllFileFilterUsed(false); // disable the "All files" option.
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
        System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
        System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else { /* ignore if user presses cancel */ }


Listing the Files or Subdirectories in a Directory

File dir = new File("directoryName");
  String[] children = dir.list(); //can also take a FilenameFilter as argument
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
    public boolean accept(File file) {
        return file.isDirectory();


Working with Files & Directories:

String userdir = System.getProperty("user.dir");

Several methods are available for inspecting an instance of the File class. Some of the important ones are:

Method Purpose
boolean exists() does the file exist?
boolean isFile() is it a file?
boolean isDirectory() … or a directory?
String[] list() return the names of all files and directories in a directory
String getName() get the file or directory's name
String getPath() get the file or directory's path



invokeLater makes a method return immediately and run the time consuming code at java's leisure. This page also had a handy list of guidelines for when you would want to thread your execution


Swing Thread

"You can't directly meddle with Swing components, or their backing data models from a second thread. The contract is, if you want to do anything to a Swing component that could have any effect on it's display from an application thread (not the EventDispatchThread itself), you should add it to the event dispatch thread's queue via SwingUtilities.invokeLater( Runnable ) or SwingUtilities.invokeAndWait( Runnable ) so that it will be done on the same thread that Swing itself uses"


Text Box with Formatting

public class StyledField extends JTextPane {
    private Style m_CurrentAttributes;

    public StyledField() {
	      m_CurrentAttributes = getStyle(StyleContext.DEFAULT_STYLE);

    public StyledField(String text) {

    public void setCurrentColor(Color in) {
        StyleConstants.setForeground(m_CurrentAttributes, in);

    // Attributes - Font.BOLD or Font.ITALIC
    public void setCurrentFont(String Family, int ptSize, int Attributes) {
      StyleConstants.setFontFamily(m_CurrentAttributes, Family);
      StyleConstants.setFontSize(m_CurrentAttributes, ptSize);
    	    ((Attributes & Font.BOLD) != 0));
    	    ((Attributes & Font.ITALIC) != 0));
    public void setCurrentBold(boolean doit) {
        StyleConstants.setBold(m_CurrentAttributes, doit);

    public void setCurrentItalic(boolean doit) {
       StyleConstants.setItalic(m_CurrentAttributes, doit);
    public void insert(String str, int pos) {
        Document doc = getDocument();
        if (doc != null) {
            try {
                doc.insertString(pos, str, m_CurrentAttributes);
            } catch (BadLocationException e) {
                throw new IllegalArgumentException(e.getMessage());
    public void append(String str) {
        Document doc = getDocument();
        if (doc != null) {
            try {
                doc.insertString(doc.getLength(), str, m_CurrentAttributes);
            } catch (BadLocationException e) {


Redirecting a Stack Trace to a String:

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
return sw.toString();


Static Initializers

"a static initializer, which is a block of code—rather like a static method—that is executed once only, when the class is loaded. It can't be called under any other circumstances, so it doesn't have a name, arguments, or any access modifiers, and does not return a value."

public final static double[] sine;
   sine = new double[360];
   for (int angle = 0 ; angle < sine.length ; angle++) {
      sine[angle] = Math.sin((angle * Math.PI)/180.0);

From: (link no longer valid)

The Reflection API

Class c = Class.forName("com.duke.MyLocaleServiceProvider");
Class c = javax.swing.JButton.class.getSuperclass();


Obscure way to get Class object for primitive arrays using reflection: (don't do this)
Instead of int[].class someone might say Class.forName(
These mean:
[B for byte array
[I for int array
[F for float array


Generic Array To String Function

public static String arrayToString(Object array) {
    if (array == null) { return "[NULL]"; }
    Object obj = null;
    if (array instanceof Hashtable) { array = ((Hashtable)array).entrySet().toArray(); }     
	else if (array instanceof HashSet) { array = ((HashSet)array).toArray(); } 
    else if (array instanceof Collection) { array = ((Collection)array).toArray(); }
	int length = Array.getLength(array);
    int lastItem = length - 1;
    StringBuffer sb = new StringBuffer("[");
    for (int i = 0; i < length; i++) {
        obj = Array.get(array, i);
        if (obj != null) { sb.append(obj); } else { sb.append("[NULL]"); }
        if (i < lastItem) { sb.append(", "); }
    return sb.toString();


Unsigned Byte Buffers

import java.nio.ByteBuffer;

 * From code by Ron Hitchens (
public class Unsigned

    public static short getUnsignedByte (ByteBuffer bb) {
        return ((short)(bb.get() & 0xff));
    public static void putUnsignedByte (ByteBuffer bb, int value) {
        bb.put ((byte)(value & 0xff));
    public static short getUnsignedByte (ByteBuffer bb, int position) {
        return ((short)(bb.get (position) & (short)0xff));
    public static void putUnsignedByte (ByteBuffer bb, int position, int value) {
        bb.put (position, (byte)(value & 0xff));
    public static int getUnsignedShort (ByteBuffer bb) {
        return (bb.getShort() & 0xffff);
    public static void putUnsignedShort (ByteBuffer bb, int value) {
        bb.putShort ((short)(value & 0xffff));
    public static int getUnsignedShort (ByteBuffer bb, int position) {
        return (bb.getShort (position) & 0xffff);
    public static void putUnsignedShort (ByteBuffer bb, int position, int value) {
        bb.putShort (position, (short)(value & 0xffff));
    public static long getUnsignedInt (ByteBuffer bb) {
        return ((long)bb.getInt() & 0xffffffffL);
    public static void putUnsignedInt (ByteBuffer bb, long value) {
        bb.putInt ((int)(value & 0xffffffffL));
    public static long getUnsignedInt (ByteBuffer bb, int position) {
        return ((long)bb.getInt (position) & 0xffffffffL);
    public static void putUnsignedInt (ByteBuffer bb, int position, long value) {
        bb.putInt (position, (int)(value & 0xffffffffL));

    public static void main (String [] argv) throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate (20);

        Unsigned.putUnsignedByte (buffer, 255);
        Unsigned.putUnsignedByte (buffer, 128);
        Unsigned.putUnsignedShort (buffer, 0xcafe);
        Unsigned.putUnsignedInt (buffer, 0xcafebabe);

        for (int i = 0; i < 8; i++) {
            System.out.println ("" + i + ": "
                + Integer.toHexString ((int)getUnsignedByte (buffer, i)));

        System.out.println ("2: " + Integer.toHexString (getUnsignedShort (buffer, 2)));
        System.out.println ("4: " + Long.toHexString (getUnsignedInt (buffer, 4)));


    ByteBuffer buf = ByteBuffer.allocate(15);
    IntBuffer ibuf = buf.asIntBuffer();

From: Creating a Non-Byte Java Type Buffer on a ByteBuffer

File I/O Performance

Exerpted from notes by "ryan" from JavaOne conference presentation on File I/Oby a presenter from BEA:


Finding Bugs

Running [code] analysis [such as FindBugs] and finding obviously stupid code is easy. Need to budget time for more than just running the analysis and reviewing the bugs. Often, the hard part is stuff like:
• Figuring out who is responsible for that code
• Understanding what the code is actually supposed to do
• Figuring out if stupid code can cause the application to misbehave
• Writing a test case that demonstrates the bug
• Getting approval to change the code


Formatting Locale-Specific Percentages

    Locale locale = Locale.CANADA; // Format
    String string = NumberFormat.getPercentInstance(locale).format(123.45); // 12,345%

    try { // Parse
        Number number = NumberFormat.getPercentInstance(locale).parse("123.45%"); // 1.2345
        if (number instanceof Long) { /* Long */ } else { /* Double */ }
    } catch (ParseException e) { ... }


Creating a Custom Table Cell Editor

    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    col.setCellEditor(new MyTableCellEditor());
    public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor { ... }


Operators in Java

Operator Purpose
+ addition of numbers, concatenation of Strings
+= add and assign numbers, concatenate and assign Strings
- subtraction
-= subtract and assign
* multiplication
*= multiply and assign
/ division
/= divide and assign
% take remainder
%= take remainder and assign
++ increment by one
-- decrement by one
> greater than
>= greater than or equal to
< less than
<= less than or equal to
! boolean NOT
!= not equal to
&& boolean AND
|| boolean OR
== boolean equals
= assignment
~ bitwise NOT
?: conditional
instanceof type checking
| bitwise OR
|= bitwise OR and assign
^ bitwise XOR
^= bitwise XOR and assign
& bitwise AND
&= bitwise AND and assign
>> shift bits right with sign extension
>>= shift bits right with sign extension and assign
<< shift bits left
<<= shift bits left and assign
>>> unsigned bit shift right
>>>= unsigned bit shift right and assign



[Return to Resources]