Using the tool jconsole in JDK1.5

The JMX compliant tool jconsole comes with JDK1.5. It allows to manage the VM, check the memory usage of the different memory managers, monitor the thread usage, see how many classes are loaded, etc.

The simplest way to use jconsole is to start up the Java application a JMX agent:

   java -Dcom.sun.management.jmxremote Main

Then, specify the process ID of the Java application when starting up jconsole:

   c:j2sdk1.5.0binjconsole <pid>

To find out the process ID, you can use the ps command on UNIX and the Task Manager on Windows.

There is a workaround to quickly find out the process ID. This following Java application prints out its own process ID and then infinitely starts creating threads that on their turn fill up the memory by creating a number of arrays.

Main.java:

import java.util.*;
import java.lang.reflect.*;
import java.lang.management.*;
 
public class Main
{
   public static void main(String []args) {
      try {
         System.out.println("Process-id: " + getProcessId());
      }
      catch(Exception e) { }
    
      while (true) {
         new Thread(new Task()).start();
          
         try { Thread.sleep(500); } catch(InterruptedException e) { }
      }
   }
    
   public static int getProcessId() throws Exception {
      // next line to trigger loading of library
      ManagementFactory.getThreadMXBean();
       
      Class c = Class.forName("sun.management.VMManagementImpl");
         
      Constructor constructor = c.getDeclaredConstructor(new Class[] { });
      constructor.setAccessible(true);
      Object impl = constructor.newInstance(new Object[] { });
       
      Method m = c.getDeclaredMethod("getProcessId", new Class[] { });
      m.setAccessible(true);
      Object result = m.invoke(impl, new Object[] { });
      
      return (Integer) result;
   }   
}
 
class Task implements Runnable
{
   public void run() {
      Vector<byte[]> v = new Vector<byte[]>();
      while (true) {
         v.add(new byte[10000]);
          
         try { Thread.sleep(100); } catch(InterruptedException e) { }
      }
   }
}

outputs:

Process-id: 2492
... (fills up heap space and eventually throws an OutOfMemoryException)

Then start up the jconsole from the command-line as follows:

   c:j2sdk1.5.0binjconsole 2492

Remote Management

You can also remotely connect. Passwords can be specified and SSL can be enabled (both are default). To start up the Java application without passwords and with SSL disabled, execute this:

java -Dcom.sun.management.jmxremote.port=1097 -Dcom.sun.management.jmxremote.ssl=false 
                                              -Dcom.sun.management.jmxremote.authenticate=false Main

Then, when jconsole starts up specify the host name and port to connect.

You can also use SSL and passwords and roles (like readonly, readwrite). Check the jconsole documentation to do so.

Getting the dimensions of a text in Swing

This example shows you how to center a text on the JFrame. It will take into account the specifics of the chosen font. Run it from command line like java Main Helvetica.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   private String fontname;
   private String text = "Easter Island";
 
   public Main(String fontname) {
      this.fontname = fontname;
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   } 

   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
      Font f = new Font(fontname, Font.BOLD, 36);
      FontMetrics fm = getFontMetrics(f);
 
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      int width = getSize().width;
      int height = getSize().height;
 
      g2d.setColor(Color.gray);
      g2d.drawLine(0, height/2, width, height/2);
      g2d.drawLine(width/2, 0, width/2, height);
 
      g2d.setColor(Color.black);
      g2d.setFont(f);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);
   }
  
   public static void main(String []args) {
      if (args.length == 0) {
         System.err.println("Usage: java Main <fontname>");
         System.exit(1);
      }
 
      Main main = new Main(args[0]);
      main.setVisible(true);
      main.setSize(300, 300);
   }
}

Skipping part of an InputStream when reading from it

You can do so using the method skip. You can call this method from any point where you are in the inputstream.

The following program skips half of the file, where the filename is supplied at command line.

Main.java:

import java.io.*;
  
public class Main {
   public static void main(String args[]) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
         System.exit(1);
      }
 
      File file = new File(args[0]);
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
 
      int half = (int) file.length() / 2;
      bis.skip(half);
 
      int b;
      while ((b = bis.read()) > 0) {
         System.out.print((char) b);
      } 
   }
}

Writing a file in UTF-8 encoding using a Writer

You can specify the encoding UTF-8 with OutputStreamWriter. This class will convert the outgoing Unicode to UTF-8 bytes.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("test.utf"), "UTF8");
         BufferedWriter bw = new BufferedWriter(osw);
         bw.write("hu0000ello");
         bw.close();
      }
      catch(FileNotFoundException e) {
         System.out.println(e);
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}

Tell how much free space is on disk in Java

Unfortunately, there is no API or method to find out, not even in JDK 1.3. Check out BUG 4057701 in Sun’s Bug Parade. Until this bug is fixed, you can try out to execute an external command like dir (Windows) or du (unix) and parse the output:

import java.util.*;
import java.text.*;
import java.io.*;
  
public class Main
{
   public static void main(String [] args) throws Exception {
      long fs = getFreeSpace("c:");
 
      System.out.println("Free space: " + fs);
   }
 
   public static long getFreeSpace(String dir) throws Exception {
      String osname = System.getProperty("os.name");
      String command = "";
      if (osname.indexOf("NT") > -1)
         command = "c:\winnt\cmd.com";
      else if (osname.indexOf("Windows") > -1)
         command = "c:\windows\command.com";
 
      Process p = Runtime.getRuntime().exec(command + " /c dir " + dir + " > c:\dir.txt");
      p.waitFor(); 
 
      File f = new File("c:\dir.txt");
      BufferedReader br = new BufferedReader(new FileReader(f));
      String line;
      String totalBytes = "";
      while ((line = br.readLine()) != null) {
         if (line.indexOf("bytes free") > -1) {
            int start = line.indexOf("dir(s)") + 7;
            int end = line.indexOf("bytes free", start);
            totalBytes = line.substring(start, end).trim();
            break;
         }
      }
 
      br.close();
      f.delete();
 
      return NumberFormat.getInstance().parse(totalBytes).longValue(); 
   }
}

This code needs to be adapted to be language and platform independent!

Detecting if the right button was clicked in Swing

To determine whether a right mouse click button was clicked or not, write code in the mouseClicked function of the mouseListener Interface.

   class MyMouseListener extends MouseAdapter
   {
      public void mouseClicked(MouseEvent me)
      {
         if ((me.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
            // right mouse clicked......   
         }
      }
   };
 
   /* getModifiers() gives constant modifier for a particular click();
      BUTTON3_MASK is constant modifier for the right moouse click */

Getting a list of packages that have been loaded

Main.java:

public class Main
{
   public static void main(String []args) {
      Package[] packages = Package.getPackages();
      for (int i=0; i<packages.length; i++) {
         System.out.println(packages[i]);
      }
   }
}

prints out:

package java.util.zip, Java Platform API Specification, version 1.3
package java.security, Java Platform API Specification, version 1.3
package java.io, Java Platform API Specification, version 1.3
package sun.net.www.protocol.file, Java Platform API Specification, version 1.3
package sun.net.www.protocol.jar, Java Platform API Specification, version 1.3
package sun.net.www, Java Platform API Specification, version 1.3
package java.util.jar, Java Platform API Specification, version 1.3
package sun.security.action, Java Platform API Specification, version 1.3
package java.lang, Java Platform API Specification, version 1.3
package sun.io, Java Platform API Specification, version 1.3
package java.util, Java Platform API Specification, version 1.3
package sun.misc, Java Platform API Specification, version 1.3
package java.security.cert, Java Platform API Specification, version 1.3
package java.lang.reflect, Java Platform API Specification, version 1.3
package java.net, Java Platform API Specification, version 1.3
package sun.security.util, Java Platform API Specification, version 1.3
package java.lang.ref, Java Platform API Specification, version 1.3
package sun.security.provider, Java Platform API Specification, version 1.3
package com.sun.rsajca

Converting a hexadecimal (hex), octal, or binary value to an integer

Use the static method parseInt in the Integer primitive wrapper class. You pass in a string containing the digits of the specified radix. If a digit is not in the radix range, you’ll get a NumberFormatException.

Here’s an example:

public class Main
{
   public static void main(String args[]) {      
      // convert from hexadecimal                
      int a = Integer.parseInt("FF1C", 16);
  
      // convert from octal
      int b = Integer.parseInt("107", 8);
 
      // convert from binary
      int c = Integer.parseInt("10010", 2);
 
      System.out.println(a);   // 65308
      System.out.println(b);   // 71
      System.out.println(c);   // 18
   }
}

Randomly shuffling an array

Take two random numbers between 0 and the length of the array (bounds inclusive) and swap the values.

This example shows you a method that can take an array of any type and just swaps references around.

Main.java:

import java.util.*;
import java.io.*;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  
      System.out.print("Before:nt");
      printArray(arr);
 
      shuffleArray(arr); 
 
      System.out.print("After:nt");
      printArray(arr);
   }
  
   public static void printArray(int []arr) { 
      for (int i=0; i<arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }
 
   public static void shuffleArray(Object arr) {
      Random r = new Random();
      for (int i=0; i<100; i++) {
         int r1 = Math.abs(r.nextInt() % 10);
         int r2 = Math.abs(r.nextInt() % 10);
         Object el0 = Array.get(arr, r1);
         Object el1 = Array.get(arr, r2);
         Array.set(arr, r2, el0);
         Array.set(arr, r1, el1);
      }
   }
}

outputs:

Before:
	0 1 2 3 4 5 6 7 8 9 
After:
	1 4 7 3 5 9 6 2 8 0 

Difference between reflection and introspection

Reflection allows you to inspect an object to find out the member field variables, methods and constructors.
Introspection is a subset of reflection. Through the special class java.beans.Introspector, it identifies which JavaBean properties (characteristics) an object has and uses the reflection package for that.