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)
| 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)
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;
if (intVal > 127) {
int temp = intVal - 256;
byteVal = (byte)temp;
}
else {
byteVal = (byte)intVal;
}
return byteVal;
}
"or, of course do a bitwise AND with 0xFF...."
Use a JSlider component.
JSlider(int orientation, int minValue, int maxValue, int initialValue)
where orientation is either JSlider.HORIZONTAL or JSlider.VERTICAL
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
"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/
See: Mastering the Java Classpath - http://www.kevinboone.com/classpath.html
| 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 | -215 (-32,768) |
+215-1 (32,767) |
Short |
| int | 32-bit | -231 (-2,147,483,648) |
+231-1 (2,147,483,647) |
Integer |
| long | 64-bit | -263 (-9,223,372,036,854,775,808) |
+263-1 (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
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
// 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
"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/
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
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
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
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 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
"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
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
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
From: http://www.rgagnon.com/javadetails/java-0029.html
"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)
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
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
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
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
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
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
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
| 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
// Standard string array initialization syntax
String array1[] = new String[]{"Zero", "One", "Two"};
// More concise syntax that only works in initializers (constructors, static blocks)
String array2[] = {"Zero", "One", "Three"};
// Syntax allocating the array as an array of null objects
String array3[] = new String[3];
// which can be later filled in with values
array3[0] = "Zero"; array3[1] = "One"; array3[2] = "Two";