Java Code Snippets & Hints

General Java Syntax Cheat Sheets:

See: http://mindprod.com/jgloss/jcheat.html (Java Syntax Cheat Sheet)
See: http://java.sun.com/j2se/1.5.0/docs/api/constant-values.html (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: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html (link no longer valid)

Unsigned Bytes:

to save a byte value in a C++ compatible format...to 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

see: http://java.sun.com/docs/books/tutorial/uiswing/components/slider.html

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 {
        ImageIO.write(image,fileType,f);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        JOptionPane.showMessageDialog(null,ioe,"Error",JOptionPane.ERROR_MESSAGE);
    }

from: http://forums.sun.com/thread.jspa?threadID=496947&messageID=2358958

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."

see: http://java.sun.com/developer/technicalArticles/Programming/sprintf/

Java Classpath

See: Mastering the Java Classpath - http://www.kevinboone.com/classpath.html

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

from: http://www.idevelopment.info/data/Programming/java/miscellaneous_java/Java_Primitive_Types.html

Packages

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 "

See: http://jarticles.com/package/package_eng.html

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;
}

from: http://www.mindprod.com/jgloss/conversion.html

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"

See: http://www.devarticles.com/c/a/Java/Listeners-in-Java/1/

Enumerations:

Java 1.5+ solution:

enum Season { WINTER, SPRING, SUMMER, FALL };

(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) {
    this.name = name;
  }
  public static final MyEnum WINTER = new MyEnum("winter");
  public static final MyEnum SPRING = new MyEnum("spring");

  public String toString() {
    return name;
  }
}

See: http://mindprod.com/jgloss/enum.html
See: http://java.sun.com/javase/6/docs/technotes/guides/language/enums.html
See: http://java.sun.com/developer/technicalArticles/releases/j2se15langfeat/index.html

Files & Directories

Select Directory using JFileChooser:

    JFileChooser chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle( "Select Directory" );
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    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 */ }

From: http://www.rgagnon.com/javadetails/java-0370.html

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();
    }
};

See: http://www.exampledepot.com/egs/java.io/GetFiles.html
See: http://javaalmanac.com/egs/java.io/GetFiles.html

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

From: http://javaboutique.internet.com/tutorials/Files_Directories/

InvokeLater

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

See: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

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"

From: http://mindprod.com/jgloss/thread.html

Text Box with Formatting

public class StyledField extends JTextPane {
    private Style m_CurrentAttributes;
    

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

    public StyledField(String text) {
        this();
        setText(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);
    	StyleConstants.setBold(m_CurrentAttributes, 
    	    ((Attributes & Font.BOLD) != 0));
    	StyleConstants.setItalic(m_CurrentAttributes, 
    	    ((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) {
            }
        }
    }
}

From: http://www.lordjoe.com/SwingCourse/StyledText/StyledText.html

Redirecting a Stack Trace to a String:

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

From: http://www.rgagnon.com/javadetails/java-0029.html

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;
static 
{
   sine = new double[360];
   for (int angle = 0 ; angle < sine.length ; angle++) {
      sine[angle] = Math.sin((angle * Math.PI)/180.0);
   }
}

From: http://www.ftponline.com/javapro/2003_04/online/tricks_pford_04_10_03 (link no longer valid)

The Reflection API

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

See: http://java.sun.com/docs/books/tutorial/reflect/index.html

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

From: http://www.coderanch.com/t/376256/Java-General-intermediate/java/get-Class-primitive-datatypes-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(", "); }
    }
    sb.append("]");
    return sb.toString();
    }
}

From: http://www.codeproject.com/KB/string/ArrayToString.aspx

Unsigned Byte Buffers

import java.nio.ByteBuffer;

/**
 * From code by Ron Hitchens (ron@ronsoft.com)
 */
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);

        buffer.clear();
        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)));
    }
}

From: http://www.javanio.info/filearea/bookexamples/unpacked/com/ronsoft/books/nio/buffers/Unsigned.java

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

From: http://www.exampledepot.com/egs/java.nio/TypeBuf.html 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:

From: http://justmonkey.biz/2005/06/javaone_notes_achieving_great.html

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

From: http://www.cs.umd.edu/~pugh/SV-JUG-2009.pdf

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) { ... }

from: http://www.exampledepot.com/egs/java.text/Percent.html

Creating a Custom Table Cell Editor

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

from: http://www.exampledepot.com/egs/javax.swing.table/CustEdit.html

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

from: http://www.cafeaulait.org/course/week2/03.html

 

[Return to Resources]