Wednesday, August 30, 2006

Java Basic Lexical Elements - Keywords and Reserved Words

Keywords and reserved words cannot be used as identifiers. They are shown here in informal groupings.
  • access modifiers - private, protected, public
  • other modifiers - abstract, final, native, static, synchronized, transient, volatile
  • flow control - break, case, continue, default, do, else, for, if, return, while, switch
  • exceptions - catch, finally, throw, throws, try
  • declarations - class, extends, implements, interface, void, strictfp
  • name space - import, package
  • primitive types - boolean, byte, char, double, float, int, long, short
  • boolean literals - false, true
  • null literal - null
  • reserved but not used - const, goto
  • object related - instanceof, new, this, super
Added in 1.4 and 5.0 are assert and enum. You can read more about assert at http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html and enum at http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html.

Try not Create Extra String Objects

When a Java compiler encounters a string literal, it scans all the strings in its current cache for another String object with the same literal value and, if it exists, reuses the object. If the string does not already exist, the compiler creates a new String object to hold the literal value and places it in a pool.

String myFirst = "A literal";
String mySecond = "A literal";

Here myFirst and mySecond are two different references to one String object.

If you use the new keyword each time you create a string, a new string object will be created every time, even if you use the same literal value.

String myFirst = new String("A literal");
String mySecond = new String("A literal");

Here myFirst and mySecond are references to two different objects.

So creating strings without using the new keyword can prevent you from needlessly creating extra String objects.

Tuesday, August 29, 2006

Java Primitive Types

  • boolean - 1 bit - [true, false]
  • char - 16 bits - [\u0000, \uffff] inclusive
  • byte - 8 bits - [-128, 127] inclusive
  • short - 16 bits - [-32768, 32767] inclusive
  • int - 32 bits - [-2^31, 2^31 - 1] inclusive
  • long - 64 bits - [-2^63, 2^63 - 1] inclusive
  • float - 32 bits
  • double - 64 bits
Note:
  • boolean is the only boolean type, others are all numeric types.
  • char is one of the integral types. A char literal should be enclosed in a pair of single quotes.
  • float and double are the floating-point types. NaN stands for Not a Number, NEGATIVE_INFINITY and POSITIVE_INFINITY for mathematical infinity.
  • default values for boolean is false, for char, \u0000, for integers, 0, for floating-points, 0.0.
  • float aFloat = 802.649F is correct, float aFloat = 802.649 is wrong.