List the available system roots in Java

Use the method listRoots in the File class. Notice that this is filesystem dependent. On Unix, there is only one system root: “/”. On Windows, it depends on drives that are mapped.
Here’s an example:

Main.java:

import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      File[] roots = File.listRoots();
      for (int i=0; i<roots.length; i++) {
         System.out.println(roots[i]);
      }
   }
}

outputs on my machine:

A:
C:
D:
E:

Determining what formats are supported by ImageIO

ImageIO is extensible. You can add third party plug-ins for other image formats than the standard ones.

Main.java:

import javax.imageio.*;
 
public class Main
{
   public static void main(String []args) {
      String[] formatNames = ImageIO.getReaderFormatNames();
 
      for (int i=0; i<formatNames.length; i++) {
         System.out.println(formatNames[i]);
      }
   }
}

outputs:

png
jpeg
JPEG
gif
jpg
JPG

Example of using clone()

Implement the Cloneable interface and call super.clone() if to make a bit-by-bit shallow copy. A shallow copy implies that only the references are duplicated in the new object and not the referents. This means that changing a referent in your original object has also an effect on the destination object. To prevent this from happening, you need to make a deep copy, that is manually creating duplicates for the members you don’t want to have shared. If all of your classes implement the Serializable marker interface, you can also make a deep copy by serializing using ObjectOutputStream and deserialize it using ObjectInputStream.
Look what happens in the two following examples.

Shallow copy

Main.java:

public class Main {
   public static void main(String args[]) {
      A a1 = new A();            // create an instance of A
      A a2 = (A) a1.clone();     // shallow-copy clone
 
      a1.sb.append(", world!");  // change the stringbuffer member of the first object
 
      System.out.println(a1);
      System.out.println(a2);    // not that the second object has also changed!
   }
}
 
class A implements Cloneable
{
   public StringBuffer sb = new StringBuffer("Hello");
 
   public String toString() {
      return sb.toString();
   }
 
   public Object clone() {
      try {
         return super.clone();
      } 
      catch(CloneNotSupportedException e) { }
 
      return null;
   }
}

outputs:

Hello, world!
Hello, world!

Deep copy

Main.java:

public class Main {
   public static void main(String args[]) {
      A a1 = new A();            // create an instance of A
      A a2 = (A) a1.clone();     // deep-copy clone
 
      a1.sb.append(", world!");  // change the stringbuffer member of the first object
      System.out.println(a1);
      System.out.println(a2);    // not that the second object has not changed now!
   }
}
 
class A implements Cloneable
{
   public StringBuffer sb = new StringBuffer("Hello");
 
   public String toString() {
      return sb.toString();
   }
 
   public Object clone() {
      try {
         A a = (A) super.clone();
         a.sb = new StringBuffer(sb.toString());
         return a;
      } 
      catch(CloneNotSupportedException e) { }
 
      return null;
   }
}

outputs:

Hello, world!
Hello

For more information on cloning an on whether you should catch the CloneNotSupportedException or specify a throws clause, see the link below.

Fast copying an array

There is a fast native method available in the java.lang.System class: arraycopy().
It can be used to copy a region of one array to another. If an array of objects
is copied, only the references are copied. arraycopy() does not allocate memory
for the destination array. Make sure you have allocated enough memory for the
destination array to hold the copied region.

This is its signature:
arraycopy(Object src, int srcOffset, Object dst, int dstOffset, int count)

Following example demonstrates the use:

public class Main
{
   public static void main(String []args) {
      int [] src = { 1, 2, 3, 4, 5, 6, 7, 8 };
      int [] dst = { 0, 0, 0, 0, 0, 0, 0, 0 };
 
      System.arraycopy(src, 2, dst, 1, 3);
   
      printArray(src);
      printArray(dst); 
   }
 
   public static void printArray(int []array) {
      for (int i=0; i<array.length; i++) {
         System.out.print(array[i] + " ");
      }
      System.out.println();
   }
}

outputs:

1 2 3 4 5 6 7 8 
0 3 4 5 0 0 0 0 

Returning a localized Exception

Throwable has a method called getLocalizedMessage, designed so that you can return a message in a language different than the standard getMessage language. By default, getLocalizedMessage returns the same as getMessage, but when you subclass Exception, you can provide your own implementation and preferably look up the localized message using a ResourceBundle.

This example introduces a Download class designed such that it can only handle the HTTP protocol. If it’s not, it will throw our exception DownloadProtocolException. The exception is caught and the message is printed both in the default locale language and a dutch one.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      try {
         Download d = new Download("ftp://microsoft.com/download/ie5.exe");
         d.start();
      }
      catch(DownloadProtocolException e) {
         System.out.println(e.getMessage());
         System.out.println(e.getLocalizedMessage(new Locale("nl", "BE")));
      }    
   }
}
 
class Download
{
   String url;
 
   public Download(String url) throws DownloadProtocolException {
      if (!url.startsWith("http://")) {
         throw new DownloadProtocolException(url);
      }
   }
 
   public void start() {
      // . . .
   }
}
 
class DownloadProtocolException extends Exception {
   private String url;
 
   public DownloadProtocolException(String url) {
      this.url = url;
   }
 
   public String getMessage() {
      return getLocalizedMessage(Locale.getDefault());
   }
   
   public String getLocalizedMessage(Locale locale) {
      ResourceBundle rb = ResourceBundle.getBundle("ErrorMessages", locale);
      return rb.getString("DownloadProtocolException") + ": " + url;
   }
}

ErrorMessages.properties:

DownloadProtocolException=Wrong protocol (only supports HTTP protocol)

ErrorMessages_nl_BE.properties:

DownloadProtocolException=Fout protocol (ondersteund slechts HTTP protocol)

Make sure these .properties can be found through a path in the classpath.

Running the app outputs:

Wrong protocol (only supports HTTP protocol): ftp://microsoft.com/download/ie5.exe
Fout protocol (ondersteund slechts HTTP protocol): ftp://microsoft.com/download/ie5.exe

Executing a method using reflection

The following example shows you how to. First get a Method instance using the getMethod method executed on any Class object of the class containing that method. Make sure you specify the correct method name and parameter list to uniquely identify the method. Then call invoke on that method instance and specify the object instance on which you want to execute that method and specify the parameters (wrap primitive types in their equivalent object types).

If you want to execute a static method, you don’t need to specify an object instance, it is ignored anyway (use null).
Main.java:

import java.lang.reflect.*;
  
public class Main {
   public static void main(String args[]) {
      MyClass myClass = new MyClass();
      MyClass.MyInnerClass myInnerClass = myClass.new MyInnerClass();
 
      try {
         Method m1 = MyClass.class.getMethod("myMethod", new Class[] { int.class });
         Object ret1 = m1.invoke(myClass, new Object[] { new Integer(1) });
         System.out.println("Returned: " + ret1);
 
         Method m2 = MyClass.class.getMethod("myStaticMethod", new Class[] { });
         Object ret2 = m2.invoke(null, new Object[] { });
 
         Method m3 = MyClass.MyInnerClass.class.getMethod("myInnerMethod", new Class[] { });
        
         Object ret3 = m3.invoke(myInnerClass, new Object[] { });
      }
      catch(NoSuchMethodException e) {
         e.printStackTrace();
      }
      catch(IllegalAccessException e) {
         e.printStackTrace();
      }
      catch(InvocationTargetException e) {
         e.printStackTrace();
      }
   }
}
 
class MyClass
{
   public int myMethod(int n) {
      System.out.println("Dynamically invoked myMethod passing: " + n);
      return n + 10;
   }
 
   public static void myStaticMethod() {
      System.out.println("Dynamically invoked myStaticMethod");
   }
 
   class MyInnerClass {
      public void myInnerMethod() {
         System.out.println("Dynamically invoked myInnerMethod");
      }
   }
}

outputs:

Dynamically invoked myMethod passing: 1
Returned: 11
Dynamically invoked myStaticMethod
Dynamically invoked myInnerMethod

Executing a DOS command from Java

Here’s an example I created on my Win2000 machine.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String[] args) throws IOException {
      if (args.length != 1) {
         System.out.println("Usage: java Main "doscmd"");
         System.exit(1);
      }
 
      ArrayList arrayList = new ArrayList();
      int exitValue = executeCmd(args[0], arrayList);
 
      System.out.println("Exit value is " + exitValue);
      System.out.println();
      for (int i=0; i<arrayList.size(); i++) {
         System.out.println("Line " + i + ":t" + arrayList.get(i));
      }
   }
 
   public static int executeCmd(String command, ArrayList arrayList) throws IOException {
      Process process = Runtime.getRuntime().exec("cmd /c " + command);
      InputStreamReader isr = new InputStreamReader(process.getInputStream());
      BufferedReader br = new BufferedReader(isr);
 
      String line;
      while ((line = br.readLine()) != null) {
         arrayList.add(line);
      }
 
      try {
         process.waitFor();
      }
      catch (InterruptedException e) {
      }
      br.close();
    
      return process.exitValue();
   }
}

Example run:

C:myruntime>java Main "dir /w"
Exit value is 0
 
Line 0:  Volume in drive C has no label.
Line 1:  Volume Serial Number is E4D8-7443
Line 2:
Line 3:  Directory of C:myruntime
Line 4:
Line 5: [.]          [..]         Main.class   Main.java
Line 6:                2 File(s)          2,958 bytes
Line 7:                2 Dir(s)   1,925,675,008 bytes free

Difference between String a=”a” and String a=new(“a”)

I’m assuming you mean “what’s the difference between
String a = “a”;
and
String a = new String(“a”);
The simple answer is that in the 2nd case an extra,
unnecessary String object is created. The reason for that is
that even string literals in Java are instances of class
String, so what happens in the 2nd case is that a string
literal “a” is created and then another String object with
a copy of the same value is created.
The complicated answer is that there is another difference.
All Java string literals are saved by the compiler directly
into the class file, the JVM then reads the class file
and creates instances of class String for all the string
literals in the class file. All these instances are saved in
a special internal pool of Strings inside the String class.
What does this mean? It means that if you do:

String a = "a";
String b = "a";

Then both a and b will reference the SAME object (so a==b is
true). But if you do this:

String a = "a";
String b = new String("a");

Then a and b will reference different String objects (both
strings will have the same value, but they will be 2 strings,
not one like in the first case).

You can add a String into the internal pool by invoking the
intern() method on a String. That method creates a new string
with the same value (if none exists in the pool already),
adds it to the pool and returns it.

Determining the Unicode category for a particular character

Try the static method Character.getType.

Main.java:

public class Main {
   public static void main(String args[]) {
      System.out.println(Character.getType('D'));
      System.out.println(Character.getType(' '));
      System.out.println(Character.getType(')'));
      System.out.println(Character.getType('1'));
      System.out.println(Character.getType('-'));
   }
}

outputs:

1	(UPPERCASE_LETTER)
12	(SPACE_SEPARATOR)
22	(END_PUNCTUATION)
9	(DECIMAL_DIGIT_NUMBER)
20	(DASH_PUNCTUATION)

What does the strictfp keyword do?

The keyword strictfp allows you to have more (predictable) control over floating-point arithmetic. It may be used (as a modifier) to classes, interfaces and methods. If a floating point expression is within a strictfp “scope”, the results will be as predictable as described in IEEE 754 (see link below). If the expression is not FP-strict, the specification is more tolerant and the result is determined by the extra precision bits that may be used in evaluating the expression (extended exponent range implemented by the VM being used).
Check out the other link below (Changes to the Java Language Specification).