Java: Difference between revisions

From miki
Jump to navigation Jump to search
(→‎How-To: Generate a string of repeating characters)
Line 177: Line 177:
* Since Java 1.5, one should prefer using <code>StringBuilder</code> over <code>StringBuffer</code>.
* Since Java 1.5, one should prefer using <code>StringBuilder</code> over <code>StringBuffer</code>.
* rosettacode.org contains more code snippets for any language ([http://rosettacode.org/wiki/Repeat_a_string#Java])
* rosettacode.org contains more code snippets for any language ([http://rosettacode.org/wiki/Repeat_a_string#Java])

== Patterns ==
=== Singleton ===
* [http://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.html 10 Interview questions on Singleton Pattern in Java]
* [http://java.sun.com/developer/technicalArticles/Programming/singletons/ When is a Singleton not a Singleton?]
* [http://www.javabeginner.com/learn-java/java-singleton-design-pattern Java Singleton Design Pattern]
* [http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html Implementing the Singleton Pattern in Java]
* [http://java.sun.com/docs/books/effective/ Effective Java]

A ''Singleton'' is a design pattern that guarantees that there can be at most one instance of a given class in a VM. The objective is controlling object creation, in this case limiting it to one.

Advantage of ''Singleton'' over a class with only static members:
* Static methods cannot implements an interface. Singleton can be used to implements an interface (&rarr; very handy for Provider frameworks).
* Static methods cannot be overridden (aka. they are de-facto ''final'').
* it is not difficult to initialize the Singleton based on run-time information.

Remember that the main objective of singleton is to limit instance of created objects. So there is nothing inherently bad at referring to static members in public methods of the Singleton, as long as these members remains private.

'''Frequent caveats''':
* Multi-instance because lack of synchronization in multi-threaded environment.
:The best solution is to rely on static initialization. In that case, object is created as soon as class is referenced or needed.
<source lang="java">
// Normal static initialization (not lazy)
private static final Foo foo = new Foo();
public static Foo getFoo() {
return foo;
}
</source>
:Using the ''initialize-on-demand holder class'' is only useful is there are cases where one would refer to the class but not uses the singleton. For instance, the <tt>System</tt> class has several singletons, but one rarely needs them all at once, and so it makes sense to only create them on demand. If that's not the case, rely on static initialization.


== Debug ==
== Debug ==

Revision as of 14:38, 9 November 2011

Other pages

Links

java.exe Command-Line

-Djava.library.path=<dllpath>
Set path to find DLL Libraries
-jar <jarfile>
Set jar file to load (should contain main())
java -Djava.library.path=.\var -jar "$(MYROOT)\var\main.jar"

Sample Program

  • Create a file HelloWorld.java, with content:
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
    for (int i = 0; i < args.length; i++)
      System.out.print(0 == i ? args[i] : " " + args[i]);
    System.out.println();
  }
}
  • Compile (javac must be in the path):
javac HelloWorld.java
  • Run:
java HelloWorld

Syntax 1.4

Arrays

  • Index is 0-based
  • Array base type can be any primitive type or reference types.
  • new allocates room for primitive types, or for references (not for object instance themselves).
  • After creation, arrays cannot grow or shrink. For dynamic arrays, consider using ArrayList class.
// Declaration
int [] arrayOfInts;                                // preferred declaration style
int arrayOfInts [];                                // ... c-style

// Creation and Initialization
int arrayOfInts [] = new int [42];                 // declaration and creation (set to 0)
arrayOfInts[0] = 69;

String [] someStrings = new String [ 3 ];          // ... idem (set to null)
String [] someStrings = { null, null, null };      // ... same as above
String [] someStrings = { "hello", new String(), someStuff.toString(), null };

// Anonymous arrays
setPets ( new Animal [] { new Dog("gray"), new Cat("grey"), new Cat("orange") });

// Get array length
int aLen = arrayOfInts.length

Syntax 1.5

For loops

Foreach loops (available since 1.5) [1]:

  • More readable
  • Series of values
  • Arrays and Collections
  • Applies to Iterable<E>.

But

  • Only access.
  • Only single structure.
  • Only single element.
  • Only forward.
  • At least Java 5.
FOR EACH loop Equivalent FOR loop
for (type var : arr) {
    body-of-loop
}
for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
for (type var : coll) {
    body-of-loop
}
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}

Miscellaneous

Class Literal
A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
Eg:
public class MyClass //...
//...
printf ("Class name is %s\n",MyClass.class.getName());
Throwable.getStackTrace()
Could be used to get the name of current class / methods for debug...

How-To

Generate a string of repeating characters

On Java 1.4.2:

  String repeatchar(char c, int len)
  {
    char [] a = new char[len];
    Arrays.fill(a, c);
    return new String(a);
  } /* repeatchar */

Other pointers:

Pad a string

On Java 1.4.2 (see [2]):

  public static String padString(String s, int n, char c, boolean padLeft)
  {
    if ( null == s ) {
      return null;
    }

    int  npad = n - s.length();
    if ( npad < 0 ) {
      return s;
    }

    char [] pad = new char [npad];
    Arrays.fill(pad, c);
    return ( padLeft ) ? new String(pad) + s : s + new String(pad);  // TODO: Faster to use StringBuffer, and insert/append?
  } /* padString */

On Java 1.5, use String.format:

public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}

public static String padLeft(String s, int n) {
    return String.format("%1$#" + n + "s", s);  
}

Other pointers:

  • For formatting numbers, use java.text.DecimalFormat (see [3])
  • Since Java 1.5, one should prefer using StringBuilder over StringBuffer.
  • rosettacode.org contains more code snippets for any language ([4])

Patterns

Singleton

A Singleton is a design pattern that guarantees that there can be at most one instance of a given class in a VM. The objective is controlling object creation, in this case limiting it to one.

Advantage of Singleton over a class with only static members:

  • Static methods cannot implements an interface. Singleton can be used to implements an interface (→ very handy for Provider frameworks).
  • Static methods cannot be overridden (aka. they are de-facto final).
  • it is not difficult to initialize the Singleton based on run-time information.

Remember that the main objective of singleton is to limit instance of created objects. So there is nothing inherently bad at referring to static members in public methods of the Singleton, as long as these members remains private.

Frequent caveats:

  • Multi-instance because lack of synchronization in multi-threaded environment.
The best solution is to rely on static initialization. In that case, object is created as soon as class is referenced or needed.
// Normal static initialization (not lazy)
private static final Foo foo = new Foo(); 
public static Foo getFoo() { 
    return foo; 
}
Using the initialize-on-demand holder class is only useful is there are cases where one would refer to the class but not uses the singleton. For instance, the System class has several singletons, but one rarely needs them all at once, and so it makes sense to only create them on demand. If that's not the case, rely on static initialization.

Debug

References

Logging:

Dynamic Proxy:

Java Trace
Profilers
Aspect-Oriented Programming


Some sample code:

  private static final String ANSI_PURPLE = (char) 27 + "[35m";
  private static final String ANSI_NONE   = (char) 27 + "[0m";

  public static String getMethodName()
  {
    return getMethodName(1);
  }

  public static String getMethodName(int idx)
  {
    return new Throwable().getStackTrace()[1].getMethodName();
  }

  public static String getFileMethodLine()
  {
    return getFileMethodLine(1);
  }

  public static String getFileMethodLine(int idx)
  {
    StackTraceElement e = new Throwable().getStackTrace()[idx];

    //return e.getClassName() + "." + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")";    // Java like
    return e.getFileName() + " " + e.getMethodName() + ":" + e.getLineNumber();                                   // C like
  }

  public static void debug(String s)
  {
    System.out.println(ANSI_PURPLE + getFileMethodLine(2) + ANSI_NONE + " " + s);
  }

References

String Integer.toHexString(byte);                    // Convert an integer to string in hexadecimal

"00" + Integer.toHexString( i )                      // Pad with leading zeros (then take rightmost characters)

String.format("%04x",0x2a);

//Prepend 0 if needed
String hex = Integer.toHexString(abyte & 0xff);
StringBuffer hexbuf = new StringBuffer();
if (hex.length() == 1) hexbuf.append('0');
hexbuf.append(hex);

//Prepend 0 if needed
String hex=Integer.toHexString(aInt);                  // Assume 0<= aInt <= 255 (i.e. positive!)
System.out.print((hex.length()>1? "" : "0") + hex + ", ");