January 25, 2010

Intro to XPath

Helpful XPath syntax reference from W3

Sample code based loosely on this Java2S example:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParserAlpha
{
private static final String SOURCE = "C:/someFolder/xmlFile.xml";
private static final String EXPR = "*";

public static void main(String[] args)
{
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = EXPR;
InputSource inputSource = new InputSource(SOURCE);

NodeList nodes = null;
int j = -1;
try
{
nodes = (NodeList) xpath.evaluate(xpathExpression, inputSource, XPathConstants.NODESET);
// NODESET maps to interface org.w3c.dom.NodeList
j = nodes.getLength();

for (int i = 0; i < j; i++) { System.out.println(nodes.item(i).getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } } }


Other values of EXPR and what they're good for:
/Report/PublicationMetadata/DescriptiveMetadata/Title/@* - All attribute values of the title element (but not the attribute names)

TODO: FINISH POST

January 13, 2010

Intro to working with XML using Java

Rob Lybarger wrote a great intro article about this, the link skips to page two of five: Working with XML and Java

Syntactic sugar

Syntactic sugar on Wikipedia

"[Syntactic sugar is] syntax designed to make things easier to read or to express, while alternative ways of expressing them exist. It makes the language 'sweeter' for humans to use...." -Wikipedia

January 7, 2010

Array index behavior in Java

int indexFor1D = 3;
int indexFor2D = 1;
int [] array1D = { 5, 6, 7, 8, 9 };
int [][] array2D = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};

System.out.println("From 2D: " + array2D[indexFor2D++][indexFor2D++]);
System.out.println("indexFor2D: " + indexFor2D);

array1D[indexFor1D++] = indexFor1D;
System.out.println("indexFor1D: " + indexFor1D);
System.out.print("New 1D: ");
for(int tmp : array1D)
System.out.print(tmp);


produces output

From 2D: 5
indexFor2D: 3
indexFor1D: 4
New 1D: 56749

Nerd Sniping or: Finally Always Wins, Unless You Crash The Machine Beforehand.

try {
return true;
} finally {
return false;
}


http://stackoverflow.com/questions/1995113/strangest-language-feature/2005435#2005435

January 6, 2010

Rules for bits in Java

All integer literals are, by default, ints in Java. All floating point literals are, by default, doubles. If a value larger than allowed is put into a given primitive type, the leftmost bits are discarded. So,

char c = (char) 65656; // Binary 00000000000000010000000001111000
byte i = (byte) 130; // Binary 00000000000000000000000010000010

A char is 16 bits, so it is set to 0000000001111000, which equals 1111000, which is 120, which in turn is the character 'z'; a byte is eight bits, so it is set to 10000010. Since the first bit is a sign bit, this actually equals -126. (By two's complement, 10000010 = -(01111101 + 1) = -(01111110) = -126.)

Division by zero in Java

Incredibly, the following code will compile without any problems:


int x = 7/0;
System.out.println(x);

int y = 0;
int z = 7/y;
System.out.println(z);


When the inevitable runtime error occurs, it appears as an ArithmeticException; there is no such thing as DivideByZeroException.

January 5, 2010

Increment and decrement for array indices in Java

This code


int anIndex = 1;
int [][] anArray = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
System.out.println("Number: " + anArray[anIndex++][anIndex++] + ".");


prints out "Number: 5." That's anArray[1][2]; anIndex is incremented after each index, so it ends up at 3 by the end of the code fragment.

Concatenation to strings in Java


System.out.println("" + 1 + 2);
System.out.println(1 + "" + 2);
System.out.println(1 + 2 + "");


results in

12
12
3

Java instanceof operator

instanceof checks true runtime values. So, the following code would print:


Object o = new LinkedList();
if(o instanceof LinkedList)
System.out.println("yep");


This is not the same behavior as method lookup (find the fancy name for this). This example would produce an error:


List theList = new Queue();
theList.enqueue(new Object());

Class initialization in Java

"Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down." -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)

Class loading time is the same as initialization time, which is described right at the top of section 12.4 of the Java Language Specification.

What happens if more than one class contains static init blocks? Are static init blocks guaranteed to run? My question at Stack Overflow covers these questions.

What about multiple instances of a class? As expected, the static initialization blocks do NOT run again. Modifying main() from the link above to this:


System.out.println("START");
new Child();
System.out.println("MIDDLE");
new Child();
System.out.println("END");


produces this output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
MIDDLE
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END

Initialization blocks in Java

Code:

public class LoadTest
{
public static void main(String[] args)
{
System.out.println("START");
new Child();
System.out.println("END");
}
}

class Parent extends Grandparent {
// Instance init block
{
System.out.println("instance - parent");
}

// Constructor
public Parent() {
System.out.println("constructor - parent");
}

// Static init block
static {
System.out.println("static - parent");
}
}

class Grandparent {
// Static init block
static {
System.out.println("static - grandparent");
}

// Instance init block
{
System.out.println("instance - grandparent");
}

// Constructor
public Grandparent() {
System.out.println("constructor - grandparent");
}
}

class Child extends Parent {
// Constructor
public Child() {
System.out.println("constructor - child");
}

// Static init block
static {
System.out.println("static - child");
}

// Instance init block
{
System.out.println("instance - child");
}
}


Output:
START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END

Generic methods in Java


public static void main(String[] args) {
genericMethod("abc");
}

static void overloadedMethod(Object o) {
System.out.println("overloadedMethod(Object) called");
}

static void overloadedMethod(String s) {
System.out.println("overloadedMethod(String) called");
}

static void overloadedMethod(Integer i) {
System.out.println("overloadedMethod(Integer) called");
}

static <T> void genericMethod(T t) {
overloadedMethod(t);
}


produces output "overloadedMethod(Object) called"; this is because the generic method doesn't know what kind of argument will be passed in at compile time [DBL-CHECK REASON]

Characters in Java

A char in Java is technically just an unsigned 16-bit number. The following code works just fine...


// 65656 - 1 - 120 = 65535, the max 16-bit unsigned range
char crazyChar = (char) 65656;
System.out.println("(char) 65656: " + crazyChar);


... and produces output "(char) 65656: x" (the ASCII/Unicode value for x is 120).

This is also perfectly legal, if not meaningful:

char crazierChar = (char) -552;

Note that casts are required for both of these snippets.

Default initialization in Java

In Java, class variables get initialized to default values. This code...

public class Test {
private static String _string;
private static byte _byte;
private static short _short;
private static int _int;
private static long _long;
private static float _float;
private static double _double;
private static boolean _boolean;
private static char _char;

public static void main(String[] args) {
System.out.println("str " + _string);
System.out.println("byt " + _byte);
System.out.println("sht " + _short);
System.out.println("int " + _int);
System.out.println("lng " + _long);
System.out.println("flt " + _float);
System.out.println("dbl " + _double);
System.out.println("bln " + _boolean);
System.out.println("chr " + _char);
}
}


...produces this output...

str null
byt 0
sht 0
int 0
lng 0
flt 0.0
dbl 0.0
bln false
chr [the non-printable character U+0000]

Unlike class variables, method-local variables are NOT automatically initialized. This code will produce a compile-time error ("the local variable anotherInt may not have been initialized"):

int anotherInt;
System.out.println(anotherInt);


On the other hand, the compiler won't catch non-initialized class objects; this code, after the earlier snippet, compiles just fine but will cause a NullPointerException at runtime:

if ("impossible".equals(_string)) {
int x = 5;
}

January 3, 2010

TweakUI

Microsoft has a somewhat famous PowerToy for Windows XP called TweakUI. It allows users to play with several user interface settings that are built into XP but aren't easily accessible out of the box. It's available at

http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx

Turns out there's an equivalent tool for Windows Vista and 7 — though not an official Microsoft product — available at

http://www.thewindowsclub.com/ultimate-windows-tweaker-v2-a-tweak-ui-for-windows-7-vista#more-1957

The Quake 3 fast inverse square root function

http://www.beyond3d.com/content/articles/8/

Programming fonts

http://www.codinghorror.com/blog/archives/000157.html